Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i save 404 requests in Django?
I have a Django app and that work perfect, I want get all request 404 for save. like: 127.0.0.1:8000/admin/hello # result is 404 because i haven't this url I want get /admin/hello because I haven't this Url. how can I do? -
Django CBV handle file upload from form
I've written this form, simple and not linked to a model or Form object (I find it easier this way to style the form and control it's behaviour with js) <form action="{% url 'upload_music_file' %}" method="POST" id="upload-form" enctype="multipart/form-data">{% csrf_token %} <div class="form-group"> <input type="file" class="form-control-file" id="csv-file"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> and the CBV that handles the post request class MusicFileUploadView(TemplateView): template_name = "music_file_upload.html" def get(self, request, *args, **kwargs): return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): print( request.FILES.keys() ) return super().get(request, *args, **kwargs) problem is I don't see the file in the request objects [01/May/2020 08:39:07] "GET /static/img/icon.png HTTP/1.1" 200 4822 dict_keys([]) [01/May/2020 08:39:19] "POST /upload-music-file HTTP/1.1" 200 7266 [01/May/2020 08:39:20] "GET /static/img/icon.png HTTP/1.1" 200 4822 dict_keys([]) [01/May/2020 08:39:28] "POST /upload-music-file HTTP/1.1" 200 7266 dict_keys([]) [01/May/2020 08:41:13] "POST /upload-music-file HTTP/1.1" 200 7266 [01/May/2020 08:41:13] "GET /static/js/upload_file.js?v=1.0.1 HTTP/1.1" 304 0 which means either the form didn't send it or Django CBV implementation I have isn't the right way to find the file. -
Django foreignKey that doesn't use model's primary key to match to foreign object's primary key?
Lets say I have two models that look like this: ModelA uuid (primary key) id ModelB id (primary key) size I want to add a field to ModelA. I want this field to be a ForeignKey that joins on ModelA.id == ModelB.id. I've searched all throughout the Django Docs and have only found how to change the foreign object's field used in the join, but I haven't found a way to change "this" object's field used in the join. Is it possible to specify a non primary key field from "this" object that is used to create a foreign key by being joined on a matching primary key from the foreign object? -
Working pagination with filters inside URL
My pagination in HTML template looks like that: {% if items.has_other_pages %} <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> {% if items.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ items.previous_page_number }}">&laquo;</a> </li> {% else %} <li class="page-item disabled"><a class="page-link" href="#"><span>&laquo;</span></a></li> {% endif %} {% for i in items.paginator.page_range %} {% if items.number == i %} <li class="page-item active"><a class="page-link" href="#">{{ i }} <span class="sr-only">(current)</span></a></li> {% else %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if items.has_next %} <li class="page-item"><a class="page-link" href="?page={{ items.next_page_number }}">&raquo;</a></li> {% else %} <li class="page-item disabled"><a class="page-link" href="#"><span>&raquo;</span></a></li> {% endif %} </ul> </nav> {% endif %} When I enter my page my url looks like this: http://localhost:8000/bikes/all , when I use pagination without filters it looks like this http://localhost:8000/bikes/all?page=2. When I use my filters URL looks like this: http://localhost:8000/bikes/all?q=&price_from=&price_to=&cat=Gravel+Bike&bra=&size=&lab= , but when I try to use pagination with the filters, the URL goes back to http://localhost:8000/bikes/all?page=2. Any idea how to fix it so it would keep the filters on inside URL? -
How to link form content with a model?
I have a group of patients. I also have a group of locations. In each patient's DetailView page, I want the user to be able to view the patient information and also link particular locations to the patient. I created a form, so the user can choose a location from a dropdown menu and then enter date, etc.. to the rest of the form. I want to be able to connect this information to the page of the current patient the user is at. forms.py class PastLocationForm(forms.Form): locations = forms.ModelChoiceField(queryset=Location.objects.all().order_by('location_name')) date_from = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS) date_to = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS) category = forms.CharField(max_length=20) views.py class PatientDetailView(DetailView, FormMixin): model=Patient form_class = PastLocationForm def get_success_url(self): return reverse('patient_detail', kwargs={'pk': self.object.pk}) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): instance = form.save(commit=False) return super().form_valid(form) models.py class Patient(models.Model): name = models.CharField(max_length=200) idn = models.CharField(max_length=200, unique=True) date_of_birth = models.DateField() date_of_confirm = models.DateField() case_number = models.IntegerField() def get_absolute_url(self): return reverse("patient_detail", kwargs={'pk':self.pk}) def __str__(self): return self.name class Location(models.Model): patient = models.ForeignKey(Patient, related_name='locations', on_delete=models.CASCADE, null=True, blank=True) location_name = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=300, null=True, blank=True) district = models.CharField(max_length=300, null=True, blank=True) grid_x = models.IntegerField(null=True, blank=True) … -
Django custom url pattern
Can i generate custom url pattern like this with or without restframework www.domain.com/sample,175,Skoda_Superb,_2000_Km,_Polski_Salon Here 175 is mysql index id. Skoda_Superb is a category model. _2000_km attribute comes from 175 index. _Polski_Salon is a subcategory -
How can I run a python 2.7 project with Django 1.8 on ubuntu 18.04 when python 3 is my default amd djamgo 1.11 is installed in my virtualenv?
I need to run a Django project which was originally coded in python 2.7 and Django version 1.8 on my linux system. How do I switch between the different versions of python and run the project through terminal and not through a python IDE. -
extend request time DjangoRestFramework API
I have deployed my djangorestframework project on heroku, but the API has a request time out, how can I extend my API request time? -
best way to use Coupon code in Guest and Login User
I django what is the best way to use coupon code for guest user and login user for per coupon per order. ? my order model is like class Orders(models.Model): order_number = models.AutoField(primary_key=True) total_amount = models.DecimalField(max_digits=10, decimal_places=2) ordertime = models.DateTimeField(auto_now_add=True) customer= models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) guest =models.CharField(max_length=500, null=True, blank=True) In my opinion I should create a coupon model like something class Coupon(models.Model): coupon = models.charField(max_length=50) -
AWS VPS not working with Nginx? (Django React project deployment)
I've newly registered with Amazon VPS service, Amazon Lightsail. After properly setup my Django app, Gunicorn and Nginx, it seems that there's some problem with the traffic? I set up the same Django app on two different VPS using the same process, both with Ubuntu 18. The IP isn't working on AWS (13.124.94.92): ~# ping -c3 13.124.94.92 PING 13.124.94.92 (13.124.94.92) 56(84) bytes of data. --- 13.124.94.92 ping statistics --- 3 packets transmitted, 0 received, 100% packet loss, time 2044ms The IP is working perfectly (5.63.152.4) in another VPS Ubuntu 18: ~# ping -c3 5.63.152.4 PING 5.63.152.4 (5.63.152.4) 56(84) bytes of data. 64 bytes from 5.63.152.4: icmp_seq=1 ttl=64 time=0.063 ms 64 bytes from 5.63.152.4: icmp_seq=2 ttl=64 time=0.108 ms 64 bytes from 5.63.152.4: icmp_seq=3 ttl=64 time=0.082 ms --- 5.63.152.4 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2043ms rtt min/avg/max/mdev = 0.063/0.084/0.108/0.019 ms The first IP isn't showing 'Welcome to Nginx' page while the second does (http://5.63.152.4/) I'm not sure where to start to debug this... I've fiddled with iptables a bit, for failing to have mosh working. Please help! Thanks!!! -
WORKER TIMEOUT djangorestframework in heroku
[4] [CRITICAL] WORKER TIMEOUT (pid:10) when i turn on my API, i get an error worker timeout, i deploy my django on heroku, how can I extend the period of my API request? -
Get all data for users Djoser
I use userProfile model the following code it has "OneToOneField". I want gel all data for users. from django.db import models from django.contrib.auth.models import User class userProfile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,related_name="profile") date_joined=models.DateTimeField(auto_now_add=True) updated_on=models.DateTimeField(auto_now=True) def __str__(self): return self.user.username and seralizers class show in bellow; from rest_framework import serializers from .models import userProfile class userProfileSerializer(serializers.ModelSerializer): user=serializers.StringRelatedField(read_only=True) class Meta: model=userProfile fields='__all__' I want to get all users using ; class userAccountsListView(ListAPIView): queryset=userProfile.objects.all() serializer_class=userProfileSerializer It return data like; [ { "id": 1, "date_joined": "2020-04-16T16:50:38.218964+03:00", "updated_on": "2020-04-16T16:50:38.218996+03:00", "user": 5 }, { "id": 2, "date_joined": "2020-04-30T13:53:48.859116+03:00", "updated_on": "2020-04-30T13:53:48.859149+03:00", "user": 6 } ] I want to get all users info; [ { "id": 1, "date_joined": "2020-04-16T16:50:38.218964+03:00", "updated_on": "2020-04-16T16:50:38.218996+03:00", "user": 5 }, { "id": 2, "date_joined": "2020-04-30T13:53:48.859116+03:00", "updated_on": "2020-04-30T13:53:48.859149+03:00", "first_name": "xxxxx", "last_name": "xxxxx", "email":"xxxx", } ] -
Images disappearing in heroku even after storing them in S3 bucket
I'm using sqlite3 as my database, i.e., the django default database. I am told Heroku is ephemeral. So the images stored will be vaporized. So I used Amazon S3 bucket for storing all my static files and the images uploaded via django admin. Still the images that I upload via django admin gets disappeared after couple of hours. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AWS_ACCESS_KEY_ID = ** AWS_SECRET_ACCESS_KEY = ** AWS_STORAGE_BUCKET_NAME = 'bucket' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Do I need to connect to the Postgresql that heroku provides? Or did I make any blunder thus far? The link to my site: http://fine-arts-club.herokuapp.com/ -
how can i set html images load with my ip proxy in Django?
I have a website with load images as shown here: <img src="https://www.gardendesign.com/pictures/images/675x529Max/site_3/helianthus-yellow-flower-pixabay_11863.jpg" alt="Smiley face" height="42" width="42"> I have proxy and port like IP proxy:45.4.85.75 Port Proxy:9991 how can i set this proxy for all my user to load this image or any images Url with this IP proxy? If need to know my web server is Django 2. I think do that with javascript but how? -
How to filter values from 3 different models in django
I have 3 classes and i want to filter them based on criteria taken form 3 classes. I am very new to django and especially model. Need your help. Student, group and nondemandgroup are tables in my db. class Student(): name=models.CharField(max_length=200) surname=models.CharField(max_length=200) class group20(): name=models.CharField(max_length=200) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) class nondemandgroup(): name=models.CharField(max_length=200) acting=models.DecimalField(decimal_places=2,max_digits=1000) cooking=models.DecimalField(decimal_places=2,max_digits=1000) i want to get list of student who's final grade is met by fowlloing criteria: final_grade = group20.objects.filter(math__gt=60, ((math+english+acting)/3)__gt=70) acting is within nondemandgroup class so my final_grade doesn't work it says no such column as acting. How to to make acting column work ? I tried Foreign key but it does not work and gives an error. Or should i create a new model and filter within it where i will create foreign keys of 3 models ? I am quite confused as i stated i am very new to Django and models are confusing. Explored web however in my case i misunderstand smth and the formula does not work. -
prevent sql duplicates by inline formset factory in django 3.0.5
i have a problem with inline formset factory in django 3.0.5. i have models like this: class Resume(models.Model): user = models.ForeignKey(User, verbose_name=_('User'), on_delete=models.CASCADE) website = models.URLField(verbose_name=_('Web Site'), blank=True, null=True) ... class Expertise(models.Model): name = models.CharField(_('name'), max_length=100) ... class ResumeExpertise(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE, related_name='resume_expertise') expertise = models.OneToOneField(Expertise, on_delete=models.CASCADE, verbose_name=_('Expertise'), related_name='resume_expertise_item') score = models.PositiveSmallIntegerField(_('Score')) def __str__(self): return self.expertise.name in this case user must edit the form. i used inline formset factory. my forms.py: class ResumeForm(forms.ModelForm): class Meta: model = Resume fields = ('website',) def __init__(self, *args, **kwargs): super(ResumeForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Field('website'), Fieldset('Expertise', Formset('expertise')), HTML("<br>"), ButtonHolder(Submit('submit', 'save')), ) ) class ResumeExpertiseForm(forms.ModelForm): class Meta: model = ResumeExpertise fields = ('expertise', 'score') ResumeExpertiseFormSet = inlineformset_factory(Resume, ResumeExpertise, form=ResumeExpertiseForm, fields=['expertise', 'score'], extra=1, can_delete=True) for views i used class based views like this: class ResumeEdit(LoginRequiredMixin, UpdateView): model = Resume template_name = "user/resume_form.html" form_class = ResumeForm success_url = reverse_lazy('user:profile') def get_object(self, queryset=None): return Resume.objects.get(user=self.request.user) def get_context_data(self, *args, **kwargs): context = super(ResumeEdit, self).get_context_data(**kwargs) context['title'] = _('Edit Resume') if self.request.POST: context['expertise'] = ResumeExpertiseFormSet(self.request.POST, instance=self.object) else: context['expertise'] = ResumeExpertiseFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() expertise = context['expertise'] with … -
Differentiate access to the post based on a user's type
I'm developing a blog and I need a differentiate access to the post based on a user's type. If the post is a draft only the staff user can read it, otherwise everyone can read it. I've this code into a views.py: geopost_filter = GeoPost.objects.filter(Q(draft=False) and Q(publishing_date__lte=timezone.now())) def single_geopost(request, slug_post): if request.user.is_staff: geopost = get_object_or_404(GeoPost, slug_post=slug_post) else: geopost = get_object_or_404(geopost_filter, slug_post=slug_post) context = { "post": geopost, } template = 'geoblog/single_geopost.html' return render(request, template, context) This function doesn't run because I can read the post whether I'm a staff member or a simple user. Where am I wrong? -
Update ManytoMany relationship in Django Rest Framework
In my django application I have a ManytoMany relationship between Orders and Packages. An order can have multiple packages. I want to know about the update and create methods Models.py class Package(models.Model): prod_name = models.CharField(max_length=255, default=0) quantity = models.IntegerField(default=0) unit_price = models.IntegerField(default=0) class Orders(models.Model): order_id = models.CharField(max_length=255, default=0) package = models.ManyToManyField(Package) is_cod = models.BooleanField(default=False) Serializers.py class PackageSerializer(serializers.ModelSerializer): class Meta: model = Package fields = "__all__" class OrderSerializer(serializers.ModelSerializer): package = PackageSerializer(many=True) class Meta: model = Orders fields = "__all__" Views.py class OrdersCreateAPIView(generics.CreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = OrderSerializer def post(self, request): serializer = OrderSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Is that sufficient to handle the related data? I am trying to understand ManytoMany relationship both in Django as well as DRF so please explain if I need to change the Models or views in anyway -
How to let users edit images like adding filters or cropping from frontend using Django?
I want to make a webpage using django backend where users can edit images the moment they upload like in Instagram or other similar websites. How to do it? Any suggestions or are there any procedures to follow? Any leads would be appreciated. Thanks in advance! -
Why can't Django class based view access a template?
I have a detailview like this: class PatientDetailView(DetailView): model=Patient template_name = 'patient_detail.html' def get_context_data(self, **kwargs): context = super(PatientDetailView, self).get_context_data(**kwargs) context['form'] = PastLocationForm return context And I get an error as django.template.exceptions.TemplateDoesNotExist: patient_detail however, path to my templates folder is defined in settings.py and I don't have an import issue to any my templates other than here. To solve the problem, I tried to manually import the template as: from ..templates.covidapp import patient_detail and I receive ValueError: attempted relative import beyond top-level package -
Django how to add a timestamp value to a database from a view function?
What i would like to do in the Initial Report Function is to get the timestamp value when the emails are sent and store that value in a database. I would appreciate the help The view function def Initial_Report(request): #Gets email addresses and sends report noc_emails = Employee.objects.exclude(Position__Position__contains='Customer').values_list('Email', flat=True) cs_emails = Employee.objects.filter(Position__Position__contains = 'Customer').values_list('Email', flat=True) initialTime = datetime.now() noc_message = ('Initial Outage Report', 'This is a new outage report, The information is in the document' , 'from@example.com', noc_emails) cs_message = ('Initial Outage Report', 'This is a new outage report ,The information is in the document', 'from@example.com', cs_emails) send_mass_mail((noc_message,cs_message), fail_silently=False) return render(request,'InitialReport.html') Models class Outage_Dates(models.Model): Report_ID = models.CharField(max_length=30,primary_key = True, unique =True) Outage_Begining = models.DateTimeField() def __str__(self): return self.Report_ID + ' ' + str(self.Outage_Begining) -
Comment Form not posting on submit in django
I have a blog site in progress, the submit form for the comment is redirecting to /post unexpectedly. error/output: before clicking submit <WSGIRequest: GET '/post/2'> -# my print statement in views.py fail -# my print statement in views.py [01/May/2020 11:28:43] "GET /post/2 HTTP/1.1" 200 14275 on clicking submit Not Found: /post/ [2020-05-01 11:33:39,126] log: WARNING - Not Found: /post/ [01/May/2020 11:33:39] "POST /post/ HTTP/1.1" 404 2795 submit button is type submit and here is everything related to it, I have been stuck on this for a while now. And I have added print() in views.py to find where the problem is. Help would be appreciated post.html <form method="POST" action="." class="commenting-form"> {% csrf_token %} <div class="row"> <div class="form-group col-md-12"> {{ form }} </div> <div class="form-group col-md-12"> <button type="submit" class="btn btn-secondary">Submit Comment</button> </div> </div> </form> views.py def postview(request, my_id): most_recent = Posts.objects.order_by('-timestamp')[:3] category_count = get_category_count() post = get_object_or_404(Posts, id=my_id) form = CommentForm(request.POST or None) print(request) if request.method == "POST": print(form) if form.is_valid(): form.instance.user = request.user form.instance.post = post form.save() print(form) return redirect(reverse('postdetail', kwargs={ 'my_id': post.pk })) else: print('fail') context = { 'post': post, 'most_recent': most_recent, 'cat_count': category_count, 'form': form } return render(request, 'post.html', context) models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp … -
How to search items using multiple model fields
My search function currently looks like that: query = request.GET.get('q') if query: item_list = item_list.filter(title__icontains=query) | item_list.filter( bike__brand__name__icontains=query) | item_list.filter( accessory__brand_accessory__name__icontains=query) | item_list.filter( bikepart__brand_part__name__icontains=query) I can filter my items using single fields, but I am looking for a filter that can look up items using multiple fields. My items are divided into 4 different models. Item model is a main model, that holds all titles for other models, that are connected to this main model, which are: Bike, Accessory and BikePart. I am looking for filtering using (title__icontains=query + bike__brand__name__icontains=query), (title__icontains=query + accessory__brand_accessory__name__icontains=query), (title__icontains=query + bikepart__brand_part__name__icontains=query) , but I still wanna be able to look up items by using just a title or just brand. What would be the best way to achieve that? -
I want to show stars based on an array element that is passed as a parameter to my template
So I was trying to loop over an array element which id {{doctor.16}} but I couldn't so I thought I could make it as if conditions but I failed to do this too so can anyone please help me? this is what I have done so far <div class="row"> <div class="col-lg-12"> <div class="single_jobs white-bg d-flex justify-content-between" style="width: 50px"> <div class="single_candidates text-center"> {% for doctor in recdoc %} <div class="thumb"> <img class="img-circle " src="{% static 'static_file/img/candiateds/2.png' %}" alt="" > </div> <a href="" ><h4 >{{doctor.6}} {{doctor.7}}</h4></a> <p> {{doctor.9}}</p> <div class="best-rating"> <div class="text-warning"> {% if{{doctor.16}} == 1 %} <i class="fa fa-star"></i> {% endif %} </div> <div class="best-rating" > <h5>تقييم الدكتور</h5> </div> </div> {% endfor %} </div> </div> </div> </div> </div> what I can't do correctly is this part {% if{{doctor.16}} == 1 %} <i class="fa fa-star"></i> {% endif %} -
Display validation errors in the same style as cripsy error messages
I'm using crispy forms to make my forms look nice and added the following validation: if age < 14: raise forms.ValidationError('Sorry, you must be atleast 14 years old to study with IPC IELTS') elif age > 110: raise forms.ValidationError('You entered a date of birth outside of the accepted range. Please try again') return data My problem is that this error message displays at the top of the page as a flash message, while other messages (which i did not set but are built into crispy, such as when a user leaves a required field blank) are displayed as a pop up message box under the field the errors related to. I am wondering how I can make my added validation error appear the same as other in-built crispy error messages, for consistency. Thank you.