Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert a char field to uuid field in django models
I have a django model, where I am storing uuid kind of strings in a character field of max length 255, I want to convert this field to uuid field, how can this be done in django. -
Django URL error: noreversematch in my app
I'm seeing this error in my Django app NoReverseMatch at /kaitorihyou/delete_fields_group/18 Reverse for 'delete_fields_group' with arguments '('',)' not found. 1 pattern(s) tried: ['kaitorihyou/delete_fields_group/(?P<fields_group_id>[0-9]+)\\Z'] However my urls.py does contain this pattern like this: app_name = "kaitorihyou" urlpatterns = [ path('delete_fields_group/<int:fields_group_id>', views.delete_fields_group, name="delete_fields_group"), # etc. ] Why is the url pattern not matching? -
How to incorporate django-tailwind into django rendered forms for input fields?
I have the following form: <form class="form" method="post" action="."> {% csrf_token %} <div class="error-wrapper"> <div class="errors">{{ form.errors }}</div> </div> <div class="email-wrapper field-wrapper"> <div class="tag name-tag">{{ form.username.label }}*</div> <!-- How to apply tailwind css classes to the rendered input field here? --> <div class="input rounded-lg">{{ form.username }}</div> </div> ... </form> # forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=True) last_name = forms.CharField(max_length=30, required=True) email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') Now I want to apply tailwind classes to the input field which is rendered by {{ form.username }}. But how to basically do it? Is there any way to apply classes to the element other than changing the form class itself? -
ModelViewSet Queryset Filter with table based value with another table
I have two tables in my database ProductStock and Sales.And I am storing the Product info in the ProductStock table and Sales info inside the Sales table. Based on the total sum of sold quantity I want to filter the data, and return the data only whose quantity is greater than 0. for eg. PRODUCT STOCK DATA ID PRODUCT QUANTITY 1 Django Course 50 2 Social Codia 50 SALES DATA PRODUCT_STOCK_ID QUANTITY 1 5 1 45 2 35 2 10 Here the sold quantity of product 1 is 5+45=50, that means there is no stock left in the database for product 1. QUESTION IN SHORT : How can i fetch all these products whose quantity is greater than current_quantity - sold_quantity greater than 0. My ProductStock Model class ProductStock(Core): medical = models.ForeignKey(Medical, on_delete=models.CASCADE) distributer = models.ForeignKey(Distributer,on_delete=models.DO_NOTHING) product = models.ForeignKey(Product,on_delete=models.CASCADE,related_name='product') variant = models.ForeignKey(Attribute,on_delete=models.DO_NOTHING) batch = models.CharField(max_length=20,null=True, blank=True) purchase_price = models.CharField(max_length=10,null=False, blank=False) price = models.CharField(max_length=10,null=False,blank=False) quantity = models.IntegerField(null=False,blank=False) location = models.ForeignKey(Location, on_delete=models.DO_NOTHING) low_stock = models.IntegerField(default=10,null=False,blank=False) expire_date = models.DateTimeField(null=False,blank=False) My SALE Model class Sale(Core): product_stock = models.ForeignKey(ProductStock,on_delete=models.CASCADE,related_name='sales') medical = models.ForeignKey(Medical,on_delete=models.CASCADE,related_name='medical') quantity = models.IntegerField(default=1,null=False,blank=False) price = models.CharField(max_length=10,null=False,blank=False) discount = models.FloatField(max_length=10,default=0) ProductStockViewSet class ProductStockViewSet(ModelViewSet): serializer_class = ProductStockSerializer permission_classes = [IsAuthenticated] authentication_classes = [JWTAuthentication] def get_queryset(self): … -
fully empty logs using gunicorn nginx and django
I have the following django API set up with nginx and gunicorn and all my logs except one are completely empty. I have never set up logs before. I was expecting to get the normal server output of any 500 errors and such like I get on local in my terminal: nano /etc/nginx/sites-available/stocks_backend server { ... access_log /root/stocks_backend/log/nginx-access.log; error_log /root/stocks_backend/log/nginx-error.log; } /etc/supervisor/conf.d/stocks [program:stocks] user=root directory=/root/stocks_backend command=/root/stocks_backend/stocks-env/bin/gunicorn --workers 3 --bind unix:st> autostart=true autorestart=true stdout_logfile=/root/stocks_backend/log/gunicorn.log stderr_logfile=/root/stocks_backend/log/gunicorn.err redirect_stderr=true /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=root WorkingDirectory=/root/stocks_backend ExecStart=/root/stocks_backend/stocks-env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target 3 of the 4 logs are empty: root@-droplet:~/stocks_backend# cat log/nginx-error.log root@-droplet:~/stocks_backend# cat log/nginx-access.log root@-droplet:~/stocks_backend# cat log/gunicorn.err [2022-08-25 21:27:39 +0000] [61321] [INFO] Starting gunicorn 20.1.0 [2022-08-25 21:27:39 +0000] [61321] [INFO] Listening at: unix:stocks_backend.sock (61321) [2022-08-25 21:27:39 +0000] [61321] [INFO] Using worker: sync .... [2022-08-27 07:27:06 +0000] [67233] [INFO] Shutting down: Master [2022-08-27 07:27:08 +0000] [69840] [INFO] Starting gunicorn 20.1.0 [2022-08-27 07:27:08 +0000] [69840] [INFO] Listening at: unix:stocks_backend.sock (69840) [2022-08-27 07:27:08 +0000] [69840] [INFO] Using worker: sync [2022-08-27 07:27:08 +0000] [69842] [INFO] Booting worker with pid: 69842 [2022-08-27 07:27:08 +0000] [69843] [INFO] Booting worker with pid: 69843 [2022-08-27 07:27:08 +0000] [69844] [INFO] Booting … -
Send context the template in a class based view
How can I send context to my template in a class based view with the get_object funtion? This is my class: class DetailMessages(LoginRequiredMixin, DetailView, ChannelFormMixin): template_name = 'DM/chat.html' def get_object(self, *args, **kwargs): my_username = self.request.user.username username = self.kwargs.get("username") channel, _ = Channel.objects.get_dm_channel(my_username, username) if channel == None: raise Http404 context = {"example1" : "I want this on the template", "example2" : "I want this on the template too"} return channel -
why the css of my django application only works in incognito mode?
I don't know if it's happened to someone else, but I have a django application that only shows the styles created in css only when it's in incognito mode, when the browser is in normal mode you can't see the changes created in css. what would cause the problem? and how can i fix it? -
Run python code in server with client files using sockets [closed]
I created a Django project that prints a sentence when a button clicks. Here instead of printing the sentence, I want to run a python function that updates an excel file in the client machine. I can run the function but I don't know how to update the excel file on the client machine. As of now, I have hard-coded the client address and I have also created a small exe file that runs in the background of the client machine, that listens to the particular IP address of the server. I am not able to figure out given the client excel location, client, and server connected via sockets, how to update the excel sheet in the client. -
Apache2 keep restarting when continuous requests are coming
when multiple requests are coming apache server got crashed and restarting automatically. i have tried updating the mpm modules, but still facing the same issue.[[1]: https://i.stack.imgur.com/Q1gFN.jpg -
django-celery-beat PeriodicTask not firing
I have a project using django-celery-beat, celery, and reds. For some reason one specific task out of many in my entire project never fires, with no errors or anything. I've verified that it's autodetected and showing up in the Django Admin dropdown and is registered with @app.task. I've tried deleting and recreating the task. I've tried creating the PeriodicTask programmatically instead of via the Admin. I've tried setting the last_run_at to start_time - interval I've tried using a crontab interval. I've made sure it's enabled and points to a correct task name. Are there any reasons why this might be happening? It appears to be just straight up ignored. -
How to add calculated default value to Django model?
I want to add slug field in existing model and the value should be calculated with Django's slugify function based on title field. How can this be done? I understand that I can override save method of the model class and do all stuff there, it will work for all future saved instances, but is there an elegant way to populate this field for existing rows also? -
Use OR clause instead AND in django-filter
I'm working with the django-filter + django rest framework. I want to search a term with the OR clause. I have this filter: class ItemFilter(filters.FilterSet): name = filters.CharFilter(field_name="name") barcode = filters.CharFilter(field_name="barcode") class Meta: model = Item fields = ['name', 'barcode'] when I send a query param like https://url?barcode=q&name=q django-filter searchs: SELECT * FROM item where name = 'q' AND barcode = 'q' How can I configure to search?: SELECT * FROM item where name = 'q' OR barcode = 'q' -
FOREIGN KEY constraint failed in django
This is my models.py from ast import Delete from email.policy import default from django.db import models from django.contrib.auth.models import User class Euser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=10,null=True) birthdate = models.DateField(null=True,) profile_pic = models.ImageField(null=True, ) cover_pic = models.ImageField( null=True, upload_to="images/%y") def __str__(self): return self.phone views.py def editprofile(request, pk): return render(request, 'proedit.html') def submitedit(request): if request.method=="POST": current_user = request.user.id firstname = request.POST.get('firstname') lastname = request.POST.get('lastname') username = request.POST.get('username') email = request.POST.get('email') phone = request.POST.get('mobileno') birthdate = request.POST.get('birthdate') profile_pic = request.FILES['profile_pic'] print(current_user) User.objects.filter(pk=current_user).update(username=username,first_name=firstname,last_name=lastname,email=email) Euser.objects.filter(pk=current_user).update_or_create( phone=phone,birthdate=birthdate,profile_pic=profile_pic, defaults={'phone': phone,'birthdate': birthdate,'profile_pic': profile_pic},) actually i am trying to update the data from web request.. i havn't used forms.py kindly suggest me if i have to change something -
TypeError: post() takes 1 positional argument but 2 were given
I have my model class: class Subscription(models.Model): email = models.EmailField(max_length=250, unique=True) def __str__(self): return self.email and my View: class SubscriptionView(APIView): queryset = Subscription.objects.all() def post(request): email = request.data.get('email') print(email) save_email = Subscription.objects.create(email=email) save_email.save() return Response(status=status.HTTP_201_CREATED) My model only takes in 1 field which is the email. Not sure why I keep getting 'TypeError: post() takes 1 positional argument but 2 were given' Appreciate any help! -
Setup UpdateView in Django with a form that has the __init__ method configured
When I use UpdateView in Django with a form that has the init method configured to customize the ModelMultipleChoiceField querysets do not load the initial values of the instance? Some context first, I find myself making an application that manages documents associated to subportals, for that each subportal has associated Service Groups and Dependencies. I need that when a document is loaded, it can be categorized by Service Groups and Dependencies that are only associated to the subportal. I achieved this by using the init method in the forms. The problem is when I need to update the document data, the initial values of the model do not appear. I show the codes Models.py class ServiceGroup(models.Model): subportal = models.ForeignKey(Subportal, null=True, blank=True, on_delete=models.CASCADE) title = models.CharField(max_length=150, null=False, blank=False) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Dependence(models.Model): subportal = models.ForeignKey(Subportal, null=True, blank=True, on_delete=models.CASCADE) title = models.CharField(max_length=150, null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class SubportalDocument(models.Model): def get_upload_to(instance, filename): return '{}/documents/{}'.format(instance.subportal.title, filename) subportal = models.ForeignKey(Subportal, null=True, blank=True, on_delete=models.CASCADE) showcategory = models.OneToOneField(ShowCategory, null=True, blank=True, on_delete=models.CASCADE) title = models.CharField(max_length=150, null=False, blank=False) file = models.FileField(upload_to=get_upload_to, null=False, blank=False) review_date = models.DateField(null=False, blank=True) review_nro = models.IntegerField(null=False, blank=True) created_at = models.DateTimeField(auto_now_add=True) dependences = … -
Limit relationship OneToone with different options
So, I extended the AbstractUser with a class called Account (Using inheritance), this doesn't add anything new, its there just in case I want to add something later. Accounts should have a "user type", lets say "user_type_1" and "user_type_2", this 2 models have new fields, and only one of them should be related to the Account, Im not sure how to do it, I readed about GenericForeignKey but that doesn't solve the problem with having just 1 of them. Maybe using GenericForeignKey + constraints, how can I do it? There is a better option for this? -
ChoiceField is appearing Instead of CharField in Django Admin Panel
while creating many-to-one relationship in django using Foreignkey Choicefield is appearing instead of CharField in Django Admin Panel Image of Model Image of Django Admin Panel Code of Views.py from django.http import JsonResponse from .models import Name def names_list(request): MAX_OBJECTS = 1 name = Name.objects.all() data = {"results": list(name.values("Name"))} return JsonResponse(data) -
Django orm: order post queryset by greatest number of tags from search
I want to order posts by the greatest number of tags a post has my models: class post(models.Model): description = models.Charfield(max_length = 2000) class tag(models.Model): t = models.Charfield(max_length = 100) class tags(models.Model): tag = models.ForeignKey(tag, ...) post = models.ForeignKey(post,...) I know django's orm supports many to many fields I just make my own table because I feel more comfortable starting out this way. When inputs a search, example: purple mountain flowers I want to query for posts that have any of the tags and order the query by the posts with the most matching tags. I'm new to using aggregation in django and have no idea how to structure this. Any recommendations? -
customize django admin field based on another drop-down field
I have a simple Django app with three models: class Category(models.Model): name = models.CharField(max_length=100) description = models.TextField(("Description")) class ItemType(models.Model): name = models.CharField(max_length=100) description = models.TextField(("Description")) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Plant(models.Model): category = models.ForeignKey(Category , on_delete=models.SET_NULL , null=True) type = models.ForeignKey(ItemType, on_delete=models.SET_NULL,null = True) name = models.CharField() what I need is in the admin panel when I chose a category the type dropdown is filter base on that for example I have category1 and category2 and type1 related to category1 and type2 related to category2 when I choose category1 from the dropdown the type dropdown show only type1 -
Django - uploading files to inline formset
I'm trying to make inline form by using inlineformset_factory but my Image object is not getting saved models: class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) availability = models.IntegerField() price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.name class Image(models.Model): file = models.ImageField(upload_to="products_images/", default="static/default.png") uploaded = models.DateTimeField(auto_now_add=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) views: def CreateNewProductView(request): context = {} ProductObj = None form=ProductForm() if request.method=='POST': form = ProductForm(request.POST) if form.is_valid(): ProductObj = form.save() print('form is valid, product has been created') else: print("form is not valid") ImageFormset = inlineformset_factory(Product, Image, fields=('file',), extra=1, can_delete=False) if request.method=='POST': formset = ImageFormset(request.POST, request.FILES, instance=ProductObj) if formset.is_valid(): formset.save() print('formset is valid, product has been created') else: print("formset is not valid") else: formset = ImageFormset(instance=ProductObj) if form.is_valid() and formset.is_valid(): return redirect('home') context = {'form': form, 'formset':formset} return render(request, 'Ecommerce/test.html', context) template test.html {% extends 'base.html' %} {% block content %} <form method="POST" action="" id="image-form" style="padding-top:10px;"> {% csrf_token %} {{form.as_p}} {{formset}} {{formset.management_form}} <button type="submit">submit</button> </form> {% endblock content %} In console I can see "formset is valid, product has been created" When I printed (request.FILES) i saw <MultiValueDict: {}>. Should it be like that ? In django admin pannel there is no Image objects What am I doing wrong ? -
How can I display in the chat list those with whom I corresponded earlier?
I have a chat code in which I want to display and suggest only those users with whom there has already been a correspondence, that is, both incoming and outgoing messages, and not all registered users html code: <div class="container" style="height: 75%;"> <div class="card bg-dark h-100 border-light"> <div class="card-body h-100"> <div class="row h-100"> <div class="col-md-4 border-right h-100"> <div class="list-group bg-dark" id='user-list'> {% for u in users %} {% if not u.id == 1 and not u.id == user.id %} <a class="list-group-item {% if u.id != chat_id %}bg-dark{% else %}bg-primary{% endif %} text-white" href="{% url 'chat-home' %}?u={{u.id}}"> <div> <p>{{u.first_name}} {{u.last_name}} ({{u.username}})</p> </div> </a> {% endif %} {% endfor %} </div> </div> <div class="col-md-8 h-100"> {% if not chat_id > 0 %} <div class="h-100 d-flex flex-column justify-content-center align-items-center"> <h3>Начните общение!</h3> <p><small class="text-muted">Выберете человека, чтобы написать ему.</small></p> </div> {% else%} <div id="chat-box-field" class="h-100"> <div class="chat-box" style="height:80%"> {% for chat in chats %} {% if chat.user_from == user %} <div class="p-2 w-100 d-flex justify-content-end"> <div class=" chat-bubble ml-2 mb-2 bg-primary text-light rounded" data-id="{{chat.id}}"> <p>{{chat.message}}</p> <div class="d-flex justify-content-between"><small>Ты</small> <small>{{chat.date_created|date:"M-d-Y H:i"}}</small></div> </div> </div> {% else %} <div class="p-2 w-100 d-flex justify-content-start"> <div class="chat-bubble mr-2 mb-2 bg-light text-dark rounded" data-id="{{chat.id}}"> <p>{{chat.message}}</p> <div class=" d-flex justify-content-between"><small>От</small> <small>{{chat.date_created|date:"M-d-Y H:i"}}</small></div> … -
How do I specify a custom lookup field for a DRF action on a viewset?
I would like to specify a custom lookup field on the action (different from the viewset default "pk"), i.e. @action( methods=["GET"], detail=True, url_name="something", url_path="something", lookup_field="uuid", # this does not work unfortunately ) def get_something(self, request, uuid=None): pass But the router does not generate the correct urls: router = DefaultRouter() router.register(r"test", TestViewSet) router.urls yields url: '^test/(?P<pk>[^/.]+)/something/$' instead of '^test/(?P<uuid>[^/.]+)/something/$' I do not want to change the lookup field for the whole model though and have been unsuccessful in finding a way to do this for the action itself after debugging through the router url generation. I did notice that model viewsets have this method: get_extra_action_url_map(Self) but am unsure how to get it to be called to generate custom urls or if it is even relevant. Any help would be great thanks! -
Django ManyToMany alternative pros and cons
I was developing a chat system with channels and have this models for a thread (some attributes removed for simplicity's sake): class Thread(models.Model): name = models.CharField(max_length=50, null=True, blank=True) users = models.ManyToManyField('auth.User') I realized it is also possible to implement it like this: class Thread(models.Model): name = models.CharField(max_length=50, null=True, blank=True) class ThreadUsers(models.Model): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) What are the advantages/disadvantages of using one over the other? -
How can a model be asigned to a User automatically?
So I am coding an e-commerce on Django in which in order to add items to cart, you need to be a customer. However, you log into the page as a user, which isnt the same. How can a customer be asigned to the User once it is created automatically? If it cannot be done automatically, then how can I insert a form to create the customer and for it to be related to the user? I'll insert some screenshots of the customer model and the views which matter. this is the Customer model this is the add to cart function in views.py as you can see in this screenshot, I could manually relate a customer to a user which has been already created, but it just wouldn't be eficient. I'd like that when a user is registered, a customer is asigned to it automatically. Thank you -
Key is not present in table django
I will say right away, I looked at all similar questions, but I could not solve my problem. Therefore I ask. I originally created the Products, FeaturesForProduct, ProductFeatures tables in postgres. Now I need to transfer these tables to django. I used python manage.py inspectdb command. I have defined the many to many relationship myself. I also wrote a small function, when called, I get an error: django.db.utils.IntegrityError: insert or update on table "product_features" violates foreign key constraint "fk_products_product_features_refer" DETAIL: Key (id)=(1) is not present in table "products". I understand what this error is about. The last time I encountered it, I just dropped the database and then everything worked. I am interested in the following question, is it possible to somehow get rid of this error in another way? My func: class AttachNewFeatureToProduct(View): def get(self, request, *args, **kwargs): if request.user.is_superuser: res_string = "" product = Products.objects.get(id=int(request.GET.get('product_id'))) existing_features = list(set([item.feature.feature_name for item in product.features.all()])) category_features = SparePartsUnitsFeatures.objects.filter( spare_parts_units=product.spare_parts_unit ).exclude(feature_name__in=existing_features) option = '<option value="{value}">{option_name}</option>' html_select = """ <select class="form-select" name="product-category-features" id="product-category-features-id" aria-label="Default select example"> <option selected>---</option> {result} </select> """ for item in category_features: res_string += option.format(value=item.spare_parts_units.id, option_name=item.feature_name) html_select = html_select.format(result=res_string) return JsonResponse({"features": html_select}) else: return HttpResponseRedirect('/') My models: class Products(models.Model): id …