Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to validate many to many field objects before insert into database in django model
I have model "cart" and it has a many to many field named "products". I wanna check if there is a product in products that is not active, prevent from creating the cart object class Product(models.Model): price = models.PositiveIntegerField(blank=True) active = models.BooleanField(default=True) objects = ProductQuerySet.as_manager() class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="cart") products = models.ManyToManyField(Product, blank=True) subtotal = models.IntegerField(default=0, blank=True) objects = CartManager.as_manager() -
Update Post clicking on a button: Django
Hope someone can help me! I'm pretty sure that there's a little error I can't detect. In my website I've got a list of items with an update button. Once i click on the button I keep having this error about the url: Reverse for 'edit_info' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['search/(?P<slug>[-\\w]+)/edit/$'] Am I missing something maybe on the urls.py file? Here's the code, Thanks a lot! views.py def edit_info(request, slug): instance = get_object_or_404(Info, slug=slug) if request.method == 'POST': form = InfoForm(request.POST, instance=obj) if form.is_valid(): instance = form.save(commit=False) instance.utente = request.user instance.save() return render(request, 'search/user.html') else: form = InfoForm(instance=obj) template = 'search/option.html' context = {'form': form} return render (request, template, context) urls.py urlpatterns = [ path('', homeView.as_view(), name='home'), path('option/', views.AddInfo, name='option'), path('delete/<int:id>', views.DeleteInfo, name='delete'), re_path(r'^search/(?P<slug>[-\w]+)/edit/$', views.edit_info, name='edit_info'), path('signup/', core_views.signup, name='signup'), path('user/', userListView.as_view(), name='user'), path('searches/', searchesView.as_view(), name='searches'), ] template html: <div class="info_band"> <!-- insert table info --> <table> <tr><th><h3>{{o.band}}</h3></th></tr> <tr><td> Anno: </td><td> {{o.anno}} </td></tr> <tr><td> Disco: </td><td> {{o.disco}} </td></tr> <tr><td> Etichetta: </td><td> {{o.etichetta_d}} </td></tr> <tr><td> Matrice: </td><td> {{o.matrice}} </td></tr> </table> </div> <div class="mod"> <table> <tr> <td> <a href="{% url 'edit_info' slug=instance.slug %}"><button type="button" class=" btn btn-default"> Update </button></a> </td> </tr> <tr> <td> <button>Delete</button> </td> </tr> </table> … -
For nginx, am I listening to port 443 or port 3000 for this url https://localhost:3000?
I am trying to navigate through the weeds of nginx and reverse proxy passing and one area that I am getting confused on is the port mappings. Here is an example nginx configuration file: server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name www.domain.com; passenger_enabled on; root /home/ubuntu/app/public; include snippets/self-signed.conf; include snippets/ssl-params.conf; } What I am specifying here is that my app should listen to port 443 because it has a self signed certificate on it. It won't accept port 80 http but only 443. Here is an example I found about proxy_passing to localhost. Which is what I want to do. Here is the example: server { listen 443; server_name localhost; ssl on; ssl_certificate server.crt; ssl_certificate_key server.key; ssl_session_timeout 5m; ssl_protocols SSLv2 SSLv3 TLSv1; ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; ssl_prefer_server_ciphers on; location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Client-Verify SUCCESS; proxy_set_header X-Client-DN $ssl_client_s_dn; proxy_set_header X-SSL-Subject $ssl_client_s_dn; proxy_set_header X-SSL-Issuer $ssl_client_i_dn; proxy_read_timeout 1800; proxy_connect_timeout 1800; } } Here is what I don't understand and could use some clarification. What port/url am I listening to in the second example? In the server block I see this: listen 443; server_name localhost; That means we are … -
Keeping track of non registered user in a django website
I'm making a django website and want to keep record of the people who didn't registered in my website like what all they searched in my website and all.For that what should I do to get all that information?? -
Dajngo: refreshing page resubmit last form
I have a view like: def some_view(request, page_url): form = UserTicketForm(request.POST) if request.method == 'POST': if form.is_valid(): first_name = request.POST.get('first_name') ticket_text = request.POST.get('ticket_text') data = dict( form=UserTicketForm, ) return render(request, 'front/some_page.html', data) and in HTML page it has: {% csrf_token %} {% bootstrap_form form %} {% block submit %} <div class="button_holder"> <button type="submit" name="register-submit" class="btn btn-primary" value="send"> submit </button> </div> {% endblock %} each time I refresh the page, it resubmits the last submitted form. how can fix this issue? -
Adding Items to cart
whenever am trying to add items to cart it is not showing in cart.No errors are there template also working fine but http://127.0.0.1:8000/admin/ecom/orderitem/ in this items are not showing. I am trying to solve this from three days but it is not working. This is views from django.shortcuts import render, get_object_or_404, redirect from .models import Item, Checkout, Order, Orderitem from django.urls import reverse_lazy from django.views.generic import DetailView, ListView from django.views.generic.edit import CreateView class CheckoutEditView( CreateView ) : model = Checkout template_name = 'checkedit.html' fields = '__all__' success_url = reverse_lazy('blank') def item_list(request): context = { 'items':Item.objects.all() } return render(request,'item_list.html',context) class CheckListView(ListView): model = Checkout template_name = 'blank.html' def check2(request): return render(request,'ckeck2.html') def front(request): return render(request,'front.html') def blank(request): return render(request,'blank.html') def product(request): return render(request,'product-page.html') def checkout(request): return render(request,'checkout-page.html') def home(request): return render(request,'home.html') class ArticleDetailView(DetailView): model = Item template_name = 'home.html' context_object_name = 'batman' def home_page(request): return render(request,'home-page.html') def add_to_cart(request,slug): item = get_object_or_404(Item,slug=slug) order_item = Orderitem.objects.create(item=item) order_qs = Order.objects.filter(user=request.user,ordered = False) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.quantity +=1 order_item.save() else: order = Order.objects.create(user=request.user) order.items.add(order_item) return redirect("core:article_page",slug=slug) whenever am trying to add items to cart it is not showing in cart.No errors are there template also working fine but http://127.0.0.1:8000/admin/ecom/orderitem/ in this … -
Permission issue in custom user model in django
I am trying to create a custom user model in my Django application. In my app user_app i have added the below code in my models.py : from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class RestrauntManager(BaseUserManager): def create_user(self, username, email, phone, restraunt_name, is_staff=False, is_admin=False, is_active=True, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have a username') if not password: raise ValueError('User must have a password') if not phone: raise ValueError('User must have a phone number') if not restraunt_name: raise ValueError('User must have a restraunt name') user = self.model( email = self.normalize_email(email), username = username, phone = phone, restraunt_name = restraunt_name ) user.set_password(password) user.staff = is_staff user.active = is_active user.admin = is_admin user.save(using=self._db) return user def create_staffuser(self, email, username, phone, restraunt_name, password=None): user = self.create_user( email = self.normalize_email(email), username = username, phone = phone, restraunt_name = restraunt_name, is_staff = True ) return user def create_superuser(self, email, username, phone, restraunt_name, password=None): user = self.create_user( email = self.normalize_email(email), username = username, phone = phone, restraunt_name = restraunt_name, password = password, is_staff = True, is_admin = True ) user.save(using=self._db) return user class Restraunt(PermissionsMixin, AbstractBaseUser): email = models.EmailField(verbose_name = 'email', max_length=60, unique=True) username … -
Read a select option on Django
I am attempting to get the value of the data from the select option which will actively decide what will be displayed on the same page. I need to get the child.id value and was wondering if there is a way to find this data without having to create a whole new page. <select id="child"> {% for cl in children %} {% if cl.parent == user %} <option value="{{child.id}}">{{ cl.first_name }} {{ cl.last_name }}</option> {% endif %} {% endfor %} </select> -
ajax call to submit data form in django RESTFRAMEWORK
I am trying to make a POST request to Mayan EDMS(a Django app to store documents), through an API to upload a document, but each time I try to submit the form I get a permission denied error. here is an HTML form with a file field and other fields, HTML form <form method="POST" id="DocForm" enctype="multipart/form-data"> {% csrf_token %} <textarea name="description"></textarea> <input type="file" /> <select class="form-control" name="document_type"> <option value="1">Default</option> </select> <button>POST</button> </form> this function get csrf token from a form ajax/js code to get csrf token ////getting crsf token /////////////////////////////////// // function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } function sameOrigin(url) { // test that a given url is a same-origin URL // url could be relative or scheme relative or absolute var host = document.location.host; // host … -
Django rest framework, imitate the Django admin behavior when using Foreign Key
I have a Django rest framework API model that contains a foreign key field. I want to show the user In the browsable API a kind of dropdown menu to choose existing objects or create a new one just like in the admin interface, Is there something like this existing? The models: class Mission(models.Model): id = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) mission_name = models.CharField(name='MissionName', verbose_name="Mission Name", unique=True, max_length=255, blank=False, help_text="Enter the mission's name", primary_key=True ) uav_lat = models.FloatField(name="UavLatitude", verbose_name="UAV Latitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) uav_lon = models.FloatField(name="UavLongitude", verbose_name="UAV Longitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) uav_elevation = models.FloatField(name="UavElevation", verbose_name="UAV Elevation", max_length=100, default=1, blank=False, help_text="Enter the above ~Sea Level~ planned uav Elevation. " ) area = models.CharField( name='Area', max_length=8, choices=AREAS, ) date_added = models.DateTimeField(verbose_name="Date Added", default=now()) gdt = models.ForeignKey(KnownLocation, on_delete=models.PROTECT) class Meta: get_latest_by = 'date_added' KnownLocation model: class KnownLocation(models.Model): name = models.CharField(name="Name", unique=False, primary_key=True, max_length=150, blank=False, help_text="Enter the name of the location's name") area = models.CharField(name='Area', max_length=8, choices=AREAS, ) date_added = models.DateTimeField(default=timezone.now) latitude = models.FloatField(name="Latitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) longitude = models.FloatField(name="Longitude", unique=True, max_length=255, blank=False, … -
Django REST serializer with multiple foreign keys
Hi everybody and good morning. My application is a sort of 'repository manager', able to list, search and create datasets of files. I have a models.py like the following: class Author(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) email = models.EmailField() phone = models.CharField(max_length=20, blank=True) # optional def __str__(self): return self.name class Dataset(models.Model): name = models.CharField(max_length=150) # dataset title description = models.TextField(blank=True) # dataset description --> optional slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) remote = models.URLField(max_length=300) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(str(self.author.pk) + "-" + str(self.name)) super(Dataset, self).save(*args, **kwargs) class File(models.Model): creator = models.ForeignKey(Author, related_name='author', on_delete=models.CASCADE) # the original creator of the file dataset = models.ForeignKey(Dataset, related_name='dataset', on_delete=models.CASCADE) # dataset to which belongs name = models.CharField(max_length=100) # file name with path description = models.CharField(max_length=300, blank=True) # file description --> optional url = models.URLField(max_length=300) # hot link to file def __str__(self): return self.name So I am working with nested serializers. The creation of an object Dataset is working in this way: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('name', 'surname', 'email', 'phone') class FileSerializer(serializers.ModelSerializer): creator = AuthorSerializer(required=False) class Meta: model = File fields = ('name', 'description', 'url', 'creator') class DatasetSerializer(serializers.ModelSerializer): author = AuthorSerializer() … -
How to chain custom methods of subclass of Django QuerySet so that types match
Consider following example code: class MyQuerySet(models.QuerySet): def my_method(self): return self.annotate(_something=47) def my_method_2(self): return self.annotate(_something2=42) def second_method(self): return self.my_method().my_method2() Problem is that PyCharms type checker highlights my_method2() call ("Unresolved attribute reference 'my_method2' for class 'QuerySet'"). I could disable warning inside IDE on case-by-case basis, but type-checker is right, types do not match. (I don't even understand why such code works, I suppose methods like filter and annotate preserve these attributes.) Is there some clean way to change returned values to MyQuerySet? Or are there any type hints that would make type-checker happy? (Setting return type of my_method to MyQuerySet only moves the problem.) -
Importing external library (say pytube) in Django
Fairly new to Django. I am trying to import Pytube to my django project. I am on my virtual environment and installed pytube va Pip. How to I import it. not working the way like 'from Pytube import Youtube' -
How to filter queryset data with exact matching word?
I am creating one Django project, here I define some fields like: class Data1(models.Model): message = models.TextField() and making input word in msg variable msg = "hello" I want to filter all message field strings in which the msg variable exists. when I am using list_data = Data1.objects.filter(message__icontains=msg).all() it's not giving me desire output is there any way to filter query objects with exact word match in strings. -
App linking to root instead of actual application on redirect
I'm having some trouble working with paths in Django. I have python experience but not Django experience at all. Here is what I have templates/AppName/base.html <header id="header"> <div id="logo"> <div id="top_menu"> Home | Calendar | About | <a href="/contactus">Contact Us</a> </div> </div> </header> template/AppName/contact_us.html {% extends 'Orchestrator/base.html' %} {% block content %} <h2>New post</h2> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} AppName/urls.py from django.urls import path from . import views app_name = 'AppName' urlpatterns = [ path('', views.index, name='index'), path('contactus/', views.contact_us, name='contactus') ] AppName/views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from .forms import ContactUs def index(request): return render(request, 'AppName/base.html') # Forms # def contact_us(request): form = ContactUs() return render(request, 'AppName/contact_us.html', {'form': form}) AppName/forms.py from django import forms class ContactUs(forms.Form): firstname = forms.CharField(max_length=100) lastname = forms.CharField(max_length=100) So, the rendering of the starting page, meaning 127.0.0.1:8000/AppName Works just fine, but when I want to make the Contact Us button redirect to AppName/contactus, Django is actually redirecting to 127.0.0.1/contactus. Any idea on how to solve this? -
How do I filter query objects (DecimalFIeld) by value range in Django?
I've a Django model with a DecimalField. class SomeModel(models.Model): decimal_field = models.DecimalField() I'd like to get all model instances which have a field value in the range of e.g. 5.0 and 10.0. I've read the Django docs section about queries but I did not find a solution. How do I have to write the query SomeModel.objects.filter(?) ? -
Django Compare ManyToMany fields
Let's say I have a model: patients = models.ManyToManyField(Patient) patients_tracker = models.ManyToManyField(Patient, blank=True, editable=False, related_name="patient_tracker") ... Now, in my overridden save function, I set both of them equal to each other. By doing: self.patients_tracker.set(self.patients.all()) #----Statement a but in my post_save function, this statement if instance.patients_tracker.all() != instance.patients.all(): #----Statement b for some reason returns False even though I checked manually and print(instance.patients_tracker.all()) & print("Here's the patients: ", instance.patients.all()) return the same Patients in them which only tells me that "Statement a" worked perfectly. But why doesn't "Statement b" work and return true? What am I doing wrong? Thank you for reading this. -
Receive django error debug report by email :
Here is my configuration in django settings : MAILER_LIST = ['toto@toto.com'] EMAIL_HOST = 'toto.smtp.com' EMAIL_HOST_USER = 'toto@toto.com' EMAIL_HOST_PASSWORD = 'tata' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'toto@toto.com' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'DEBUG', 'class': 'django.utils.log.AdminEmailHandler', 'filters': [], } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'DEBUG', 'propagate': True, }, } } i've try to debug with : from django.core.mail import EmailMessage email = EmailMessage('Hello', 'World', to=['toto@toto.com']) email.send() And i get the test email if i put this in my settings. i would like to receive this error report by email : What am i missing to get the debug log by email ? The test is sending the email so it's not an email configuration problem ... Thanks and regards -
django datatables | filter the queryset python 3
I am trying to query on jquery datatables list. Right now I can fetch all records from the table, but i want to fetch records to whom their parent id matches. e-g users have posts, so in my case it would be fetch posts where user id is lets say 1. So I am trying to implement same thing for jquery datatables. I can see data is being posted but I cant figure out how to query along with datatables, so that datatables filters are not affected by this change. My current code: class PartRequestViewSet(CommonViewset, generics.RetrieveAPIView): queryset = PartRequest.objects.filter(deleted_at=None) serializer_class = PartRequestSerializer def list(self, request, *args, **kwargs): records = request.GET.get('records', None) # ID of the part part_number_id = request.GET.get('part_number_id', None) queryset = self.get_queryset() queryset = self.filter_queryset(queryset) page = self.paginate_queryset(queryset) if page is not None and records is None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Now in above code I can get the part_number_id from request, but how can I filter records using filter_queryset(), so that only parts_requests are given back in datatables where part_number_id is 1 Update: current helper function filter_queryset that is used in above code. def filter_queryset(self, queryset): format = self.request.GET.get('format', None) … -
testing stripe on-boarding django with mock
i am having trouble trying to mock test the on-boarding process of stripe connect. I am just learning how to use mock and i am struggling with the StripeAuthorizeCallbackView. the process is as follows: A user reaches the StripeAuthorizeView which sends them to the stripe api to sign up for an account. Once they successfully sign up for an account their redirected back to my platform and stripe sends a temporary code which i then send back to stripe with my api keys. Once i have sent the information back to stripe they then return me credentials for the user being the stripe_user_id. Here is the two views in question: import urllib import requests class StripeAuthorizeView(LoginRequiredMixin, View): def get(self, request): url = 'https://connect.stripe.com/express/oauth/authorize?' user = self.request.user if user.account_type == 'Business': business_type = 'company' else: business_type = 'individual' params = { 'response_type': 'code', 'scope': 'read_write', 'client_id': settings.STRIPE_CONNECT_CLIENT_ID, 'redirect_uri': f'http://127.0.0.1:8000/accounts/stripe/oauth/callback', 'stripe_user[email]' : user.email, 'stripe_user[business_type]' : business_type, 'stripe_user[url]' : 'http://127.0.0.1:8000/accounts/user/%s/' %user.pk, } url = f'{url}?{urllib.parse.urlencode(params)}' return redirect(url) lass StripeAuthorizeCallbackView(LoginRequiredMixin, View): def get(self, request): code = request.GET.get('code') if code: data = { 'client_secret': settings.STRIPE_SECRET_KEY, 'grant_type': 'authorization_code', 'client_id': settings.STRIPE_CONNECT_CLIENT_ID, 'code': code } url = 'https://connect.stripe.com/oauth/token' resp = requests.post(url, params=data) stripe_user_id = resp.json()['stripe_user_id'] stripe_access_token = resp.json()['access_token'] … -
Generate div in django template according to logic in template tag
I would like to generate different types of html code according to logic/conditions I check in template tags. E.g. if a text from a Model contains a '!' in front of a word, the word should be bold. What is the best way to do something like this in django? I want to avoid to create too much conditional html code in the templates. -
How to do a form with a list of check items in Django, with the check box on the left?
I am converting a simple checkbox list to a Django form. Here is a the checkbox survey: <input type="checkbox"><label>I like bourbon.</label><br> <input type="checkbox"><label>I like whisky.</label><br> <input type="checkbox"><label>I like beer.</label><br> Of course George Thorogood would chose all three. My grandma would chose none of them. Django doesn't have a checkbox field, and I read that I should use a BooleanField. This is the form code: class Form_BoissonSurvey(forms.Form): c0 = forms.BooleanField(required=False, label='I like bourbon.'); c1 = forms.BooleanField(required=False, label='I like whisky.'); c2 = forms.BooleanField(required=False, label='I like beer.'); And rendered it in a template.html form as: {{ form_boisson_survey.as_p }} But it looks like this: I have spent beaucoup time trying to get the check boxes to the left side, and to get it to separate without the big spaces inbetween. How can I get the check boxes on the left and get the lines to be separated by br instead of p ?? I.e. to get this to look like a normal list of three things of which any number of them may be selected? -
django OperationalError
i start to learn django and i want to crate models the first one work and then i want to make another and i go to the admin panel and this happen[https://i.stack.imgur.com/rg8oO.png] can somone help me with that[https://i.stack.imgur.com/7Da01.png] [https://i.stack.imgur.com/SGEiX.png] -
Guzzle http and Laravel Http post method replace with get method
I create guzzle client using post method but it replaced to get method. I try to use Illuminate\Support\Facades\Http on Laravel 7.x but get the same error. The API server is Django Rest Framework. see Illuminate\Support\Facades\Http doc at : https://laravel.com/docs/7.x/http-client#request-data Http::withHeaders([ 'Authorization' => "" ])->post('http://domain.id/api/v1/test', [ "parameter" => "value", ]); Result using Laravel Illuminate\Support\Facades\Http The method is GET instead of POST -
Obtain the last "n" values from my model from all my devices
I want to obtain the last values of my different devices from my data model. If I want the last one I'm using, dev_data = DevData.objects.order_by('dev_id','-data_timestamp').distinct('dev_id') But I don't know how to obtain the last "n" values of each one (not just the last one). I tried this, but is wrong. dev_data = DevData.objects.order_by('dev_id','-data_timestamp').distinct('dev_id')[:n] Can somebody help me? Thank you very much!