Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and HTML table not displayed properly on Linux
I come with a weird case. I have a webapp with multiple pages but 1 of them is unproperly displayed when i run it on linux. Ill post 2 screenshots: As you can see, every row stops after the Mainhand column, so half of the table is only displayed... {% elif i.categoryid.categoryid == 2 %} this is the line that seems to have the issue.. Any idea? I repeat that on windows it is properly displayed. -
How to access parent model fields?
models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='profile_images', blank=True) def __str__(self): return self.user.username views.py @method_decorator(login_required, name='dispatch') class UserUpdateView(UpdateView): model = UserProfile fields = ['image'] template_name = 'accounts/my_account.html' success_url = reverse_lazy('Accounts:my_account') def get_object(self): return self.request.user I want to access the first_name, last_name, email properties of the User model. I am getting error if I user those fields in views. What am I doing wrong here? Thanks in advance -
Need help troubleshooting google app engine job that worked in dev but not production
I have been working on a website for over a year now. Using Django and Python3 primarily. A few of my buddies and I built a front end where a user enters some paramters and submits, this goes to the GAE to run the job and return the results. In my local dev environment, everything works peachy. I have two separate dev environments. One builds the entire service up in a docker container. This produces the desired results in roughly 11 seconds. The other environment runs the source files locally on my computer and connects to the PostGres DB hosted in google cloud. The python application runs locally. It takes roughly 2 minutes for it to run locally, a lot of latency between the cloud and the post/gets from my local machine. Once I perform the gcloud app deploy and attempt to run in production, it never finishes. I have some print statements built into the code, I know it gets to the part where the submitted parameters go to the python code. I monitor via this command on my local computer: gcloud app logs read I SUSPECT that since my local computer is a beast (i7-7770 processor with 64 … -
How to use a HTML variable inside another
I have a piece of code that loops through some objects. I have another set of objects that i want to loop through too. is there a way i can use the forloop.counter to increase the image object? <div class="row"> {% for project in projects.all %} <div class="col-md-4 col-sm-6"> <div class="news-section-single"> <div class="news-img-main"> <div class="news-img"><img src="{{ images.{{ forloop.counter }}.image.url }}" alt="" data-popupalt-original-title="null" title=""> <div class="news-list"> <ul> <li><i class="fa fa-clock-o" aria-hidden="true"></i> {{ project.date }}</li> </ul> </div> </div> </div> <div class="news-head"> <h3>{{ project.title }}</h3> </div> </div> </div> {% endfor %} </div> Hope that makes sense what i'm trying to do. I'm sure someone will tell me i'm trying to do the wrong thing so here is my views.py def projects(request): projects = Project.objects.all() images = ProjectImage.objects.all() return render(request, 'projects.html', {'projects': projects, 'images': images}) And my models.py class Project(models.Model): title = models.CharField(max_length=250) body = models.TextField() date = models.DateField() def __str__(self): return self.title class ProjectImage(models.Model): project = models.ForeignKey(Project, related_name='images', on_delete='CASCADE') image = models.ImageField() -
Implementing HTTP Digest Auth for Django view
I need to implement a view in Django that requests digest auth instead of basic auth. The authentication should not be linked to the default User class but instead to a custom model. I tried with django-digest but it is outdated and not usable with recent versions of Django (ModuleNotFoundError: No module named 'django.utils.importlib'). I need a very simple digest auth solution for my Django application. -
Apache2 + mod_wsgi + python 3.6 not responding
I'm deploying a Django app with python 3.6 and virtualenv in an Ubuntu 18.4 server. This is my apache config <VirtualHost *:80> ServerName myapp.com Redirect / https://myapp.com/ </VirtualHost> <VirtualHost *:443> ServerName myapp.com SSLEngine On SSLCertificateFile "/etc/apache2/ssl/myapp.com.crt" SSLCertificateKeyFile "/etc/apache2/ssl/myapp.comv.key" SSLCertificateChainFile "/etc/apache2/ssl/myapp.com.crt" SSLProxyEngine On ProxyPass / http://localhost:8059/ connectiontimeout=5 timeout=300 ProxyPassReverse / http://localhost:8059/ ProxyPass /static/ ! ProxyPass /media/ ! Alias /static/ /home/ubuntu/myapp/assets/ Alias /media/ /home/ubuntu/myapp/data/ <Directory /home/ubuntu/myapp/data> Require all granted </Directory> <Directory /home/ubuntu/myapp/assets> Require all granted </Directory> <Directory /home/ubuntu/myapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myapp python-path=/home/ubuntu/myapp:/home/ubuntu/myapp/venv/lib/python3.6/site-packages WSGIProcessGroup myapp WSGIScriptAlias / /home/ubuntu/myapp/wsgi.py </VirtualHost> if I run mod_wsgi-express module-config I get LoadModule wsgi_module "/home/ubuntu/myapp/venv/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so" WSGIPythonHome "/home/ubuntu/myapp/venv" which is the virtualenv I want to use. Nonetheless when I try to access myapp.com I get timedout and there is nothing in error.log or access.log error.log [Sun Sep 30 11:42:37.066273 2018] [core:notice] [pid 628:tid 140584565169088] AH00094: Command line: '/usr/sbin/apache2' [Sun Sep 30 11:42:39.728096 2018] [mpm_event:notice] [pid 628:tid 140584565169088] AH00491: caught SIGTERM, shutting down [Sun Sep 30 11:42:39.812550 2018] [mpm_event:notice] [pid 882:tid 140042546797504] AH00489: Apache/2.4.29 (Ubuntu) OpenSSL/1.1.0g mod_wsgi/4.6.4 Python/3.6 configured -- resuming normal operations [Sun Sep 30 11:42:39.812642 2018] [core:notice] [pid 882:tid 140042546797504] AH00094: Command line: '/usr/sbin/apache2' access.log 51.38.12.21 - - [30/Sep/2018:08:20:14 +0000] "GET / HTTP/1.1" … -
How to keep previous submitted value from user, add it to next one, and so on. Django 2.1
i am new to Django and Python. I wanna achieve something and i struggle with that for over a week. I have a simple form with one field where user can input some number, after he submit it, i return to him that same number on same page. If he submit again i wanna add that number with previous one. How can i do that? For example: User submit 1 I return 1 User submit 3 i return 4 i wanna keep previous submitted number and add it do next one. -
How secure is jinja logic for blocking unauthorized access
I understand everything is hackable given enough time and effort, however I would like to know if my method described below is "somewhat" secure. I have built a Django powered webapp, and I would like only certain users to have access to certain information. I'm sure there are many ways to do this. I have found using python and Jinja logic does exactly what I want, and I can't seem to poke any security holes in this method, but I am the farthest from an expert on this as it gets. This is my Views.py: Essentially this view will grab the current users "customerTag" (a unique identifier for this group of customers set during signup). This view then checks to ensure the current users customerTag matches the customerTag of the information it is trying to access, then passes a string to the HTML template. The HTML template (below) then decides what to display. from django.shortcuts import render from defaults.forms import processParams from django.views.generic import TemplateView from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views import generic from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from . import models from django.contrib.auth.mixins … -
Defining variables in django template
I have a dictionary and a list. The dictionary contains the title and link of an youtube video and list contains the description. I want to print the respective tile and description. {% for key,values in link.items%} <a><h4>{{key}}</h4></a> <p><b>Description:</b> {{description[how do i iterate the description]}}</p> {%endfor%} I tried to create a variable {{i}} and increment it but didn't work. -
Inheritance with nested models and inbetween relations
I am experimenting a smart calculator (with some strange operating methods). It manipulates objects which share common methods of calculus. These objects being operands and various operators. Here I am trying with only one kind of operator : PolarBinaryOperator (could be « power » for example), but there will be many others. PolarBinaryOperator links two operands. Operands don’t share attributes, only methods like calculation methods. Inheritance : I can’t make operand an abstract class because it needs to be linked by operators like the PolarBinaryOperator. I can’t make all operands a unique model named operand with some null values, always the same giving the real nature of the operand. But giving the type of operator, the linked objects could be other operands or objects. I have tried using content type for generic operator relations but it gives poor speed performance. I have tried multi-table inheritance but it gives poor speed performance. Am I stuck with the content type solution ? Or could there be another possible pattern ? class Operand(models.Model): def _nexts(self): nexts = Operand.objects.filter( lien_operand_origin__operand_origin=self) return nexts def calculate(self): pass def calculate2(self): pass class Integer(Operand): value = models.models.IntegerField() class Operator(Operand): # Relations operand_origin = models.ForeignKey( 'Operand', related_name='destination_operand') operand_destination = … -
Not created class table (not seen in Admin)
I create new model: class Subscribe(models.Model): title = models.CharField(max_length=30); subscribers = models.ManyToManyField(User) Create migration: E:\Dropbox\djagoBlog\blog>python manage.py migrate --fake account zero Operations to perform: Unapply all migrations: account Running migrations: No migrations to apply. Run migation: python manage.py migrate account Operations to perform: Apply all migrations: account Running migrations: Applying account.0001_initial... OK Byt in Admin I not see new table Subscribe What problem? -
where to install markdown if im using angular for the frontend and django for the backend?
Hello I would like to know where I need to install markdown I am using angular for the frontend and django for the backend with rest_framework and to show the user after the markdown the frontend need to support it no? and the backend need to support it as well and as I know rest_framework supports markdown so where I need to install only at the backend/frontend or both? -
How to manipulate response in django middleware when using django rest framework?
I am using django rest framework. Due to some reason I want the response data be in below format { code: http_code, data: original_data } So I write a django middleware to process the response. The logic is as below: class WrapResponse(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) original_content = json.loads(response.content) wrapped_response = json.dumps({'data': original_content, 'code': ''}) response.content = wrapped_response return response Normally this will be fine. But there is one problem. The response returned by rest framework is a rendered view. So in some situation like viewing the api from brower, the response.content will be a rendered html. And this will cause error. I know that I can change the response before view return. But I really want to do this with middleware. Is there any good way to do so? -
Using a different counter from different object_list than the one used in for_loop
I want to count the objects in my template but since i am using pagination to divide the into pages i want to use counter from different object_list than the one used in forloop. This is my template: {% extends 'base.html' %} {% block content %} {% if user.is_superuser %} <div class="row"> <div class="col-sm-4 offset-sm-4"> <form class="form-inline md-form form-sm" method="GET" action=""> <i class="fa fa-search" aria-hidden="true"></i> <input class="form-control form-control-sm ml-3 w-75" type="text" placeholder="搜索货品 Znajdź część" name="q" value="{{ request.GET.q }}"/> </form> </div> </div> <br/> <hr/> <div class='row'> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Image</th> <th scope="col">Product name</th> <th scope="col">Price (cost)</th> <th scope="col">Price (PL)</th> </tr> </thead> <tbody> {% for product in objects %} <tr> <th scope="row">{{forloop.counter}}</th> <td><img class="img img-fluid rounded" width="200" height="136" src="{{ product.photo.url }}"></td> <td>{{product.product_name}}</td> <td>{{product.price}}</td> <td>{{product.price_pol}}</td> </tr> {% endfor %} </tbody> </table> </div> <div class="col-sm-4 offset-sm-4" align="center"> <div class="pagination"> <span class="step-links"> {% if objects.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ objects.previous_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">previous</a> {% endif %} <span class="current"> Page {{ objects.number }} of {{ objects.paginator.num_pages }}. </span> {% if objects.has_next %} <a href="?page={{ objects.next_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">next</a> <a href="?page={{ objects.paginator.num_pages }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">last … -
how can i check duplicate data in my django database comparing with form data in generic view(Updateview)
I made a Updateview method in django to update firstname, lastname, mobile etc..but how can i check the the data received by generic view through the form is previously exist for example i want to avoid duplicating of mobile number with the model User in database i tried by approaching def post() method but i got lot of errors can u teach me the exact way for avoiding duplicate data inserting View code class UpdateMprofile(mixin1, mixin2, UpdateView): login_url = reverse_lazy('loginurlhere') model = User fields = ['first_name', 'last_name', 'mobile', 'avatar'] success_url = reverse_lazy('redirectedviewurlhere') -
Django - how to update content on page after it was changed on the server side?
on my html page I have a drop-down list, that is filled as such: <select id="ddlGroups"> <option value="All">All</option> {% for element in objectlist %} <option value={{ element.id }}>{{ element.group_name }} {% endfor %} </select> The variable objectlist is passed when the page is loaded, through this view: @csrf_protect @login_required def index(request): grouplist = Group.objects.all() return render(request, 'policies.html', {'objectlist': grouplist}) I also have a button, that allows to add more groups to the drop-down list. After the button is pressed the following view is called, and new group is created. def add_group(request): if request.method == 'POST': group_name = request.POST.get('groupName') if Group.objects.filter(group_name=group_name).exists(): return JsonResponse({'status': 'false', 'message': 'Group already exists'}, status=400) group = Group.create(group_name) group.save() return HttpResponse("Successful") return JsonResponse({'status': 'false', 'message': 'error'}, status=400) Right now, if I want to see the changes in the content of the dropdown list, I have to reload the page. My question is how can I see see the changes right away, without having to reload the page? Thanks in advance. -
Django. Query by reference table field with aggregate function
I have the models. class Vote(models.Model): title = models.CharField(max_length = 50, blank=False) start_date = models.DateTimeField(blank=False) end_date = models.DateTimeField(blank=False) votes_to_win = models.IntegerField(blank=False) class Character(models.Model): name = models.CharField(max_length=20) image = models.ImageField(upload_to='img') age = models.IntegerField() vote = models.ManyToManyField(Vote, through='VoteForCharacter') class VoteForCharacter(models.Model): vote = models.ForeignKey(Vote, on_delete=models.CASCADE) character = models.ForeignKey(Character, on_delete=models.CASCADE) votes_number = models.IntegerField(default=0) class Meta: unique_together = ('vote', 'character',) And I want to select all votes where all characters have number of votes less than needed to win in vote (active votes). What Iam trying to do is active_votes = Vote.objects.filter(votes_to_win__gt=Max('voteforcharacter__votes_number')). But I got an error django.db.utils.OperationalError: a GROUP BY clause is required before HAVING -
How to get list of model objects requested for deletion in admin panel in Django
I have this simple Django app which uses admin panel as a user portal to add and delete model objects.On addition of each model object I am adding a related data file in S3, how can I get the list of objects requested for deletion from the "delete selected" action, so that the particular object's file in S3 can be deleted. I tried searching for the related function definition in admin.ModelAdmin class but no help. -
How to capture the Model.DoesNotExist exception in Django rest framework?
In django rest frame work. When you query a database model and it do not exist you will hit a exception as below ModleName.DoesNotExist This exception will change according to the model name. For example: Query modle Car will raise Car.DoesNotExist Query model Plane will raise Plane.DoesNotExist This cause trouble that you can not catch the exception at one common place. Because you do not know the parent class of the Exception. You have to catch the exception every time you query a model , for example: try: return Car.objects.get(pk=1) except Car.DoesNotExist: raise Http404 Why django design the exception like this? Is it possible to capture the exception with its common ancestry? -
Django F expression and ArrayField position
I have a problem with Django and would like to ask for some advice: One of my models contains specific indicators with variable values. This is why I am using an Arrayfield for those. For example one Indicator has 3 values, another only 2 and some only have 1 value. Now I want to compare values from within the Arrayfield with each other. So I know there are those fancy F Expressions and I tried to use them, but here I am stuck, because it seems like F doesn't allow an positional-lookup from inside ArrayField. Does anyone know if i can use F for positional lookup of arrayfield? Or do I have to make a direct SQL-Call from Django or change my db somehow to make one value per field? Here is the Model: class Indicators(models.Model): datetime = models.DateTimeField(default=datetime.now) name = models.TextField(default="none") values = ArrayField(models.FloatField(default=0)) This is what I want to achieve: indicator_object = Indicators.objects.filter(name='compareable', values__0=F('values__1')).values_list('values__0') And it raises an Exception.. operator does not exist: double precision = double precision[] LINE 1: ...areable' AND "vanillacore_indicators"."values"[1] = ("vanill... From the Exception in seems like I am not allowed to give ArrayField position to F Expression (or that Django ignores the position..). … -
_reverse_with_prefix() argument after * must be an iterable, not int
I have used Django's reverse multiple times in the past but somehow I am getting this error today which doesn't seem intuitive enough to debug: TypeError: _reverse_with_prefix() argument after * must be an iterable, not int Here's the code in the view where I am using it: from django.urls import reverse ... ... def show_scores_url(self, obj): scores_url = reverse('get_scores', args=(obj.pk)) return format_html('<a href="' + scores_url + '">Scores</a>') ... ... -
My custom Django admin group form does not save selected users
Since the default django admin group form does not have field for selecting users in a group. I Wrote down some codes which i got online to add the selected users field.Everything is working just fine. Until i tried saving the group form i created, the form does not save selected users for the group i just saved . That is the selected user field for the group shows empty after saving the group. Below is my code my custom form for adding users in a group from admin class GroupAdminForm(forms.ModelForm): class Meta: model=group exclude=[] users=forms.ModelMultipleChoiceField(queryset=User,objects.all(),widget=FilteredSelectMultiple('users',False),required=False) def __int__(self,*args,**kwargs): super(GroupAdminForm,self).__int__(*args,**kwargs) if self.instance.pk: self.fields['users'].initial=self.instance.user_set.all() def save_m2m(self): self.instance.user_set=self.cleaned_data['users'] def save(self,*args,*kwargs): instance= super(GroupAdminForm,self).save() self.save_m2m() return instance This code gives me the desired form to add users to a group from the admin . But my biggest challenge is, when i save the group , the group is not saved with the selected users in the group. Meaning the field of users in the group appears empty after saving groups with selected users in the group. Please , how can i go about solving this problem . I need to save the group successfully with selected users. -
django-filter messing around with empty field
I setup django-filter to filter some of my listings. Here is one of them, with a custom form: class BookingListFiltersForm(forms.Form): state__in = forms.MultipleChoiceField( choices=Booking.STATE_CHOICES, required=False, label=_("État"), widget=forms.CheckboxSelectMultiple) source__in = forms.ModelMultipleChoiceField( queryset=Platform.objects.all(), required=False, label=_("Source"), widget=ModelSelect2Multiple( url='autocomplete:platform')) class BookingManagerFilter(filters.FilterSet): payments__date = filters.DateFilter(method='payments__date_filter') payments__method = filters.ChoiceFilter( method='payments__method_filter', choices=BookingPayment.METHOD_CHOICES, ) class Meta: model = Booking fields = { 'period': [ 'endswith', 'endswith__gte', 'endswith__lte', 'startswith', 'startswith__gte', 'startswith__lte', ], 'state': ['in'], 'source': ['in'], 'booking_date': ['date', 'date__lte', 'date__gte'], 'accommodation': ['in'], 'guest': ['exact'] } def get_form_class(self): return BookingListFiltersForm def payments__date_filter(self, queryset, name, value): return queryset.filter(**{name: value}) def payments__method_filter(self, queryset, name, value): return queryset.filter(**{name: value}) The form is submitted by GET method. When the field "source__in" is empty, the querystring looks like this "?state__in=1". In such case, I have no result in my page (which is unexpected). I looked at debug toolbar to have more information about the executed SQL query. Surprisingly, I found no SQL query for the related queryset! (while if querystring is "?state__in=1&source__in=2" for instance, the result is as expected, and I can find related queries in debug toolbar) So I tried to force the impression of the SQL query using print(str(filters.qs.query)). New surprise, this triggered an EmptyResultSet exception: Traceback: File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response … -
How to capture exception in django rest framework with django middleware?
Django middleware have a process_exception hook which can be used to capture excepition and handler. But there is some problem while using django restframe work class ExceptionHandler(MiddlewareMixin): @staticmethod def process_exception(request, exception): if isinstance(exception, ValidationError): return Response(data=exception.messages, status=status.HTTP_400_BAD_REQUEST) For example, I try to use above middleware to capture the ValidationError and return HTTP 400 But it will not work and raise below error AssertionError: .accepted_renderer not set on Response It turns out that the restframe work view layer will add a .accepted_renderer to the response. If I handle the exception outside view. This attribute will be missed and cause another exception. So my question is: Is it wrong to handle exception in middleware when using django restframework? What is the correct way to do ? -
Django decorator @permission_required
I'm new to Django. I'll be appreciate if anyone can help me. When I was trying to use the decorator @permission_required in a view in Django, it always told that my app name is not defined. I put this before a view in request/views.py @permission_required(request.change_part_status) and got this error NameError: name 'request' is not defined Do I have to import something or is there something I missed?