Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamically building complex queries in Django using Q-Objects
I have a database query for some items (containers). There is a related table that could define some restrictions (Only those in a top-level org, only those in a dept (customer) in an org, or just those in a team (course) in a dept) Here's my (not working) code to get the list of objects: def get_containers(customer_id: None, course_id: None): q_list = (Q(is_private=False), Q(is_active=True)) if customer_id: try: customers = Customer.objects customer = customers.get(id=customer_id) except KeyError: return None # Second level restriction: may have a customer-id customer_q = ( Q(restrictions__customer__isnull=True) | Q(restrictions__customer=customer.id) ) # Third level restriction: may be restricted to a course-code course_q = Q(restrictions__course_code__isnull=True) if course_id: course_q |= Q(restrictions__course_code=course_id) # Top level restriction: restricted to org restrictions_q = ( Q(restrictions__organisation=customer.org.id) & customer_q & course_q ) q_list = (Q(q_list) | Q(restrictions_q)) print(f"q_list: {q_list}") return Container.objects.filter(q_list) I've been using https://docs.djangoproject.com/en/3.0/topics/db/queries/#complex-lookups-with-q (& the referenced https://github.com/django/django/blob/master/tests/or_lookups/tests.py), and the previously asked django dynamically filtering with q objects as references during this. I've tried a bunch of variations to get the OR at the end of the if customer_id: block to work - and they all give me errors: q_list = q_list | restrictions_q\nTypeError: unsupported operand type(s) for |: 'tuple' and 'Q' q_list = Q(q_list … -
Django: Use a different related_name than "%(class)s" on abstract base classes to account for irregular plurals
I have the following models: from django.db import models from foo.bar.models import Location class AbstractShop(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name="%(class)s") class Meta(self): abstract = True class Bakery(AbstractShop): some_field = models.BooleanField("Some field", default=True) class Meta: verbose_name = "Bakery" verbose_name_plural = "Bakeries" class Supermarket(AbstractShop): some_other_field = models.CharField("Some other field", max_length=20) class Meta: verbose_name = "Supermarket" verbose_name_plural = "Supermarkets" Now, Supermarket as well as Bakery inherit the location-ForeignKey from AbstractShop. If I want to query the reverse relation to Bakery on the Location model, I would have to use bakerys as related_name - which I don't want as it's grammatically wrong and unintuitive. So my questions are: Is there any way to use the verbose_name_plural as related_name? Is there any way at all to use any other related_name than "%(class)s" or "%(app_label)s or do I just have to implement the ForeignKey on the child classes? If so, that would be somewhat annoying. Imagine you have a lot of shared ForeignKeys: You can move the ones with regular plurals in English to the abstract base class while those with irregular plurals have to be implemented on the child class. This is a totally arbitrary condition which might not be obvious to non-native English speakers, … -
How many parallel request can flask/django handle at a time?
I have built an api with python deployed with gunicorn/nginx/docker. I would like to know how many parallel request can a single api handle at a single point of a time. -
RuntimeError at /admin/auth/user/add/ generator raised StopIteration
I am new in django and i am facing RuntimeError at /admin/auth/user/add/ generator raised StopIteration while adding new user in database -
Allow user to make new roles in django?
I am new to Django.I was learning how to create multiple user type with same common login form in Django.I was following this blog https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html.On this blog it says that No matter what strategy you pick, or what is your business model, always use one, and only one Django model to handle the authentication. And in this blog example, before building the project the set of users were known and according to that the model was built.For that he took a choice field and stored the user_type.When the user wants to login he/she need to select any option from the dropdown and login.But I want my user(admin) to create the user_type.In such case how do I dynamically add the created user_type and add to that choice_field. Code snippet from that blog: class Role(models.Model): STUDENT = 1 TEACHER = 2 SECRETARY = 3 SUPERVISOR = 4 ADMIN = 5 ROLE_CHOICES = ( (STUDENT, 'student'), (TEACHER, 'teacher'), (SECRETARY, 'secretary'), (SUPERVISOR, 'supervisor'), (ADMIN, 'admin'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True) def __str__(self): return self.get_id_display() class User(AbstractUser): roles = models.ManyToManyField(Role) -
django 3 Forbidden (403) CSRF verification failed. Request aborted. how can you bypass or send a token via axios vuejs
I have an error that I can't go further because he swears at the token, I don't want to use django-rest-framework and django-cors-headers. front works in vuejs 3. front <i class="fa fa-question-circle fa-2x text-warning" aria-hidden="true" @click="checkFly(item.booking_token)"></i> checkFly: function(booking_token) { var vue = this; console.log(booking_token); axios .post(API + "check-fly/", { params: { csrfmiddlewaretoken: $("#csrfmiddlewaretoken").val(), booking_token: booking_token, }, }) .then(function(response) { vue.check = response.data; console.log(vue.check); }); }, back def checkfly(request): data = [] url = "v=2&booking_token=" + \ request.GET.get( 'booking_token') + "&bnum=3&pnum=2&affily=picky_{market}&currency=USD&adults=1&children=0&infants=1" print(url) return JsonResponse(json.dumps(url), safe=False) -
Django receiving POST URL
I'm using Jira webhooks to communicate with my Django app. In Jira, I set POST URL to: /api/webhooks/jira?issue_id=EXAMPLE_ISSUE_ID&secret=EXAMPLE_SECRET&user_id=EXAMPLE_USER_ID&user_key=EXAMPLE_KEY My app urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path("api/webhooks/jira", views.webhook, name='webhook') ] How can I get information about issue_id, secret, user_id, and user_key (Those values aren't included in json that I recveive via post) and what is the proper way to set path in my urls.py? -
How to to math operation in Django templates?
I am writing a web app in Django where a user can vote a post, from 1 to 5 (using stars), when I want to display the stars I have to decide how many of them have to be yellow and how many not. I save the feedback in this model: class Feedback(models.Model): text = models.TextField() stars = models.IntegerField(choices=[(i, i) for i in range(1, 6)], blank=False) article = models.ForeignKey(Article, on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) the problem is in the template, because I would like to do something like this, but i don't know how and if it is a good choice: {% for _ in art.stars %} <span class="fa fa-star checked"></span> {% endfor %} {% for _ in (5-art.stars) %} <span class="fa fa-star"></span> {% endfor %} -
hide secret key on django/pycharm mac
I'm making a simple CRUD app in django with the use of Pycharm. I want to upload the project to Github and thus need to protect some of my settings.py file. Would the best way to be use a .env file and add it to .gitignore or does that method not work on mac? -
What are the best online programs suitable for kids? [closed]
Coding, Programming, App Development, Digital Literacy, C program , Little Hackers and many more engaging programs. -
How to use django signals with model creation?
This is my UserClass models and i want to use django signals to set user in UserClass model to the user registred in the site. from django.contrib.auth.models import User class UserClass(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) I came up with this code but it doesn't work. def user_create(sender, instance, created, **kwargs): if created: UserClass.objects.create( user=instance, ) print('User created') post_save.connect(user_create, sender=User) -
Django choice select after render related foreignkey fields[txt or file field]
I am working on test series module. I stuck adding question with option. I have a question model and related with option models(objective base question and descriptive base question) and want to add option according question type. I am looking for your valuable suggestion. class Questions(models.Model): ques_type = ( ('SCQ', 'Single choice questions'), ('MCQ', 'Multiple choice questions'), ('OQ', 'Descriptive'), ) title = models.TextField(_("Question Title")) difficulty_level = models.ForeignKey("DifficultyManager.Difficulty", verbose_name=_( "Difficulty Level"), on_delete=models.SET_NULL, null=True) topics = models.ForeignKey("TopicManager.Topic", verbose_name=_( "Topic"), on_delete=models.SET_NULL, null=True) ques_type = models.CharField( _("Question Type"), max_length=4, choices=ques_type) is_delete = models.BooleanField(_("Delete"), default=False) created_by = models.ForeignKey(User, related_name="questions", blank=True, null=True, on_delete=models.SET_NULL) status = models.BooleanField(_("Status")) create_date = models.DateTimeField( _("Created timestamp"), auto_now_add=True) update_date = models.DateTimeField( _("Last update timestamp"), auto_now=True) objects = QuestionsManager() def __str__(self): return self.title class QuestionOption(models.Model): question = models.ForeignKey( "Questions", on_delete=models.CASCADE, verbose_name=_("questions")) option = models.CharField(_("Choice"), max_length=255) is_right = models.BooleanField(_("Right/Worng"), default=False) create_date = models.DateTimeField( _("Created timestamp"), auto_now_add=True) update_date = models.DateTimeField( _("Last update timestamp"), auto_now=True) class Meta: unique_together = [ ("question", "option"), ] def __str__(self): return self.question.title class QuestionFile(models.Model): question = models.ForeignKey( "Questions", on_delete=models.CASCADE, verbose_name=_("questions"), null=True) image = models.ImageField(_("Image"), upload_to='question/images/%Y/%m/%d', height_field=None, width_field=None, max_length=400, null=True) video = models.FileField( _("Video"), upload_to='question/videos/%Y/%m/%d', max_length=100, null=True) create_date = models.DateTimeField( _("Created timestamp"), auto_now_add=True) update_date = models.DateTimeField( _("Last update timestamp"), auto_now=True) def __str__(self): … -
Autofill state while user enter zip code by using zip code database|Django|JQuery|UI
How to auto fill state by entering zip code. I have zip code database. How to validate with in form. If user enters the zip code that zip code is available in this database using that zip code the state should autofill as mention below datbase.If zip code matches then state must autofill I have implemented this using API. But know I have to do with database INSERT INTO pages_zip_code (id, zip, city, st) VALUES (1, '00501', 'Holtsville', 'NY'), (2, '00544', 'Holtsville', 'NY'), (3, '00601', 'Adjuntas', 'PR'), (4, '00602', 'Aguada', 'PR'), (5, '00603', 'Aguadilla', 'PR'), (6, '00604', 'Aguadilla', 'PR'), (7, '00605', 'Aguadilla', 'PR'), (8, '00606', 'Maricao', 'PR'), (9, '00610', 'Anasco', 'PR'), (10, '00611', 'Angeles', 'PR'), (11, '00612', 'Arecibo', 'PR'), (12, '00613', 'Arecibo', 'PR'), (13, '00614', 'Arecibo', 'PR'), (14, '00616', 'Bajadero', 'PR'), (15, '00617', 'Barceloneta', 'PR'), (16, '00622', 'Boqueron', 'PR'); urls.py path('autostate', views.autostate, name='autostate'), views.py def autostate(request): if 'term' in request.GET: qs = zip_code.objects.filter(zip__iexact=request.GET.get('term')) zip_li = list() for zip_n in qs: zip_li.append(zip_n.st) return render(request, 'home.html') html page:- <input class="InputZip" name="Zip" placeholder="Zip Code" type="text"> <input class="Inputstate" name="state" placeholder="State" type="text"> *JQuery* <script> function is_int(value) { if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) { return true; } else { return false; } } $(".InputZip").keyup(function() { … -
Avoid running script when refreshing page in Django
I am running my external python script using submit button on my web page script.py: def function(): print('test it') views.py from script import function def func_view(request): if request .method == 'POST': function() return render('my.html',{'run_script':function}) Problem: when I am opening my page, program is running, it's not waiting until I will click this button. additionally: when I add in my if request loop File input, after refreshing web page , Django is adding same file again. What I am doing wrong here? -
I have deleted django's debug.log file in a Django app which is running in a ubuntu server using Apache. It has stopped working after that
When I go to the url it shows 500 Internal server error. Apache is running. I get the following when I open Apache's log file: [Thu Oct 01 00:05:58.928187 2020] [mpm_event:notice] [pid 3300:tid 139714918706112] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured --$ [Thu Oct 01 00:05:58.942594 2020] [core:notice] [pid 3300:tid 139714918706112] AH00094: Command line: '/usr/sbin/apache2' [Thu Oct 01 01:48:01.623516 2020] [mpm_event:notice] [pid 3300:tid 139714918706112] AH00491: caught SIGTERM, shutting down [Thu Oct 01 01:48:01.801650 2020] [mpm_event:notice] [pid 8340:tid 140123896040384] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured --$ [Thu Oct 01 01:48:01.801791 2020] [core:notice] [pid 8340:tid 140123896040384] AH00094: Command line: '/usr/sbin/apache2' [Thu Oct 01 02:39:31.890115 2020] [mpm_event:notice] [pid 8340:tid 140123896040384] AH00491: caught SIGTERM, shutting down [Thu Oct 01 02:39:32.025560 2020] [mpm_event:notice] [pid 9367:tid 139790829341632] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured --$ [Thu Oct 01 02:39:32.025705 2020] [core:notice] [pid 9367:tid 139790829341632] AH00094: Command line: '/usr/sbin/apache2' [Thu Oct 01 08:33:15.700373 2020] [mpm_event:notice] [pid 9367:tid 139790829341632] AH00491: caught SIGTERM, shutting down [Thu Oct 01 08:33:15.789098 2020] [mpm_event:notice] [pid 13931:tid 139952318925760] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -$ [Thu Oct 01 08:33:15.789241 2020] [core:notice] [pid 13931:tid 139952318925760] AH00094: Command line: '/usr/sbin/apache2' I have created a new debug.log file but it is empty now. I think it might be … -
Django - How to apply onlivechange on CharField / IntegerField
I want to hide the field form.name_of_parent_if_minor if the age (CharField) < 18 else show. I am not getting where to write jQuery or JS code or add separate js file. For this do I need to the html definition and add tag for age (CharField) or we can perform action on this as well. I am new to the Django so if you find any mistakes in my code then any help would be appreciated for guidance. forms.py class StudentDetailsForm(forms.ModelForm): class Meta: model = StudentDetails views.py class StudentCreateView(LoginRequiredMixin, CreateView): template_name = 'student/student_details_form.html' model = StudentDetails form_class = StudentDetailsForm success_url = "/" html {% extends 'student/base.html' %} {% load crispy_forms_tags %} {% block content %} <div id="idParentAccordian" class="content-section"> <form method="POST"> {% csrf_token %} <div class="card mt-3"> <div class="card-header"> <a class="collapsed card-link" style="display: block;" data-toggle="collapse" href="#idPersonalInformation">Personal Information</a> </div> <div id="idPersonalInformation" class="collapse show" data-parent="#idParentAccordian"> <div class="card-body"> <div class="row"> <div class="col-6"> {{ form.joining_date|as_crispy_field }} </div> <div class="col-6"> {{ form.class|as_crispy_field }} </div> </div> {{ form.student_name|as_crispy_field }} {{ form.father_name|as_crispy_field }} {{ form.mother_name|as_crispy_field }} {{ form.gender|as_crispy_field }} <div class="row"> <div class="col-6"> {{ form.date_of_birth|as_crispy_field }} </div> <div class="col-6"> {{ form.age|as_crispy_field }} </div> </div> <div> {{ form.name_of_parent_if_minor|as_crispy_field }} </div> </div> </div> </div> <div class="form-group mt-3"> <button class="btn btn-outline-info" … -
how I can to migrate this python script to django? [closed]
I tried to migrate this python script to Django but without success: import asyncio import websockets async def hello(websocket, path): name = await websocket.recv() print(f"< {name}") greeting = f"Hello {name}!" await websocket.send(greeting) print(f"> {greeting}") start_server = websockets.serve(hello, "localhost", 8055) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() -
Form not looking good without using crispy form
This is the form that appears if I donot use crsipy form.But, if I use crispy forms, the radio button disappears, anyone have any idea?? As shown above, if crispy form is used, the radio button now disapperas.what is the issue?? <form method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success" formaction="{% url 'addcustomer' %}">Submit</button> <button class="btn btn-primary" formaction="{% url 'customerlist' %}">Cancel</button> </form> -
Django: preventing concurrency in related models without using a lock
Let's say I have 4 models, as such: class Venue(models.Model): capacity = models.IntegerField() class Event(models.Model): description = models.CharField() class Session(models.Model): event = models.ForeignKey(Event) start = models.TimeField() end = models.TimeField() class UserSession(models.Model): venue = models.ForeignKey() user = models.ForeignKey(User) event = models.ForeignKey(event) session = models.ForeignKey(Session) class Meta: unique_together = ['user', 'venue', 'event'] So a user has to choose 1 session out of an event, and can only attend one session. A user is limited to a single venue (this integrity is enforced elsewhere). The number of user sessions is limited by the venue capacity. Events and sessions can happen in multiple venues. The question is, how best to prevent concurrency resulting in the number of UserSessions exceeding the venues capacity. Given that events and sessions are not unique to events and venues and occurring elsewhere the use of pessimistic lock wouldn't make sense. One thing I've considered is relating Sessions to Venues via a M2M relationship using a through model, and tracking an indicator field, such as attendance. This would work in both the pessimistic and optimistic approach, as a lock could be placed on the through model, or attendance could be used to confirm no changes in the optimistic approach. I … -
Django - how to update manytomany field using UpdateView and ModelForm
I have following models(not actual names). class MyModelTwo(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) class MyThroughModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) foo = models.ForeignKey(MyModelTwo, null=True, on_delete=models.CASCADE) bar = models.ForeignKey('MyModelOne', null=True, on_delete=models.CASCADE) original_price = models.DecimalField(_('original price'), max_digits=8, decimal_places=2) off = models.DecimalField(_('off'), max_digits=8, decimal_places=2) final_price = models.DecimalField(_('final price'), max_digits=8, decimal_places=2) class MyModelOne(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) foos = models.ManyToManyField(MyModelTwo, through='MyThroughModel') In my CreateView I have following. db_obj = form.save(commit=False) db_obj.save() for item in form.cleaned_data['items']: throughModel= MyThroughModel() throughModel.original_price = item.original_price throughModel.foo = item throughModel.bar = db_obj throughModel.off = item.off throughModel.final_price = item.final_price throughModel.save() return super(MyCreateView, self).form_valid(form) This saves things correct. Now the problem is how do I make sure that UpdateView inserts new entries(items) and also removes the items which have been unselected by the user? What is the way to handle that in the form_valid inside UpdateView? I looked into some questions related to M2M but couldn't find something fitting my case. Maybe I got tired of searching and trying. I spend hours on this but no luck. I am new to this. Please help. Thank you. -
How to group by? Django Rest Framework
I am developing an API Rest based on Django, I have two models: Album Track I am trying to get the right format on this JSON (this is what I am getting now): [ { "album": "album-123kj23mmmasd", "track": { "id": 6, "uuid": "2c553219-9833-43e4-9fd1-44f536", "name": "song name 1", }, "duration": 2 }, { "album": "album-123kj23mmmasd", "track": { "id": 7, "uuid": "9e5ef1da-9833-43e4-9fd1-415547a", "name": "song name 5", }, "duration": 4 }, This is what I would like to reach, I would like to group by 'albums': [ { "album": "album-123kj23mmmasd", "tracks": [{ "id": 6, "uuid": "2c553219-9833-43e4-9fd1-44f536", "name": "song name 1", "duration": 2 }, { "id": 7, "uuid": "9e5ef1da-9833-43e4-9fd1-415547a", "name": "song name 5", "duration": 4 }, ] }, ] Thanks in advance -
Django Template - Nested Dictionary Iteration
My template receives from views.py following nested dictionary of shopping cart content. {'20': {'userid': 1, 'product_id': 20, 'name': 'Venus de Milos', 'quantity': 1, 'price': '1500.00', 'image': '/media/static/photos/pngegg.png'}, '23': {'userid': 1, 'product_id': 23, 'name': 'Bicycle', 'quantity': 1, 'price': '1000.00', 'image': '/media/static/photos/366f.png'}} I am having problem with iteration through it. For example, when I am using following code, {% for key, value in list %} {{ key }} {{ value }} {% endfor %} instead of keys and values I receive just this: 2 0 2 3 My goal is to calculate grand total through multiplying quantity and price for each product and dding it all together with each product in cart. May sombody give me a hand on this, or at least help to figure out how to iterate properly through nested dictionary? -
AttributeError at / 'QuerySet' object has no attribute 'users'
I don't know why I am getting this error I am new to Django I researched a lot but I didn't find an answer please when giving me the answer explain as much as you can I want to learn but if you don't want to no problem Thank you, This is my Views.py from django.views.generic import TemplateView from django.shortcuts import render, redirect from django.contrib.auth.models import User from home.forms import HomeForm from home.models import Post, Friend class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id) friend = Friend.objects.filter(current_user=request.user) friends = friend.users.all() args = { 'form': form, 'posts': posts, 'users': users, 'friends': friends } return render(request, self.template_name, args) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['post'] form = HomeForm() return redirect('home:home') args = {'form': form, 'text': text} return render(request, self.template_name, args) def change_friends(request, operation, pk): friend = User.objects.get(pk=pk) if operation == 'add': Friend.make_friend(request.user, friend) elif operation == 'remove': Friend.lose_friend(request.user, friend) return redirect('home:home') This is my models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Friend(models.Model): users = … -
use nested list in django template
I have a 1d queryset and I want it to be nested based on its each value. For example, in a template like below <ul> {% for dept in dept_queryset %} <li>{{ dept.code }} {{ dept.name }}</li> {% endfor %} </ul> I see something like this 1000 a 1100 b 1200 c 2000 q 2100 w 2110 e 2111 t ... 2200 t 2210 h 2211 b ... 2300 p What I want is however something like this: 1000 a 1100 b 1200 c 2000 q 2100 w 2110 e 2111 t ... 2200 t 2210 h 2211 b ... 2300 p I can hard code each queryset and use it in as context, but I'd like to know if there is any pythonic way. I tried divisible by filter, with no success. And I'm aware that I should change my template tag of course, I hope to get some guidance about it. Any help would be appreciated. Thanks! -
Cannot access Django query string parameter in url
I am trying to access the 'category' key from the following url within my view: ...users/8/feed?category='x'. However, when I run self.kwargs within my view, it only returns 'user_id': 8. urls.py: path('users/<int:user_id>/feed', views.Posts.as_view()) views.py: class Posts(APIView): def get(self, request, **kwargs): return Response(self.kwargs) What would I change such that self.kwargs returns "user_id": 8, "category": 'x' rather than just "user_id": 8? It is important that this stays as a query string parameter using '?'. Additionally, I've seen other people implementing similar things using self.request.GET, what is the difference between using this and self.kwargs? Thanks, Grae