Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ?? -
Django : Why does logging in with superuser email allauth redirect to different page?
I have a django app in which I have a google allauth sign up/login . If I log in with the same email I entered in the superuser creation , it redirects me to : Otherwise : Why? -
Django - set many to many through with differing defaults
Assuming the data model as in Django docs: class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) In the docs the beatles group is set the following way: beatles.members.set([john, paul, ringo, george], through_defaults={'date_joined': date(1960, 8, 1)}) In my case I got a tuple with differing through values: ( { "person": "john", "date_joined": datetime(2002,1,1), "person": "ringo", "date_joined": datetime(...), ... } ) How do I set this many-to-many with differing defaults? I could do something like group.members.clear() for m in member_to_set: Membership.objects.create(person = m.person, date_joined = m.date_joined) But this would invoke a lot of database operations. On the other hand I would not like to reimplement the whole logic of finding out, which memberships to remove -
Django, DRF: How to get related posts with Tag(m2m)
Currently, we are able to get the following related articles by Tag. In the following method, scores are calculated in the order of the number of tags contained in the object. If more related objects of the object with the highest score are retrieved, only articles with more tags will be retrieved and articles with fewer tags will not be retrieved. Is there any other way? # models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=100) class Video(models.Model): tags = models.ManyToManyField(Tag, blank=True, db_index=True) # views.py class RelatedListView(generics.ListAPIView): serializer_class = VideoSerializer def get_queryset(self): video_pk = self.kwargs["pk"] tags = Video.objects.get(pk=video_pk).tags.all() return ( Video.objects.annotate(score=Count("pk")) .exclude(pk=video_pk) .filter(tags__in=tags) .order_by("-score") ) -
How to cast parameter values based on their annotations in python functions?
Consider having a task worker, which executes tasks from a task queue. I am trying to built a web interface in django to trigger those tasks manually. So far, for some built-in data-types I go about something simple like this: # tasks.py @app.task def add(a: int, b: int) -> int: return a+b # views.py TYPE_TO_FIELD_MAPPING = { str: forms.CharField, int: forms.IntegerField, float: forms.FloatField, datetime: forms.DateTimeField, # ... } class TaskTriggerView(View): def get(self, request): tasks = {} for task in app.tasks: tasks[task.name] = self.make_task_parameter_form(task)() return render(request, 'template.html', context={'tasks': tasks} def make_task_parameter_form(self, task): # every task has a signature parameter which # is a inspect.Signature object. task_signature: inspect.Signature = task.signature # Initialize a django form with fields made out of # task's function signature, where the form field # is based on it's annotation if annotation is in # `TYPE_TO_FIELD_MAPPING` else forms.CharField. # initial value comes from parameter's default value # if it is not parameter.empty. parameter_form = type( 'ParameterForm', (forms.Form,), {param_name: TYPE_TO_FIELD_MAPPING.get(param.annotation, str)( initial=None if param.default is param.empty else param.default ) for param_name, param in signature.parameters.items()}) return parameter_form def post(self, request): task_name = request.POST.get('task_name') task = app.get_task_by_name(task_name) form_class = self.make_task_parameter_form(task) form = form_class(request.POST) if form.is_valid() # this sends the task to … -
How do I format django url so that AJAX call will get database data that is not dependent on the current page, but from a form value?
I have a page that details a post and comments on that post. The pk for this page is the post pk. I want to be able to construct comments using symbols only. I have a series of symbols saved to the database that are all associated with a category class. I have a form on my page that can select one of those categories, but how do I get an AJAX call to load all the symbols in that category? The user will need to be able to chop and change between categories so I wanted to do this with AJAX rather than reload the page each time. So far, all I get are 404 not founds. I want to do this so that I can drag or select symbols to add to comments. I've tried lots of different formats to get the urls to work (both in urls.py and in main.js) so I can't list off all the alternatives that I've tried as it's all a bit overwhelming. I've also read through a heap of questions on here and other sites but nothing seems to match what I am trying to do. Any help would be appreciated. Symbols … -
Django search bar implementation with multiple field filtering
I am trying to implement the functionality of a search bar. my models.py: class Question(models.Model): questionId = models.IntegerField(primary_key=True) groupId = models.IntegerField(default=0) questionTitle = models.TextField() groupName = models.CharField(max_length=500, null=True, blank=True) correctAnsRef = models.ManyToManyField(CorrectAns, related_name="questionReletedResponses") My database is huge, so I tried to skip Question.objects.all() to save time. my views.py: def questionList(request) # Searching Any Value if request.method == "POST" and request.POST['searchKey'] != '': searchKey = request.POST['searchKey'] questions = Question.objects.filter(questionId=searchKey) return render(request,'diagnosis/questionList.html', {'questions': questions}) This works perfectly but it can only filter by questionId. I wish to have such a search bar that will filter by matching all the fields(questionId, groupId, questionTitle... etc all) the Question model has. (note: request.GET already been used for pagination.) Please suggest how can I do this?