Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Filter data on the basis for ForeignKey in django
I've three types of model as show below and now I want to apply filter on them. I want to filter list of all the category from foodItem containing takeaway, dine_in, function separately. I want to filter list of sub_category containing category I want to filter list of food item containing subcategory. For the more clarification, I want to filter food item in hierarchal approach. I've also attached a screenshot, How I want to display my data, and sorry for my poor english. class FoodCategory(TimeStampWithCreator): title = models.CharField(max_length=55) class FoodSubCategory(TimeStampWithCreator): title = models.CharField(max_length=55) class FoodItem(TimeStampWithCreator): CATEGORY_CHOICES = ( ('takeway', 'Takeway'), ('dine_in', 'Dine In'), ('function', 'Function'), ) type_menu_select = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='takeway') category = models.ForeignKey(FoodCategory, on_delete=models.CASCADE) sub_category = models.ForeignKey(FoodSubCategory, on_delete=models.CASCADE) title = models.CharField(max_length=55) I want to display data in frontend like this. -
Middleware Setup
I am trying to setup a message middleware for my marketing app,but the method process_request is not returning anything. it is running without errors still though not returning message requests. my middleware.py--- from .models import MarketingMessage class DisplayMarketing(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): def process_request(request): print("something") try: request.session['marketing_message'] = MarketingMessage.objects.all()[0].message except: request.session['marketing_message'] = False response = self.get_response(request) return response my settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'marketing.middleware.DisplayMarketing', ] -
Django Channels consumer consuming 1 call twice
I am using a combination of DRF 3.11.0 and Channels 2.4.0 to implement a backend, and it is hosted on Heroku on 1 dyno with a Redis resource attached. I have a socket on my React frontend that successfully sends/received from the backend server. I am having an issues where any message sent back to the front end over the socket is being sent twice. I have confirmed through console.log that the front end is only pinging the back end once. I can confirm through print() inside of the API call that the function is only calling async_to_sync(channel_layer.group_send) once as well. The issue is coming from my consumer - when I use print(self.channel_name) inside of share_document_via_videocall(), I can see that two instances with different self.channel_names are being called (specific.AOQenhTn!fUybdYEsViaP and specific.AOQenhTn!NgtWxuiHtHBw. It seems like the consumer has connected to two separate channels, but I'm not sure why. When I put print() statements in my connect() I only see it go through the connect process once. How do I ensure that I am only connected to one channel? in settings.py: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { #"hosts": [('127.0.0.1', 6379)], "hosts": [(REDIS_HOST)], }, }, } Consumer: import json from … -
Why can't I inject form into HTML?
I have a form that I want to inject into a class based DetailView. forms.py class PastLocationForm(forms.Form): locations = forms.ModelChoiceField(queryset=Location.objects.all().order_by('location_name')) views.py class PatientDetailView(DetailView): model=Patient form_class = PastLocationForm Unfortunately, the form PastLocationForm doesn't appear on the HTML page after injection. I inspected the page and there was nothing. Interestingly, if I pass PastLocationForm to a functional view and render it for another page, the form shows up! I also have other views where I make use of "form_class" for other modelForms and they function correctly. I will switch my view to functional view if I can't find the solution but I would rather keep the class based view. -
How to make Django recognize JSON file in another directory
I'm using a JSON file to store some credentials. I have a file with a function that opens that JSON file and uses the credentials to call the Twitter API using Tweepy. The file structure looks like this: [search]/ ├── [tweepi_api]/ │ ├── __init__.py │ ├── get_tweets.py │ ├── credentials.json └── views.py init.py looks like: from .get_tweets import ApiAuth Views.py looks like: from django.shortcuts import render import json from .tweepy_api import ApiAuth # Create your views here. def search_bar(request): tweetObj = ApiAuth('IBM') tweet_text = tweetObj.get_tweets() return render(request, 'tweets.html', {'public_tweets': tweet_text}) The problem is I get this error: Exception Value: [Errno 2] No such file or directory: 'credentials.json' I'm not sure how to include this file in my project in a different way. Hope this is enough to answer my question. I can share more of the code if needed but my goals is not made the credentials visible when i upload this to Github and keep them as a json file on my machine. Thank you in advance -
Find out the count of Matches from fixtures for individual country in Django Model
I have a model below which has matches_between which returns "Team1 vs Team2" Team1 will be the first country name and Team2 will be the second country name. I'm trying to find out the individual country's match count to represent the same in the points table for the number of matches the country has played. Model class Score(models.Model): matches_between = models.ForeignKey('Match',on_delete = models.CASCADE, related_name ='fixture_between') Team1 = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, related_name='teamA',default = 0) Team2 = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, related_name='teamB',default = 0) team1Score = models.IntegerField(default = 0) team2Score = models.IntegerField(default = 0) def team1_count(self): team_count1 = {i["Team1"]: i["count"] for i in order_items.objects.values('Team1').order_by().annotate(count=Count('Team1'))} return team_count1 def team2_count(self): team_count2 = {i["Team1"]: i["count"] for i in order_items.objects.values('Team2').order_by().annotate(count=Count('Team2'))} return team_count2 team1_count and team2_count function give the individual Team count but how to add both and return the individual country count. -
Celery Multiple Database Connections Django
On my project I have 5 workers on running that periodically check or insert data on database (postgress) every 5 seconds . My problem is that celery is opening too many connections to the database. I can see at least 20 connections for the same tasks hitting the database. Is there way to improve this with Django? I tried setting up CONN_MAX_AGE = None on django, to have the database persist the same connection but that didn't help. I also saw a pull request and some comments on reuse the database on previous mentioned issues but they were reverted because they caused regression problems. I wanted to accomplish one connection to Django ORM per worker. -
freeBSD _mysql.c:44:10: fatal error: 'my_config.h' file not found
My env is freeBSD12.1 python2.7.17 django1.11.29 mysqlserver18.0.19,I'v already uninstall python3.7.7 and ln -s /usr/local/python2.7/bin/python2.7 /usr/bin/python,a [root@bsd /home/tl/MySQL-python-1.2.5]# python setup.py build running build running build_py copying MySQLdb/release.py -> build/lib.freebsd-12.1-RELEASE-p3-i386-2.7/MySQLdb running build_ext building '_mysql' extension cc -fno-strict-aliasing -O2 -pipe -fstack-protector-strong -fno-strict-aliasing -DNDEBUG -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/include/mysql -I/usr/local/include/python2.7 -c _mysql.c -o build/temp.freebsd-12.1-RELEASE-p3-i386-2.7/_mysql.o _mysql.c:44:10: fatal error: 'my_config.h' file not found include "my_config.h" ^~~~~~~~~~~~~ 1 error generated. error: command 'cc' failed with exit status 1