Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Ajax: div is not reloading after post rate
i'm trying to implement ajax to my project. I want to reload the div where the average rate is. I stucked on the moment when the average is disappearing after posting rate. ajax $(document).ready(function(){ $("#rateButton").click(function(){ var serializedData = $("#rateForm").serialize(); $.ajax({ url: $("rateForm").data('url'), data: serializedData, type: 'post', success: function(data){ console.log(data); $('.average').html(data); } }) }); }); template <p>Rating: <div class="average">{{ movie.get_average }}</div></p> {% if user.is_authenticated %} <form action="" method="POST" id="rateForm" data-url="{% url 'detail_movie' slug=movie.slug %}"> {% csrf_token %} {{ form.as_p }} <button type="button" id="rateButton">Oceń</button> </form> {% endif %} get_average func from models def get_average(self): rates = self.rate_set.all().values_list('choice', flat=True) if rates: average = (sum(rates))/len(rates) return average return "No rates" views def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if request.method == 'POST': if form.is_valid(): new_rate, _ = Rate.objects.update_or_create( sender=self.request.user, movie=self.object, defaults={'choice': form.cleaned_data['choice']} ) return JsonResponse({'rate': model_to_dict(new_rate)}, status=200) else: return self.form_invalid(form) I will be very grateful for help. -
Saving a object which is a foreign key of another project in views.py in django
This is my views.py: def handlerequest(request, id): order=Order.objects.get(id=id) items=order.orderitem_set.all() verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': order.complete=True order.save() for item in items: a=str(item.size) if a=="XS": item.product.XS-=1 if item.product.XS<=0: for s in item.product.size.all(): item.product.remove(1) **#Save Product Here** return render(request, 'handlerequest.html', {'response': response_dict,'order':order}) and this is my orderitem model: class OrderItem(models.Model): product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True) What I want is that in my views.py when I am doing if a=="XS" after that I want to save the product(which has a different model).I tried several variations but got errors.How should I save the product after the if statement. -
Post user geolocation to Django class based view
I am trying to post user geolocation to Django class based view. Apparently, javascript is not so friendly to me. How can I post user geolocation to UserProfileView class based view in django, ajax? <body> <div> <div> <strong>Current Position: </strong> {{ profile.user_location }}<br/> </div> <label for="locations-status">Enable Location?</label> <input type="checkbox" id="locations-status"> <form id="location_form" method="POST" action="{% url 'rent_app:add-location' %}"> {% csrf_token %} <button type="button" id="send-my-url-to-django-button">Send URL to Django View</button> </form> {% block js %} <script> function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); } } }); if ("geolocation" in navigator) { navigator.geolocation.getCurrentPosition( function (position) { console.log('Position has been set successfully'); console.log(position.coords); dataToSend = { "permission": $("input[name=locations-status]").is(':checked'), "user_location": position, }; }); } $("#send-my-url-to-django-button").click(function() { $.ajax({ type: "POST", dataType: 'json', url: "{% url 'rent_app:add-location' %}", data: JSON.stringify(dataToSend), success: function (msg) { console.log('Succeeded!'); }, error: function (err) { console.log('Error!'); } }); }, function (error) { console.log('Position could not be obtained.'); } ); </script> {% endblock %} </body> views.py: class UserProfileView(View): form_class = UserProfileModelForm template_name = "user_profile.html" def get(self, *args, **kwargs): form = self.form_class() user_locations = UserProfile.objects.user_location() return render(self.request, self.template_name, {"form": form, "user_location": user_locations}) def … -
Django Tutorial - Problem with Laptop Django when running "python manage.py xyz" -> AttributeError: 'Choice' object has no attribute 'model'
I am following the Coursera Course on Django as well as the Django tutorial. The Coursera course runs on Pythonanwhere. Now I came up with idea to run it on my MacAir. Thus I created a Conda environment and followed all the steps as for Pythonanywhere. But whenever I run anything like "python manage.py ...." I get this error: AttributeError: 'Choices' object has no attribute 'model' After researching I finally went from file to file and made a copy paste (except one or two). I even downgraded my Python version from 3.8 to 3.6.3. Didn't help. I checked for typos and finally did copy-paste. Nothin' :-( And this my polls/model.py: from django.db import models import datetime from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text In the meantime I changed the name "Choice" to "Choices" just to get the error message: AttributeError: 'Choices' object has no attribute 'model' I am quite sure that it is a simple error but I cannot find the solution :-( Thanks. -
Getting url errors after deployment
Hello I have a django project with the domain www.itucampus.com, I owned the domain from godaddy and forwarded itucampus.com to www.itucampus.com I hosted it on pythonanywhere.com. I also forced http to https. My problem now is sometimes I could reach my webpage and sometimes not and now I found which urls are working and which not. itucampus.com www.itucampus.com https://www.itucampus.com are working but https://itucampus.com http://itucampus.com http://www.itucampus.com are not working and I am getting the error to many redirects. Could you please help me -
Cross Origin Request Blocked: Django, Axios
I am attempting to retrieve information around a book via the good reads API. So far, I've attempted the following: Through Postman: A simple get request with the API key and query string works perfectly, and I receive an XML response: 2.Through django/python methods : I wrote a simple method that uses the 'requests' package to retrieve data as follows, this also works with info being returned as expected: def get_goodreads_response(book_name): api_key = config('GOODREADS_API_KEY') response = requests.get('https://www.goodreads.com/book/title.xml?key=' + api_key + '&title=' + book_name) response_xml = ElementTree.fromstring(response.content) return response_xml Through the axios JS library in a django template: I am very new to JS, and found snippets of code over the web that I've put together for now, this is what it looks like: <script> axios.get('https://www.goodreads.com/book/title.xml?key={{ api_key }}&title={{ book_name }}') .then(response => { console.log(response.data) }) .catch(error => console.error(error)) </script> This throws the following error: I haven't the slightest clue about where to begin to debug this. Can you tell me where I'm going wrong? The reason I am trying to do this with javascript is to allow the rest of the page to load and not be delayed by the API call. This way, only the sections that are dependent on … -
Rendering images from REST response on localhost
I am trying to run a REST API on one port (8000) using django and consuming that API in an App running on port 9000 again using django. My REST response is having an image field, now the problem is that i can not provide my desktop path in upload_to option in my API models and if i am giving the absolute path of API project in my App project index. Html, i get a browser error as "Not allowed to load resources from local path" So i am having to create media folders with same name in both API and App projects and keeping image files in both and using only the file path from the REST response and rendering the image from App project itself. Is there any way i can get away with this and consume the image from the Rest response only? -
Django queryset date filter based on subelement
I have the following Django models: class Table(models.Model): # model fields @property def is_finished(self): return not Meal.objects.filter(table=self)\ .filter(finished_time=None).exists() class Meal(models.Model): table = models.ForeignKey( Table, null=True, blank=True, on_delete=models.CASCADE, related_name='meals' ) finished_time = models.DateTimeField(null=True, blank=True, default=None) A table is considered finished if all meals for it have a finished_time. I would like to annotate is_finished in a queryset, to exclude tables where are meals are finished. Something like: Table.objects.all()\ .annotate(has_meals=Count('meals__finished_time'))\ .annotate(finished=Min('meals__finished_time'))\ .filter(finished=None)\ .exclude(has_meals=0) But this does not work if I have finished meals and unfinished meals on a table. How can I fix this? -
Serializing lists of the same object, but differentiating a field within the response
I am building an endpoint within Django Rest Framework that's goal is to return events User added to their calendar and confirmed attendance to I'd like this to look something like: { "events": "added-to-calendar": [], "confirmed": [] } I've solved this with the following: events = { "events": { "added-to-calendar": serializers.EventSerializer(added_to_calendar_events, many=True).data, "confirmed": serializers.EventSerializer(confirmed_events, many=True).data, } } return Response(data=events, status=status.HTTP_200_OK) But this just smells to me... I imagine there's a proper way of serializing this within a proper Serializer, rather than the double serializer logic I've created here. -
How to change the "username" displayed for the django username field to something different like "code name" or "nickname"
I was trying to customize my user but at the same time keep it as simple as possible, I wanted the username field to display as "nickname" but still keep all the behaviour and properties of the username. What I do when I am extending a django class is the ctrl+click thing on vscode to go inspect the super class (I was extending the AbstractUser this time) and here is the code for the username field in django's AbstractUser: username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) Usually, I'd just paste the field in my custom class and override the _('username') with _('nickname') but that doesn't feel like the right thing to do here as there's a lot going on in that field, plus I'd have to also import the username_validator to keep that behaviour. Now my question is; how do I override the verbose_name field (I guess that is what it's called) and still keep other behaviours. -
django does not start in docker. Attaching to clone_web_1
trying to run empty django project in dockcer. Here is my dockerfile and docker-compose: FROM python RUN mkdir /code && mkdir /data ADD . /code RUN mkdir /root/.ssh WORKDIR /code version: '2' services: web: build: . ports: - 8000:8000 volumes: - .:/code command: python3 manage.py runserver 0.0.0.0:5000 WHAT IS WRITING: $ docker-compose up Starting clone_web_1 ... done Attaching to clone_web_1 -
How to install postgresql in red hat linux without root
I have a django app to deploy. I have cpanel with no root access. I cannot use yum etc either. I am instructed to install python3-pip python3-dev libpq-dev postgresql postgresql-contrib redis-server for deployment if using Ubuntu. I am able to install python 3.7, redis from the source, and psql is pre-installed I assume, because using psql --version it gives me the version 9.2.24. When I tried to test production server 8000, it gives me an error No module named _sqlite3. After some search, it seems I need to install postgresql-dev which is equivalent to libpq-dev. I found the source here, but I don't know how to install it properly, i.e., how to install it without breaking the existing one, since the versions do not match. -
Show javascript variable in django
I have a function that, when the form is submitted, shows a pop up. In that pop up i have a link <a class="btn btn-primary" href="{{ url 'enviado' name=? mail=? }}">Join</a> I want to pass my js variables there. This is my code: My js: document.querySelector('#elform').addEventListener("submit", function(event) { event.preventDefault(); fetch("", { method: 'POST', body: JSON.stringify({ mail: document.querySelector('#email').value, name: document.querySelector('#name').value }), headers: { "Content-type": "application/json; charset=UTF-8", "X-CSRFToken": getCookie('csrftoken') } }) .then(response => response.json()) .then(result => { popup_content('show'); } }); } }); }) My html, the pop up content: <div id="popup_content_wrap" style='display:none'> <div align="center" id="popup_content"> <center> <p>Welcome</p> <a class="btn btn-primary" href="{{ url 'enviado' name=? mail=? }}">Join</a> <a align="right" type="submit" name="submit" onClick="popup_content('hide')">Go back</a> </center> </div> </div> Is there any way to do this? -
How to eliminate duplicate object and add in to a single object
I am having a model class Project(models.Model): project = models.CharField(max_length=255, blank=True, null= True) user = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() start_date = models.DateField() THis is my query for fetching the data qs = Project.objects.values('project').annotate( total_hours=Sum((F('end_time') - F('start_time')) / 3600000000), start_date =F('start_date'), ).distinct() for i in qs: print(i) Now what I am getting is {'project': '1', 'total_hours': Decimal('2.0000'), 'start_date': datetime.date(2020, 8, 1)} {'project': '3', 'total_hours': Decimal('1.0000'), 'start_date': datetime.date(2020, 8, 1)} {'project': '1', 'total_hours': Decimal('1.0000'), 'start_date': datetime.date(2020, 8, 2)} Here if project 1 coming twise in to diffrent dates.... How to elimintate second one add as a single object -
Django: Show the content of the model as per the current user logged in
I want to show the form content of the current user logged in How can I achieve that models.py class Sign(models.Model): name = models.CharField(max_length=50) regid = models.CharField(max_length=50) email = models.EmailField(max_length=255) designation = models.ForeignKey(Designation, default='', on_delete=models.CASCADE) phone = models.IntegerField() car_type = models.ForeignKey(Cars, default='', on_delete=models.CASCADE) pick_up = models.CharField(max_length=50) destination = models.CharField(max_length=50) guestname = models.CharField(max_length=50, blank=True) user = models.ForeignKey(User, default='', null=True, on_delete=models.CASCADE, related_name='hiuser') class Meta: db_table = "Sign" def __str__(self): return self.name def get_absolute_url(self): return reverse('final') forms.py class BookingForm(forms.ModelForm): class Meta: model = Sign fields = ['name', 'designation', 'email', 'pick_up', 'regid', 'car_type', 'guestname', 'destination', 'phone', ] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Your Name'}), 'designation': forms.Select(attrs={'class': 'form-control' }), 'email': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Email Address'}), 'pick_up': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Pick Up Location'}), 'regid': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Registration ID'}), 'car_type': forms.Select(attrs={'class': 'form-control'}), 'guestname': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Guest Name(If Any)'}), 'destination': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Destination'}), 'phone': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Phone Number'}), } views.py @login_required def booking(request): '''model = Sign form = BookingForm''' if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your Booking is Accepted') return redirect('final') else: form = BookingForm() return render(request, 'datas/booking.html', {'form': form}) This is my view for creating the form,now I want to show this content here: @login_required def … -
Django raw cursor.execute for insert statement - cannot insert null value for a column
I am trying to insert null for a table's column using Django's cursor.execute method but couldn't. I tried different options by providing - 1. 'NULL' 2. None 3. 'None' 4. '' But none of these above options was able to insert null value in for the field in a record/row. At max I was able to insert '' (blank) but not null. I even tried leaving the field empty, for ex. values('foo',,'bar') but still gives exception. Any pointers ? -
Reverse for 'day_new' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['date/(?P<pk>[0-9]+)/new/$']
this is my first django project and it seems like I don't understand something about primary keys I have 2 models and want to add them to 1 form but I'm getting this error Reverse for 'day_new' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['date/(?P[0-9]+)/new/$'] my models.py from django.db import models from django.utils import timezone from django.urls import reverse from django.conf import settings class MyDate(models.Model): english_date = models.DateField(auto_now=False) hebrew_date = models.CharField(max_length=20,unique=True) def get_absolute_url(self): return reverse("date_detail",kwargs={'pk':self.pk}) def __str__(self): return self.hebrew_date class MyDateDetails(models.Model): date = models.ForeignKey('luach.MyDate',on_delete=models.CASCADE) sof_zman_1 = models.TimeField(auto_now=False,blank=True,null=True) sof_zman_2 = models.TimeField(auto_now=False,blank=True,null=True) sof_zman_tefila = models.TimeField(auto_now=False,blank=True,null=True) message = models.CharField(max_length=200,blank=True,null=True) ad_image = models.ImageField(unique=False,blank=True,null=True) def __str__(self): return str(self.date) class Image(models.Model): date = models.ForeignKey('luach.MyDate',on_delete=models.CASCADE) image = models.ImageField(unique=False,upload_to='images') def get_absolute_url(self): return reverse("date_detail",kwargs={'pk':MyDate.pk}) def __str__(self): return str(self.date) my views.py from django.shortcuts import render,get_object_or_404,redirect from django.urls import reverse_lazy from luach.models import (MyDate,Image,MyDateDetails,MazelTov) def create_day_view(request,pk): date = get_object_or_404(MyDate,pk=pk) if request.method == 'POST': length = request.POST.get('length') sof_zman_1 = request.POST.get('sof_zman_1') sof_zman_2 = request.POST.get('sof_zman_2') sof_zman_tefila = request.POST.get('sof_zman_tefila') ad_image = request.POST.get('ad_image') day_details = MyDateDetails.objects.create( sof_zman_1 = sof_zman_1, sof_zman_2 = sof_zman_2, sof_zman_tefila = sof_zman_tefila, ad_image = ad_image, ) for file_num in range(0, int(length)): Image.objects.create( date = date, image = request.FILES.get(f'images{file_num}') ) context = {'date': date} return render(request, 'luach/create_day.html') urls.py urlpatterns = [ … -
Can I annotate onto a select_related() field?
I want to annotate how many cars each owner owns as an optimization. This may seem like an odd way to do this, but I'm using Django Rest Framework and the serialized Car has an Owner field, and the Owner serialization contains a dynamically calculated count of how many cars the user owns. This is sort of what I want... cars = Car.objects.select_related('owner').annotate(owner__cars_count=Count('owner__car')) ...except what I want is cars[0].owner.cars_count not cars[0].owner__cars_count. I want to annotate the owner, not the car so that DRF has the field available when it serializes the owner. Swapping out objects in Owner isn't going to work either because select_related doesn't on Car doesn't use the Owner manager. This is spookily similar to Nested annotate fields in Django REST Framework serializers, but the accepted answer does what I'm already doing -- calculating it per record in a SerializerMethodField. A not accepted answer describes doing this with prefetch_related not select_related. Since this is DRF, alternatively perhaps I can copy the annotation from Car.owner__cars_count to Car.owner.cars_count before it gets to the nested serializers? -
Do I need to be able to access the Django admin page?
As a follow up to this question Django Server Unable to Open Admin Page, seeing as no one was able to answer, I am all out of ideas. I don't know how to solve this, and am wondering if I should just avoid using the Django admin page since the other pages work fine. Can I achieve all of the admin functionality from the command line? Alternatively, does anyone have any ideas as to how I could solve this? -
Remove extra line in sending email from Smtplib
I am trying to send an email from smtplib and although it is sent correctly, it adds a line similar to this at the end of each email --=-y8GVNOpCpe7m9o/JKK53-- I would like to know how to eliminate it this is my view mailcontext = {'date': datetime.now(), 'group_name': datos_cotizador.nombre, 'broker': self.request.user.first_name + ' ' + self.request.user.last_name, 'number': datos_cotizador.id, 'group_type': 'small' if datos_cotizador.cant_empleados < 101 else 'large'} new_message = render_to_string('mail_text_inform_sales.html', mailcontext) server = smtplib.SMTP(base.EMAIL_HOST, base.EMAIL_PORT) server.starttls() server.login(base.EMAIL_HOST_USER, base.EMAIL_HOST_PASSWORD) fromaddr = "Notifications (Do Not Reply)<no-reply@example.com>" msg = MIMEMultipart('alternative') msg['From'] = fromaddr msg['To'] = 'myemail@gmail.com' msg['Subject'] = "Subject" msg.add_header('Content-Type', 'text/html') msg.set_payload(new_message) text = msg.as_string() toaddr = 'myemail@gmail.com' toaddr = toaddr.split(', ') server.sendmail(fromaddr, toaddr, text) server.quit() in the html template i only have a div with content example content -
Python (Django): 'self.text' is unsubscriptable
I am learning Django following the book "Django for beginners", there is a strange problem. The code snippet below actually works, but Pylint keeps showing me an error, and I know the error happens. But the author did nothing about it. Does anyone know why, please? The code snippet is from my app folder's models.py. from django.db import models # Create your models here. class Post(models.Model): text = models.TextField() def __str__(self): return self.text[:50] The pylint error message in my vscode editor is - Value 'self.text' is unsubscriptable My environment: Win 10, Python 3.6, Django 3.0.1 -
Django renders images multiple times for a .html
I have a web page with a django 1.7.1 back-end. I use it for an image gallery. For a certain page, I make a request for images. In the views.py I basically have this: def get_query(req, data_request): filter = get_filter(data_request) # the request has some filtering instructions items = Image.objects.filter(**filter) # query a django model # only return max 20 images items = items[0:20] print(len(items)) # indeed returns 20 - only 20 items are given to render() context = { 'items ':items , } return render(req, 'query_results_painting.html', context) This all appears to work properly. In the .html file passed to render I have the following: {% for painting in items %} <div class='search-result-painting-item'> {% autoescape off %} <p class="title"> {{painting.title | safe}} </p> <p class="artist"> {{painting.artist.name | safe}} </p> <p class="year"> {{painting.year}} </p> {% endautoescape %} <img src= {{painting.image_200.url}}> </div> {% endfor %} As can be expected, this returns the following elements structure: The issue is as follows: Many images show up twice, while the rest only shows up once (as intended!). This result in more then 20 elements being created while rendering, sometimes as many as 40! See for example: Note that, the original 20 items do not have … -
Django : global search in different model
I hope you're well. I'm beginning with Django. After creating my single search views (for one model), I'd like to create a global search with more than one model in different app. I need you because I got nothing in my result. So I don't understand what's wrong in my code. It's my first global search for sure there is mistake. user/views.py from nutriscore.models import Post from itertools import chain from django.db.models import Q # global search class GlobalSearchView(ListView): template_name = 'search_global.html' def get_queryset(self): # new query = self.request.GET.get('q', None) if query is not None: nutri = Post.objects.filter( Q(title__icontains=query) | Q(slug__icontains=query) | Q(typederepas__name__icontains=query) | Q(prixrepas__name__icontains=query) | Q(vitesserepas__name__icontains=query) | Q(force__name__icontains=query) | Q(bienfaitrepas__name__icontains=query) ).distinct() user = UserProfile.objects.filter( Q(pays__icontains=query) | Q(town__icontains=query) | Q(user__username__icontains=query) | Q(mealtrend__name__icontains=query) | Q(pricetrend__name__icontains=query) | Q(speedtrend__name__icontains=query)| Q(strengthtrend__name__icontains=query) | Q(wellnesstrend__name__icontains=query) ).distinct() results = chain(nutri, user) return results user/urls.py path('search/', GlobalSearchView.as_view(),name="global_search"), user/templates/global_search.html <div class="row" id="collapseNutriscore"> {% for nutri in results %}<div class="col-sm-4">{{ post.title }}</div>{% endfor %} </div> <br> <br> <br> <div class="row collapse" id="collapseCooker"> <div class="col-sm-4">{% for user in results %}<div class="col-sm-4">{{ userprofile.user.username }}</div>{% endfor %}</div> </div> -
ManyToMany Field Refere to Itself
How can make my model so that its ManyToMany Refer to User class User(AbstractUser): teacher_or_student = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) grade = models.CharField(max_length=100) laptop_yes_or = models.CharField(max_length=100) students = models.ManyToManyField(User) -
Django + Celery application works locally but not when deployed
I have celery tasks which executed fine locally using ampq broker. However, it doesn't work when deploy my django app to kubernetes. I can execute the task on worker pod and everything works fine 'the ampq server is connected', but if I try to execute it in backend pod I got [Errno 111] Connection refused. Any idea what may cause that issue?