Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to refresh an included Django template without refreshing the whole page?
I'm struggling with an issue similar to this one. I've got a Django template that includes a whole bunch of smaller templates with for-loops to render various aspects of my page. I'm wondering what the best way is to go about updating individual little templates to render them in the master template without having to do a whole page refresh. Does Django for example support some kind of React-like virtual dom to rerender only individual sub-templates? I understand that templates are being computed on the server and the generated HTML is then sent to the client for rendering so perhaps it's not possible to render templates in-place? The post above mentions passing data to the server with AJAX to refresh a particular template, but before I start revamping my page, I was wondering if that would work for rendering multiple templates at a time, and if so, if someone could point me to an example where this is explained in some detail; I've been looking, but couldn't find any. Thanks! -
Calling Python function from JS [duplicate]
I have a python django project. And I am trying to call a python function from JS. To start I’ve a html button that runs a JS function. It works fine: <input id="clickMe" type="button" value="clickme" onclick="show();" /> Currently I have this JS function just showing an alert. Like so. function show_eb_variable_table() { alert("Hello! I am an alert box!!"); } What I want to do is to instead of showing this alert I want to call and run a python function from my “plot.py” file in the project. The function I want to call is as so: def printing_something (request): print('hi') return render(request, 'index2.html', {}) Is there a way I can connect the JS to call the Python function? -
Django form validation only validating partially before submit/post
I have a customer registration form within a bootstrap modal, for this reason I would like to do some basic validation before posting. At the moment if you leave a field blank, if the string is too long or if there isn't a @ in the email then an alert appears, which is perfect. But, mismatching passwords, invalid email addresses like example@example submit. Surely that should fail the ValidateEmail regex? The validation failures are picked up fine in views after submission but getting back to the modal is the problem so I'd like them caught by the same pre-submission validation that picks up a blank fields. Or failing that, is it feasible to do an Ajax request on View and refresh the form asynchronously? Getting the form into json wouldn't be fun. Or should I just give up on django and use jquery validation? Forms: class CreateRegistrationForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for f in self.fields: self.fields[f].widget.attrs['class'] = 'form-control' class Meta: model = User fields = ["email", "password1", "password2", "first_name", "last_name"] Models: class User(AbstractBaseUser, PermissionsMixin): class Types(models.TextChoices): CUSTOMER = "CUSTOMER", "Customer" STAFF = "STAFF", "Staff" base_type = Types.CUSTOMER type = models.CharField( _("Type"), max_length=50, choices=Types.choices, default=base_type ) user_name = models.CharField(max_length=150) … -
Add a template folder selection for a django package
I am relatively new to django and am looking for help on custom package templates management. At work, we are using a home-made custom django package that we add to installed apps in our main projects. This package has tools and utilities, as well as the base templates that we derive from in main projects. What's changing? We need to update our frontend and are changing libraries, which has an impact on the templates in this custom package. With a view to avoid multiplying the custom package branches and versions (we already have a couple for different versions of django), and given that the templates in our existing applications will not all be updated at once, we wish to make it so that the main project will use either the old templates or the new version of templates (variable selection or default). What I aim for (if possible): adding a folder level in the custom package templates folder that the project will look in adding a variable (in the project's settings.py file for example) to indicate which template folder the main project needs to look for in the package not having to modify the old templates folder in the package, … -
django documentation user permission ambiguity on object level permission
I am getting my feet wet with django user permission and I am trying to: Create specific permissions for different models I have. Assign to some permissions to some users for only some instances of a specific model. So basically, user_i might have permission_a and permission_b on project_one but only permission_a on project_two. Looking at the documentation, I got that I can define a custom permission on a model by adding the following Meta to the class: class JobProject(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) .... class Meta: permissions = [ ("permission_a", "This is perm a"), ("permission_b", "This is perm b"), ] However, now I am not sure I understand how can I add permission_a to user_a only for a specific instance project_a of the JobProject class. Django documentation is indeed ambiguous on the matter. On one hand it states that I can use the method has_perm(perm, obj=None) to check if a user has a specific perm on a specific obj. On the other hand, there is no hint on how I can specify which specific object I want to add a permission for when I run user_a.user_permissions.add(permission_a) Any idea? I saw that django-guardian could be a valuable alternative but I … -
How to make many to one field reference in Django 3.2?
I'm working on a simple project in Django which is a To Do applictaion. Lately I have add to this project a login/register form, but despite that every user has their own account with their own credentials they access to the same data. I tried to use the models.ForeignKey(User, on_delete=models.CASACADE) but it shows me this error: django.core.exceptions.FieldError: Unsupported lookup 'user' for CharField or join on the field not permitted. To understand it better will show the full code: models.py from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE # Create your models here. class todo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content class User(models.Model): name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib import messages from .models import * from .models import __str__ from .forms import CreateUserForm # Create your views here. @login_required(login_url='login/') def home(request): user = request.user count_item = todo.objects.count() all_items = todo.objects.filter(content__user=user).order_by("created") context = {'all_items': all_items, 'count_item':count_item} … -
sudo supervisorctl status: gumi gunicorn ERROR (spawn error)
$ sudo supervisorctl status guni:gunicorn FATAL Exited too quickly (process log may have details) Process log details in short: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: all the packages are installed with their latest versions bit still I am getting these above errors after running sudo supervisorctl status output gumi:gunicorn: ERROR (spawn error) Any idea what I am missing? -
An if-statement based on src HTML
I have big html document with various images with href and src. I want to make an if statement based on the output of the src. <img class="img-fluid d-block w-100" src="/static/assets/img/{{ LANGUAGE_CODE }}/actionFlow({% if form.status.value|slugify == '1'%}taak-toegewezen{% else %}{{form.status.value|slugify}}{%endif%}).png" id="workflowVisual"> Example outputs can be: "/static/assets/img/en/actionFlow(taak-toegewezen).png" "/static/assets/img/en/actionFlow(firststep).png" Now, I want to create an if statement like so: {% if src== "/static/assets/img/en/actionFlow(taak-toegewezen).png"}{{instance.reviewer2}} {% else src== "/static/assets/img/en/actionFlow(firststep).png"}{{instance.reviewer1}}{%endif%} How do I do this in HTML? Best, Rob -
Using a ListCharField as a filter field
I am trying to implement an API which you would filter objects using a ListCharField called categories. I want an object to be filtered if any of the values in its categories field matches with the category being searched. With my implementation, objects are being matched only if all the values in the categories match. Example: Consider an object A with categories='fun','party' and B with categories='fun' Then http://127.0.0.1:8000/theme/?categories=fun does not match with A but with B only. Model: class Themes(models.Model): id = models.CharField(max_length=64, unique=True, default=gen_uuid4_th name = models.CharField(max_length=128) description = models.CharField(max_length=512) categories = ListCharField(base_field=models.CharField(max_length=32), size=5, max_length=(6*33), null=True) View: class ThemesView(viewsets.ModelViewSet): serializer_class = AgendaTemplateSerializer permission_classes = (IsMemberUser,) filter_backends = (filters.DjangoFilterBackend,) filterset_fields = ('categories',) def get_permissions(self): ... def get_queryset(self): return Themes.objects.filter(Q(team__isnull=True) | Q(team=self.request.mp.team.teamid), is_archived=False) \ .order_by('-created_at') -
Django CreateView pass additional context data
I have a form in a bootstrap modal, and I want to keep that modal open after submission. I am using CreateView and trying to pass an additional variable to the template in front-end where I could check if the flag is set or not, but the flag is always False even after submission. Here is what I have: views.py from django.urls import reverse from django.views.generic.edit import CreateView from .forms import MescForm from .models import Mesc class MescData(CreateView): model = Mesc form_class = MescForm template_name = 'Materials/mesc_data.html' successful_submit = False # Flag to keep the add entry modal open def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['successful_submit'] = self.successful_submit return context def get_success_url(self): return reverse('mesc') def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) form.was_satisfied = True if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form, **kwargs): # self.successful_submit = True return super(MescData, self).form_valid(form, **kwargs) And in Template, I'm checking it like this: {% if success %} <h1>Flag is set</h1> {% endif %} Is there a way to pass non-form-related data in CreateView to the template without having to change the url.py (i.e. adding variable data to url path)? -
JSON.parse in javascript not converting to array correctly
I have a queryDict in django. I'm serializing it documents = serializers.serialize('json', Documents.objects.filter(id=self.kwargs['pk'])) context['documents'] = json.dumps(documents) When I accept in javascript I got this JSON.parse("{{ documents|escapejs }}") -> &quot;[{&quot;model&quot;: &quot;documents&quot;, &quot;pk&quot;: I need to parse once more time to get correct arrray. Can someone help me? -
django-filter how to style RangeFilter?
I have a problem with styling a range input. I'm using django_filters.RangeFilter class on declaring my filter: parent__length = django_filters.RangeFilter(label="Length") It looks like this I wan't have this length input in one row seperated with "-" sign. I'm using bootstrap grid when im displaying that filters. Thank you in advance -
Create User and UserProfile on user signup with django-allauth
I am using django-allauth for taking car of accounts, login, logout, signup, but I need that on create the user must create a profile and I am using the model UserProfile as it can be seen on the code. The problem is that when I created the custom signup form, now it creates a user with [username, email, first_name, last_name, password] but it does not create a UserProfile. And I have three questions: How to create a User and a UserProfile on signup? How can add styling to the forms that come with django-allauth, i.e. at /accounts /login/ How can I modify so that when the user logs in, it will redirect him to /profiles/ instead of /accounts/profiles or is it better in terms of REST principles to have it /accounts/profiles/ if yes, then is it possible to modify the profiles app so that it can use django-allauth views? My custom signup form: # django_project/profiles/forms.py from django import forms from allauth.account.forms import SignupForm class CustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') bio = forms.CharField(max_length=255, label='Bio') def save(self, request): user = super(CustomSignupForm, self).save(request) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.bio = self.cleaned_data['bio'] user.save() return user Settings: # … -
How to deserialize a serialized queryset in Django?
views.py def ipd_report_view(request): report=IpdReport.objects.all() myFilter=IpdFilters(request.POST, queryset=report) report=myFilter.qs total1=report.aggregate(Sum('realization__amount_received')) total2=report.aggregate(Sum('realization__deficit_or_surplus_amount')) rp=serializers.serialize('json', report) request.session['report']=rp context={'report': report, 'total1':total1, 'total2':total2, 'myFilter':myFilter} return render(request, 'account/ipdreport.html', context) In another view function, I have to use the data in the session to be able to make the function export the data to an excel file. I did rp=request.session['report'], but this object is a string object, so how do I go about converting this back to a queryset? Or is there any other way to achieve this? -
Restricting access to some pages in Django
In my Django project, I want only the premium users to be able to access the sales page. So if a user's user_type is Trial, he/she can't be able to access sales page. For these non-premium users, I want to display another html (upgrade.html) to them Below is my view class SalesView(TemplateView, SingleTableView): model = Product table_class = ProductTable template_name = 'src/dashboard/sales.html' def get_queryset(self): ... ... def get_context_data(self, **kwargs): # my contexts goes here And this is my url path('sales', SalesView.as_view(), name='sales'), This is the normal view. Now I want to stop Trial users from accessing this page. Please how can I achieve this? My model has a field user_type which tells whether a user is a Trial or Premium user -
how to overwrite data in django?
I have two views where I tried to overwrite the data in one here's the first code: ** tafhist = APIHistory(API_Hist_Id= pi,Status='API has been Submitted',unique_Id='UNID1006',url=url) tafhist.save() ** here first i'm creating data and saving it. now in same location i want to update same column here's the 2nd code of it: ** tafhist = APIHistory(Status='TAF Started').filter(unique_Id=tuid) tafhist.save() ** in this line I was trying to update but not getting how to do that. can someone please explain? -
Can I make a movie theater seat reservation system by linking Django and JavaScript?
Today, when accessing the website of a movie theater, there is a graphic UI that informs the location and number of seats, and there is a function for the user to select a seat. I want to implement such a function, but when I try to do it, I have no idea how to handle it. For example, if there are 10x10 rows of seats, should I create a seat model in Django, create 100 objects there, and choose the method of linking them? First of all, the graphic function is written in JavaScript, but the rest is not progressing. This is my javascript code about seat table. {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="{% static 'movie/bootstrap/bootstrap.min.css' %}" rel="stylesheet" type="text/css"> <title>Pick your seat</title> <link rel="stylesheet" href="{% static 'ticket/css/seat_page.css' %}"> <style> .seat { width: 40px; height: 30px; } .clicked { background-color: #f4a7bb; color: #000000; } </style> </head> <body> <div class="screen-x"> <h2>SCREEN</h2> <div class="seat-table"> <div class="seat-wrapper"></div> </div> </div> </body> <script> let test = []; let selectedSeats = new Array(); let selectedSeatsMap = []; const seatWrapper = document.querySelector(".seat-wrapper"); let clicked = ""; let div = ""; for (let i = 0; i < 18; i++) … -
How to don't save null parameter in table if got parameter with null field in Django
I have table with some parameters like this: class Education(models.Model): title = models.CharField(default=None, max_length=100) content = models.TextField(default=None) In Django request from client maybe content field equals to NULL. So i want to when content parameter is NULL Django does not save it in database but does not show any errors. Maybe already this field has data and in the Update request client just want to change title field. -
Django ORM: ForeignKey=self and on_delete=PROTECT
I have Model with field, where I see next field: some_field = ForeignKey('self', on_delete=PROTECT, blank=true, null=true, editable=false) For what this field exist and what it does? Also I cant delete obj of this model id adminpanel, cause it say " you cant delete obj A, because would require deleting next protected obj: obj A" Reason for this in this some_field? -
Custom permission/restriction with DJANGO REST ModelViewSet
I would like to restrict users to have only limited access/permissions in create or destroy method. Here is the scenario, a user, with admin role can do anything (create, get, update, delete), where as an ordinary user(customer) can only perform those allowed actions(create, get, delete) to its related model. My model looks like this class Material(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) class UserMaterialAllow(models.Model): user = models.ForeignKey(get_user_model()) material = models.ForeignKey('Material, on_delete=models.CASCADE) Here is how I added a custom restriction /views/material.py class MaterialView(viewsets.ModelViewSet): queryset=Material.objects.all() serializer-class = MaterialSerializer def create(self, request, *args, **kwargs): if(not app_admin(request.user)): // the user is not admin return Response(status=status.HTTP_403_FORBIDDEN)// this will forbid non admin user in MateralView, a user cant access if it is not an admin. What I need is, if the user is not an admin, just allow them to perform action but limited only the the material belongs to them app_admin implemtation `def app_admin(user): if user.user_is_admin: return True if user.is_superuser: return True return False Any ideas? -
"Must be owner of table A", but A doesnt exist
I`m trying to run database migrations, but getting the following error: psycopg2.ProgrammingError: must be owner of table request_settings This is from my .env file: ... DB_USER=idaproject DB_NAME=wellton DB_PASSWORD=password DB_HOST=127.0.0.1 DB_PORT=5432 ... So, I assume, this table should be inside "wellton" database. The user "idaproject" is the owner of "wellton" database and has all priveleges and rights on the database. Then I tried to change owner of request_settings table with ALTER TABLE request_settings OWNER TO idaproject; But seems like it doesn't exist ERROR: relation "request_settings" does not exist Am I missing something? -
Can I create one Superuser and use it in multiple Django Projects?
In order to reduce short-term memory load, is it possible to use one superuser account in the Django admin for multiple projects? -
Django Channels "took too long to shut down and was killed"
I am using Django Channels for a real-time progress bar. With the help of this progressbar the client gets actual feedback of a simulation. This simulation can take longer than 5 minutes depending on the data size. Now to the problem. The client can start the simulation successfully, but during this time no other page can be loaded. Furthermore I get the following error message: Application instance <Task pending coro=<StaticFilesWrapper.__call__() running at /.../python3.7/site-packages/channels/staticfiles.py:44> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/futures.py:348, <TaskWakeupMethWrapper object at 0x123aa88e8>()]>> for connection <WebRequest at 0x123ab7e10 method=GET uri=/2/ clientproto=HTTP/1.1> took too long to shut down and was killed. Only after the simulation is finished, further pages can be loaded. There are already articles on this topic, but they do not contain any working solutions for me. Like for example in the following link: https://github.com/django/channels/issues/1119 A suggestion here is to downgrade the Channels version. However, I encounter other errors and it must also work with the newer versions. requirments.txt: Django==3.1.2 channels==3.0.3 channels-redis==3.3.1 asgiref==3.2.10 daphne==3.0.2 I am grateful for any hint or tip. Best regards, Dennis -
change function based to generic list view in django
How do i write this view into generic list view in django @login_required def accept_tickets_view(request,pk): ticket = get_object_or_404(Ticket,id=pk) if ticket.status == 'Opened': ticket.status = 'Accepted' ticket.accepted_date = datetime.datetime.now() ticket.accepted_by = request.user ticket.save() return redirect(reverse('open_tickets')) -
how to do reverse query set based on forgen key set in django
its a bit complicated, here are the 2 models that am performing the query on : class Line(models.Model): # Relationships end_station = models.ForeignKey("stations.station", related_name='line_end_station', on_delete=models.CASCADE) starting_station = models.ForeignKey("stations.station", related_name='line_start_Station', on_delete=models.CASCADE) class InLineStation(models.Model): # Relationships line = models.ForeignKey("lines.Line", on_delete=models.CASCADE) in_line_station = models.ForeignKey("stations.station", on_delete=models.CASCADE) am getting a station object in the request and I need to filter the line model based on it , if it's a starting , ending, or in line station.. here is how I tried this : @api_view(['POST', ]) def do_search_logic(request): if request.method == 'POST': from_station_id = request.data['from_station_id'] to_station_id = request.data['to_station_id'] from_station_object = station.objects.get(id=from_station_id) to_station_object = station.objects.get(id=to_station_id) Line.objects.filter(Q(starting_station=from_station_object) | Q(end_station=to_station_object) | Q(from_station_object in inlinestations_set)) #this_is_the_tricky_line any help about this ??