Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
how to prevent the resubmition of the form in Django template
{% extends 'base.html' %} {% load buttons %} {% load static %} {% load custom_links %} {% load helpers %} {% load plugins %} {% block content %} <form action = "add" method= "post" enctype="multipart/form-data" class="form form-horizontal" id="reportForm"> {% csrf_token %} <div class="panel panel-default"> <div class="panel-heading"> <strong>Add Report</strong> </div> <div class="panel-body"> <table class="table table-hover report-body attr-table"> <tr> <td>URL</td> <td> <input type="text" required="required" name="src"> </td> </tr> <tr> <td>WIDTH</td> <td> <input type="number" required="required" name="width"> </td> </tr> <tr> <td> HEIGHT</td> <td> <input type="number" required="required" name="height"> </td> </tr> <tr> <td> NAME OF THE REPORT</td> <td> <input type="text" required="required" name="report_name" > </td> </tr> </table> <input type="submit"> </div> </div> </form> {% endblock %} i don't have the database for the checking the exiting record . Here is one problem in my from when the user click on the reload on top of the web page ...then same form with same record will generated again ...how to prevent this resubmition the form -
How to clear selection in Django autocomplete field
I have a model admin. class Some(admin.ModelAdmin): ... autocomplete_fields = ['user', ...] When user is selected I cannot clear selection in admin interface. Is there some setting I missing? -
How to retrieve latest model object of a logged in user who has already submitted the form?
I tried something like this customer=Customer.objects.filter(id=request.user.id).latest('first_name', 'last_name') customer.first_name However this fetches me the old data of the logged in user. I read about latest() method and implemented this customer=Customer.objects.latest('id') but as we know this will only render the last submission details not necessarily of the user who has logged in. Here is my model.py for reference class Customer(models.Model): id=models.AutoField(primary_key=True, default=None) customerReg=models.OneToOneField(User, on_delete=models.SET_NULL, null=True, blank=True) first_name=models.CharField(max_length=200, blank=False, default=None) last_name=models.CharField(max_length=200, blank=False, default=None) So, how would I query that information? -
Filter data based on intervals in Django
I have following model: class MyModel(models.Model): due = models.DateTimeField(null=True) max_days_before_due = models.IntegerField() I would like to filter out instances or rows that are past this due, ie. when due minus max_days_before_due is in the past. I am using this query: current_date = timezone.now() MyModel.objects.annotate( counted_days=Case( When( due__isnull=False, then=ExtractDay(F('max_days_before_due')-current_date) ), default=0, output_field=IntegerField() ) ).filter( due__gt=F('counted_days') ) I am receiving this error: django_1 | File "/usr/local/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute django_1 | return self.cursor.execute(sql, params) django_1 | django.db.utils.ProgrammingError: function pg_catalog.timezone(unknown, interval) does not exist django_1 | LINE 1: ... '2020-08-26T15:03:11.111165+00:00'::timestamptz) AT TIME ZO... django_1 | ^ django_1 | HINT: No function matches the given name and argument types. You might need to add explicit type casts. When I delete the subtration from the annotation, the error does not show, but I need to be able to count the timedelta. Otherwise if I set the due to, let's say, 2020-08-30 and current_date is 2020-08-26 it returns 30 in the counted_days field instead of 4. I've been trying to use this question and these docs as reference. I am using PostgreSQL in version 10 and Django in version 1.11, Python 3.4. -
Can't go to the detail view in Django
my detail view supposed to give me the primary key but why I got this error? error I got django.urls.exceptions.NoReverseMatch: Reverse for 'leaveform_detail' with no arguments not found. 1 pattern(s) tried: ['student\\-leaveform\\-detail/(?P<pk>[0-9]+)/$'] models.py class StudentLeave(models.Model): student = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) date_created = models.DateTimeField(auto_now_add=True) leave_from_date = models.CharField(max_length=200) leave_till_date = models.CharField(max_length=200) student_name = models.CharField(max_length=200) leave_reason = models.TextField() def __str__(self): return self.student_name views.py class Student_leaveform_detailView(DetailView): model = StudentLeave template_name = "attendance/content/student/student_leaveform_detail.html" urls.py path('student-leaveform-detail/<int:pk>/', Student_leaveform_detailView.as_view(), name="leaveform_detail") I used this button to got to the route <a href="{% url 'leaveform_detail' %}" class="btn btn-info mt-3 ml-auto">View</a> -
Extending graphene-django FILTER_DEFAULTS does not work
I am generating dynamically schema definitions iterating over django models in my project like so: My project includes some custom model fields that need to have mapped filters to them or otherwise graphene-django will throw errors like: AssertionError: MyModelSet resolved field 'custom' with 'exact' lookup to an unrecognized field type CustomField. Try adding an override to 'Meta.filter_overrides'. See: https://django-filter.readthedocs.io/en/master/ref/filterset.html#customise-filter-generation-with-filter-overrides I have extended the graphene_django.filter.filterset.GrapheneFilterSetMixin.FILTER_DEFAULT with my custom field->filter mapping as suggested in graphene-django github issue Extending global filter set overrides #1031. This makes the aforementioned error go away, however it does not seem to use the filter class that I map to the custom field. It rather uses default django_filter ChoiceFilter from which that filter inherits: class CustomChoiceField(forms.ChoiceField): def valid_value(self, value): """Check to see if the provided value is a valid choice.""" print('VALIDATING !!!!!') text_value = str(value) for k, v in self.choices: if isinstance(v, (list, tuple)): # This is an optgroup, so look inside the group for options for k2, v2 in v: if value == k2 or text_value == str(k2): return True else: if value == k or text_value == str(k): return True return False class ChoiceFieldFilter(CustomChoiceField, ChoiceIteratorMixin): iterator = ChoiceIterator class CustomChoiceFilter(ChoiceFilter): field_class = ChoiceFieldFilter Running query to … -
Django not picking up the functions
I have tried every thing from making new function and saving every file thrice but nothing seems to work. And its my first time using Django if any one find anything please point it out... Note: Django ver 3.1 Server Error: path('', views.home_view), AttributeError: module 'pages.views' has no attribute 'home_view' settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products', 'pages', ] views.py from django.http import HttpResponse # Create your views here. def home_view(*args, **kwargs): return HttpResponse("Hello world") urls.py from django.contrib import admin from django.urls import path from pages import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_view), ] -
Django Rest Framework Generic ViewSet doens't show parameters and models in Swagger
I try to develop an backend API using Django, the rest framework and swagger (using drf_yasg). To get started quickly I tried to generate the viewsets and serializers, but in Swagger the parameters and schemata/ models aren't shown. If I would manually code this for each model it would work, but I would need to adjust each serializer/ viewset for each change in the models. This is my code for the generation: # Template class for serializing class GenericSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' depth = 3 # Unified Generic API view for all models in shop.models class GenericAPIView(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) lookup_fields = ['id'] def dispatch(self, request, *args, **kwargs): for model_name, model in apps.get_app_config('api').models.items(): if request.path.split('/')[2] == model._meta.verbose_name_plural.title().lower(): self.model = model self.queryset = self.model.objects.all() serializer = GenericSerializer serializer.Meta.model = self.model self.serializer_class = serializer return super().dispatch(request, *args, **kwargs) This way the default ModelViewSet routes show up in swagger, but the parameters for each model are missing and the models itself. I confirmed that the model is assigned and despite my code it shows a warning in the console that I should provide a serializer_class or override the method (but I think it should be fine because I assign it manually). -
Can't set any background image for jumbotron-local or remote
I have just overridden the bootstrap here and I made sure it's pulling from my local css, any other changes to it do work, but when I try to insert a background-image nothing happens. I tried all local path variations for images and remote URLs as well. I'm using Django and had a problem earlier with my settings.py -can that be causing it?? Thanks #settings.py STATIC_URL = '/static/' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' #this is the jumbotron html <section class="jumbotron text-center"> <div class="container"> <h1>Album example</h1> <p class="lead text-muted">Something short and leading about the collection below—its contents, the creator, etc. Make it short and sweet, but not too short so folks don’t simply skip over it entirely. </p> <p> <a href="#" class="btn btn-primary my-2">Main call to action</a> <a href="#" class="btn btn-secondary my-2">Secondary action</a> </p> </div> </section> #and the custom .css .jumbotron { padding: 2rem 1rem; margin-bottom: 2rem; background-color: #c5b8b8; border-radius: .3rem; background-image: url("https://en.wikipedia.org/wiki/Image#/media/File:Image_created_with_a_mobile_phone.png"); background-repeat: no-repeat; background-position: bottom center; background-size: cover; } -
Logout function provides RecursionError error
I have this function in views.py: def logout(request): logout(request) return HttpResponse('Logged out succesfully!') and this is the error I get when going to /logout RecursionError at /logout/ maximum recursion depth exceeded -
DRF how to update email with @action?
When I try to update User it's create new user. Where is my problem? View class UserViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer def get_object(self): return self.request.user Action @action(methods=['PATCH'], detail=False) def change_email(self, *args, **kwargs): user = self.get_object() serializer = serializers.UserEmailSerializer(data=self.request.data, context={'request': self.request}) serializer.is_valid(raise_exception=True) serializer.save() self.send_email(user.email) return Response({'Confirm yours new email'}, status=status.HTTP_200_OK) Serilializer for action class UserEmailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email') read_only_fields = ('id',) -
`groupby` by date with timezone influence among Django/Jinja2 environment
In PostgreSQL I store time information in INT (meaning UNIX timestamp) with django-unixtimestampfield. Now I am using django-jinja (Jinja2 backend) to render templates, and also, I am using groupby to group results from transaction data, like this: {% for d, t_day in transactions|groupby('updated_at.day') %} <p>{{ d }}</p> {% for t in t_day %} ... {% endfor %} {% endfor %} But updated_at.day will be calculated by UTC, not by the local timezone. How should we influence local timezone information into groupby()?