Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using MultiFieldPanel inside a StructBlock
If you have a StructBlock class (used inside a StreamField)... Can you still use the Wagtail panels to group some fields (eg MultiFieldPanel) and (ideally!) use the collapsible class on the panel to hide them in some kind of "Advanced" panel? I have tried adding the block.TextBlock definitions into the array for a panel the, however neither the Panel nor the Fields appeared in the form. I cant see anything in the docs about using Panels in StructBlocks: https://docs.wagtail.io/en/v2.8.1/reference/pages/panels.html https://docs.wagtail.io/en/v2.8.1/topics/streamfield.html -
html template not rendering correctly for dynamic html content in django
I have strange issue in HTML template rendering, I have template index.html, in that template i passing dynamic content, here i have placed that code <p class="font-secondary paragraph-lg text-dark" style="color: black;"> {{ portal_contact_home_about|safe }} </p> in portal_contact_home_about this variable it contains data like "<p>Lorem ipsum</p>", so data should have to be render like this <p class="font-secondary paragraph-lg text-dark" style="color: black;"> <p>Lorem ipsum</p> </p> but it is rendering it as wrong way <p class="font-secondary paragraph-lg text-dark" style="color: black;"></p> <p>Lorem ipsum</p> can anyone please help me how to resolve this issue ? -
Connecting React with Python backend
I have created a form using React that uploads a image. This image should be sent to python where it is taking the image as input and giving the category of the image as output. I have designed the React and Python files as well, but I have no idea on how to integrate both. How to send API request to python and get back the response to React? -
I can't display django form fields based on user type or access type
I have a form defined in my forms.py there is this field on my form called "user" which is my foreing key or a reference to my User model. I want this field to display if you are a "CDA Admin" then is field should not display if you are a "CDA member". "CDA Admin" and "CDA member" are ways of determining user type. I know I can achieve this same thing by creating another form, views, linking to urls, etc and creating templates. I don't want to go through that process I want to easily manage it in one place. How do I handle this on my forms.py if possible views and templates? Please, I will really need someone to help me with code samples Below is what I have done so far options.py CDA_EXECUTIVE = 'CDA Executive' CDA_MEMBER = 'CDA Member' CMO = 'CMO' CDA_ADMIN = 'CDA Admin' CHOOSE = '' USER_TYPE = [ (CDA_EXECUTIVE, 'CDA Executive'), (CDA_MEMBER, 'CDA Member'), (CHOOSE, 'Choose User Type'), (CMO, 'CMO'), (CDA_ADMIN, 'CDA Admin'), ] models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ class User(AbstractBaseUser, PermissionsMixin): member_id = … -
how to upload files using nested serializer in Django
I have a problem uploading images/files through a nested serializer. I couldn't to see any article or documentation about this nested serializer to handle this. and if you have any library already there to handle such a problem please let me know. here am storing images location path in attachment table related with corresponding student like models misc/models.py class Attachment(BaseModel): file = models.FileField(upload_to=file_upload_location) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() uploader = GenericForeignKey('content_type', 'object_id') student/models.py class Profile(BaseModel): name= models.CharField(max_length=250) attachments = GenericRelation(Attachment) student/serializers.py from misc.models import Attachemnets class ProfileSerializer(WritableNestedModelSerializer): attachments = AttachmentSerializer(many=True, write_only=True, partial=True) class Meta: model = Profile exclude = ('created_at', 'updated_at') -
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