Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tailwind purgecss with django forms?
I have a django project with a forms.py where I want to style the fields with tailwind. However, I can't figure out how to get purgecss to not remove the classes I have in forms.py. Is there a way to dynamically check python files as well, or do I have to resort to whitelisting them? # users/forms.py class SignUpForm(UserCreationForm): # ... class Meta: model = User fields = ('username', 'email', 'password1', 'password2', ) widgets = { 'username': forms.TextInput(attrs={ 'class': 'bg-gray-300' # how to not purge this class? }) } // tailwind.config.js module.exports = { content: [ // ... '/**/forms.py' // this doesn't work ], // ... -
Carousel with backend data showing all images or no images
I am running a Django application where I receive the list of images and in my template, I have the following code for Carousel. The issue is if I use this class "carousel-inner active" while iterating all images are set active and all images are shown on a single screen, if not if I remove active and just keep carousel-inner no image is shown <div id="demo" class="carousel slide" data-bs-ride="carousel"> <!-- Indicators/dots --> <div class="carousel-indicators"> <button type="button" data-bs-target="#demo" data-bs-slide-to="0" class="active"></button> <button type="button" data-bs-target="#demo" data-bs-slide-to="1"></button> </div> <!-- The slideshow/carousel --> <div class="carousel-inner active"> {% for image in data.images %} <div class="carousel-item active"> <img src="{{ image }}" alt="image 1" class="d-block" style="width:100%"> </div> {% endfor %} <!-- Left and right controls/icons --> <button class="carousel-control-prev" type="button" data-bs-target="#demo" data-bs-slide="prev"> <span class="carousel-control-prev-icon"></span> </button> <button class="carousel-control-next" type="button" data-bs-target="#demo" data-bs-slide="next"> <span class="carousel-control-next-icon"></span> </button> </div> -
Django Streaming Videos from Mobile Devices not Working Properly
Django server does not play videos properly on mobile devices. Video seek options are not available. It works fine if we use media files from another domains but files from own server are not working correctly. Forward, rewind and seek options are not accessible <video id='main-video' controls style="width:100%;"> <source src='{{ video_format.url }}' title='{{ name }}' type='video/mp4' /> </video> Should I change any Django core settings? I have built the server using Nginx + Django + Gunicorn. -
Model ID in a for loop (django jinja) how do I set the pk value
I am trying to figure out how I can get the model ID from the for loop in the html/jinja to be set as the cert_id in views.py so that I can update that specific model by clicking the update button I am not sure if there is an easier way i.e. passing the 'cert.id' back to django some other way any help would be excellent thank you, littlejiver detail.html <div id="Certificate" class="tabcontent"> <div class="cert-btn-div"> <button onclick="showAddSiteForm()" id="sitebtn" class="btn"> Add Certificate + </button> <div class="form-add-site" id="form-add-site-js"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <p> {{ form.department.label }}: {{ form.department }} {{ form.licence.label }}: {{ form.licence }} Exp. Date: {{ form.exp }} {{ form.file.label }}: {{ form.file }} </p> <button name="add_site_btn" type="submit">Create</button> </form> </div> </div> <table class="cert-table"> <tr> <th>Dpt:</th> <th>Licence:</th> <th>Exp. Date:</th> <th>Upload Date:</th> <th>File:</th> <th></th> <th></th> <th></th> </tr> <tr> {% for cert in list_of_certs %} <td>{{ cert.department }}</td> <td>{{ cert.licence }}</td> <td>{{ cert.exp }}</td> <td>{{ cert.ul_date }}</td> <td>{{ cert.file }}</td> <div class="upload-tds"> <td> <button class="btn sitebtn" onclick="showUpdateCertForm({{cert.id}})" id="sitebtn{{cert.id}}">Update File</button> </td> <td> <div class="upload-tds-hidden" id="form-update-cert-js{{cert.id}}"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.file }} <button class="btn" name="update_btn" type="submit">Update</button> </form> <div> <button class="btn sitebtn" onclick="showUpdateCertForm({{cert.id}})" id="cancelbtn{{cert.id}}">Cancel</button> </div> </div> </td> </div> </div> </tr> {% … -
How to predict error when saving utf8 chars in latin-1 mysql table via django?
My setup is using python3+, django 3.2 with mysql 5.7 on an AWS Amazon linux instance. When I originally created my database and tables, I did not specify a particular charset/encoding. So, I read the following post and determined that my tables and columns are currently latin1: How do I see what character set a MySQL database / table / column is? I have also read this post to try and understand the differences between what the client uses as encoding and what the table/database is using -- this allows the client to save non-latin1 chars in a mysql table with latin1 charset: MySQL 'set names latin1' seems to cause data to be stored as utf8 Here is some code to show what I am trying to do: # make a new object mydata = Dataset() # set the description. This has a few different non-latin1 characters: # smart quotes, long dash, dots over the i mydata.description = "“naïve—T-cells”" # this returns an error to prove to myself that there are non-latin1 chars in the string mydata.description.encode("latin-1") # Traceback (most recent call last): # File "<console>", line 1, in <module> # UnicodeEncodeError: 'latin-1' codec cant encode character '\u201c' in position … -
Django sending data from outside consumer class
I am trying to get use Django channels to send data over a websocket to my react native application from django. I have read all the available documentation on this subject on Django and have went through numerous stackoverflow posts, but I don't think they are applicable to me because they use redis and I decided not to use redis. Whenever I try to send data right now, nothing sends. These are my files. models.py from django.db import models import json from .consumers import DBUpdateConsumer from django.db.models.signals import post_save from django.dispatch import receiver from channels.layers import get_channel_layer from asgiref.sync import async_to_sync channel_layer = get_channel_layer() class Connect(models.Model): id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') neighborhood = models.CharField(max_length=50, choices=neighborhood_choices, default='all') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.CharField(max_length=100) phone = models.CharField(max_length=50) def save(self, *args, **kwargs): super().save(self, *args, **kwargs) print("def save") async_to_sync(channel_layer.send)("hello", {"type": "something", "text": "hellooo"}) class Meta: managed = False db_table = 'connect' settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } consumers.py import json from channels.generic.websocket import AsyncJsonWebsocketConsumer #used https://blog.logrocket.com/django-channels-and-websockets/ #https://channels.readthedocs.io/en/latest/topics/consumers.html class DBUpdateConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.send_message(self, "UPDATE") await self.accept() await self.send(text_data=json.dumps({ "payload": "UPDATE", })) print("connect!") async def disconnect(self, close_code): print("Disconnected") async def receive(self, text_data): """ Receive message from WebSocket. … -
Unable to update/delete item from table even with on_delete=CASCADE
I am trying to make a Cooking Recipe Portal DB and none of the DELETE queries work for me. Here are my tables/models related to the error: class Ingredient(models.Model): ingredientid = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) type = models.CharField(max_length=255) class IngredientRecipe(models.Model): ingredientid = models.ForeignKey("Ingredient", to_field="ingredientid", on_delete=models.SET_NULL, null=True) recipeid = models.ForeignKey("Recipe", to_field="recipeid", on_delete=models.SET_NULL, null=True) amount = models.CharField(max_length=255) class Meta: unique_together = ("ingredientid", "recipeid") class IngredientNutrition(models.Model): nutritionid = models.IntegerField(null=True, blank=True) ingredientid = models.ForeignKey("Ingredient", to_field="ingredientid", on_delete=models.CASCADE) #ingredientid = models.OneToOneField(Ingredient, on_delete=models.CASCADE) portionsize = models.FloatField(max_length=24) calories = models.IntegerField() fat = models.IntegerField() protein = models.IntegerField() sodium = models.IntegerField() carbs = models.IntegerField() class Meta: unique_together = (("nutritionid", "ingredientid"), ) Issue: Say i want to delete ingredient.ingredientID = 20 or ingredient.name = 'Corn Starch', it won't let me delete because ingredientID = 20 is still referenced by the table IngredientNutrition. I have on__delete=CASCADE. I tried altering the parameters inside the models.ForeignKey and changed parameters in various keys in different tables to see if it allowed me to delete. -
Django cache real-time data with DRF filtering and sorting
I'm building a web app to manage a fleet of moving vehicles. Each vehicle has a set of fixed data (like their license plate), and another set of data that gets updated 3 times a second via websocket (their state and GNSS coordinates). This is real-time data. In the frontend, I need a view with a grid showing all the vehicles. The grid must display both the fixed data and the latest known values of the real-time data for each one. The user must be able to sort or filter by any column. My current stack is Django + Django Rest Framework + Django Channels + PostgreSQL for the backend, and react-admin (React+Redux+FinalForm) for the frontend. The problem: Storing real-time data in the database would easily fulfill all my requirements as I would benefit from built-in DRF and Django's ORM sorting/filtering, but I believe that hitting the DB 3 times/sec for each vehicle could easily become a bottleneck when scaling up. My current solution involves having the RT data in python objects that I serialize/deserialize (pickle) into/from the Django cache (REDIS-backed) instead of storing them as models in the database. However, I have to manually retrieve the data and DRF-serialize … -
Django, how can I show variables in other model class?
I'm learning Django and I'm trying to understand its logic. There are 2 models I created. I am designing a job listing page. The first model is "Business". I publish the classes inside this model in my html page and for loop. {% job %} {% endfor %}. But inside my second model in this loop I want to show company_logo class inside "Company" model but I am failing. Methods I tried to learn; 1- I created a second loop inside the job loop, company loop, and published it failed. 2- I assigned a variable named company_list to the Job class on the views page and made it equal to = Company.objects.all() but it still fails. Here are my codes. models.py from django.db import models from ckeditor.fields import RichTextField from djmoney.models.fields import MoneyField JobTypes = ( ('Full-Time', 'Full-Time'), ('Part-Time', 'Part-Time'), ('Internship', 'Internship'), ('Temporary', 'Temporary'), ('Government', 'Government') ) class Job(models.Model): job_title = models.CharField( max_length=100, null=True) job_description = RichTextField() job_application_url = models.URLField(unique=True) job_type = models.CharField(max_length=15, choices=JobTypes, default='Full-Time') #job_category job_location = models.CharField( max_length=100) job_salary = MoneyField(max_digits=14, decimal_places=4, default_currency='USD') created_date = models.DateTimeField(auto_now_add=True) featured_listing = models.BooleanField( default=False) company = models.ForeignKey( "Company", on_delete=models.CASCADE) def __str__(self): return f"{self.company}: {self.job_title}" class Company(models.Model): created_date = models.DateTimeField(auto_now_add=True) company_name = models.CharField(max_length=100, … -
How to solve url parameter problem in Django?
I have a strange problem. I have a page that uses url parameters. Users can reach this site based on their project id and name and the group(csoport) name that stored in three models. This is a link for an example page: /performance/monthlyfeedback/{{ request.user.profile.csoport }} That link works fine if the name of the csoport is a number. If it is any kind of a text it gives me 404 error that I can't figure out why. models.py class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) csoport = models.CharField(max_length=100, null=True, blank=True) class Projekt_perf(models.Model): def __str__(self): return str(self.projekt_perf) projekt_perf = models.CharField(max_length=250) jogosult_01_perf = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) class Performance_profile(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE) projekt_perf = models.ForeignKey(Projekt_perf,on_delete=models.CASCADE) views.py I am using raw query in the views. def obj_results(request, projekt_perf_id, projekt_perf, user_name_id, csoport): person = Projekt_perf.objects.raw('SELECT * FROM performance_projekt_perf INNER JOIN performance_performance_profile ON performance_projekt_perf.id = performance_performance_profile.projekt_perf_id INNER JOIN stressz_profile ON performance_performance_profile.user_name_id = stressz_profile.user_id WHERE performance_projekt_perf.id = %s AND projekt_perf = %s AND stressz_profile.user_name_id = %s AND stressz_profile.csoport = %s',[projekt_perf_id, projekt_perf, user_name_id, csoport]) context = { 'person': person, } return render(request, 'performance/obj-results.html', context) urls.py app_name = 'performance' urlpatterns = [ path('monthlyfeedback/<int:projekt_perf_id>', login_required(views.Performance_test), name='performance_feedback'), path('list/<int:projekt_perf_id>/<projekt_perf>', … -
Preparing data for a form view (django, drf, axios, vuejs)
I'm building a web application with Django, DRF, Axios and Vuejs. It works but I'm wondering what are best practices for handling such a case. Considering the form below : I want to create an Item for which I can assign a Company and a Contact. The Company is a model in its own as well as the Contact. The Contact field shows only contacts for the selected Company. How should I query the datas to be the most RESTful possible ? Query all the companies, query all the contacts, and make a computed property that shows only contacts of the currently selected company ? Query all the companies, and each time I select a company I query related Contacts only ? Other solution ? Both have pros and cons and I wonder what is the best way to handle this kind of situation. Also, if there are standard ways to design this. -
How can i access javascript data in my django template for forloop iteration
I am using js to fetch api from django rest api and after fetching api i need to use length of fetched api obj in django template how can i do that? Or is there any other way which this problem can be solve by? ///////////////////////////////////////////js function for fetching api/////////////////////////////////// function getName() { fcom=document.getElementById('fcom').value; dep=document.getElementById('dep').value; console.log(fcom, dep) fetch(`http://localhost:8000/create-f-company-record/${fcom}/${dep}`, { method: 'GET', // or 'PUT' headers: { 'Content-Type': 'application/json', }, }) .then(response => response.json()) .then(data => { console.log(data) console.log(data.length) temdata=data.length if(data!="0"){ document.getElementById('length').value=5 document.getElementById('fdate').value=data.date document.getElementById('fcom').value=data.FCompany document.getElementById('dep').value=data.depostieAmount document.getElementById('pay').value=data.paymenetAmount document.getElementById('deppaydate').value=data.DepPAyDate document.getElementById('net').value=data.netAmount } else{ alert('Could not find data with this id') window.location.reload() } }) } ///////////////////////////////////////django template html file////////////////////////////////////// {% for tem in temdata %} {% endfor %} this temdata variable is inside js function -
UnboundLocalError at /api/registration/ even though I tried fixing it
Screenshot of the Error is at Error The Error I face is: UnboundLocalError at /api/registration/ local variable 'data' referenced before assignment Request Method: POST Request URL: http://217.160.170.83:81/api/registration/ Django Version: 3.2.12 Exception Type: UnboundLocalError Exception Value: local variable 'data' referenced before assignment Exception Location: /var/www/LWD/userAccount/views.py, line 128, in get_response_data Python Executable: /usr/bin/python3 Python Version: 3.8.10 Python Path: ['/var/www/LWD', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Sat, 26 Mar 2022 19:05:05 +0000 My Project Repository Link: https://github.com/Bilal815/LWD LWD/userAccount/views.py: from django.conf import settings from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework import permissions, status, viewsets from rest_framework.views import APIView from rest_framework.generics import ( ListAPIView, RetrieveAPIView, CreateAPIView, GenericAPIView, RetrieveUpdateAPIView, UpdateAPIView, ) from rest_framework.exceptions import PermissionDenied, NotAcceptable, ValidationError from allauth.account.views import ConfirmEmailView from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter from allauth.socialaccount.providers.twitter.views import TwitterOAuthAdapter from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client from rest_auth.registration.views import SocialConnectView, SocialLoginView from rest_auth.social_serializers import TwitterConnectSerializer from allauth.account.models import EmailAddress, EmailConfirmationHMAC from rest_auth.views import ( LoginView, PasswordResetView, PasswordResetConfirmView, PasswordChangeView, LogoutView, ) from rest_auth.serializers import PasswordResetConfirmSerializer from rest_auth.registration.views import RegisterView, VerifyEmailView from rest_auth.registration.serializers import VerifyEmailSerializer from rest_auth.app_settings import JWTSerializer from rest_auth.utils import jwt_encode from django.views.decorators.debug import sensitive_post_parameters from django.utils.decorators import method_decorator from django.contrib.auth.models import User, Permission from django.utils.translation import ugettext_lazy as _ from … -
I get the error "Cannot resolve keyword 'category' into field. Choices are: id" in MPTT
I want to create a subcategory with MPTT but I get the error "Cannot resolve keyword 'category' into field. Choices are: id". I can't find the reason. I would be happy if you half. I'm trying to edit dressing on the admin page. I'm trying to do this from a source I found on the internet. source:https://django-mptt.readthedocs.io/en/latest/models.html models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey # Create your models here. class Category(MPTTModel): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) keywords = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name class Product(models.Model): pass admin.py from django.contrib import admin from mptt.admin import DraggableMPTTAdmin from .models import Category, Product # Register your models here. class CategoryAdmin(DraggableMPTTAdmin): prepopulated_fields = {'slug': ('name',)} mptt_indent_field = "name" list_display = ('tree_actions', 'indented_title', 'related_products_count', 'related_products_cumulative_count') list_display_links = ('indented_title',) def get_queryset(self, request): qs = super().get_queryset(request) qs = Category.objects.add_related_count( qs, Product, 'category', 'products_cumulative_count', cumulative=True) qs = Category.objects.add_related_count(qs, Product, 'categories', 'products_count', cumulative=False) return qs def related_products_count(self, instance): return instance.products_count related_products_count.short_description = 'Kataqoriada olan məhsulların sayı' def related_products_cumulative_count(self, instance): return instance.products_cumulative_count related_products_cumulative_count.short_description = 'Alt kataqoriada olan məhsulların sayı' admin.site.register(Product) admin.site.register(Category, CategoryAdmin) Error: -
Django: I can't figure out how to save the model
I'm just learning django. And for 2 hours I can not understand what the mistake is. Model Blog class Blog(models.Model): title = models.CharField(max_length=255, verbose_name='Заголовок') text = RichTextField(verbose_name='Текст') date = models.DateField(auto_now_add=True, verbose_name='Дата') user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Автор') image = models.ImageField(verbose_name='Фото', upload_to='blog') tags = models.CharField(max_length=500, verbose_name='Теги', help_text='через кому') slug = AutoSlugField(populate_from='title', null=True) class Meta: verbose_name = 'Стаття' verbose_name_plural = 'Статті' def __str__(self): return self.title Model Comment class Comment(models.Model): name = models.CharField(max_length=100, verbose_name='Ім\'я') email = models.EmailField(verbose_name='Email', max_length=255) text = models.CharField(max_length=500, verbose_name='Коментар') datetime = models.DateTimeField(auto_now_add=True) article = models.ForeignKey(Blog, on_delete=models.CASCADE, verbose_name='Стаття') parent = models.IntegerField(verbose_name='Батьківський коментар') class Meta: verbose_name = 'Коментар' verbose_name_plural = 'Коментарі' def __str__(self): return self.name + ', ' + self.email Model CommentForm class CommentForm(ModelForm): class Meta: model = Comment fields = ['name', 'email', 'text'] widgets = { 'name': TextInput(attrs={'class': 'form-control form--control'}), 'email': TextInput(attrs={'class': 'form-control form--control'}), 'text': Textarea(attrs={'rows': 5, 'class': 'form-control form--control'}), } views.py def detail(request, slug): blog = Blog.objects.get(slug=slug) if request.method == 'POST': form = CommentForm(request.POST) form.article_id = blog.pk form.parent = 0 if form.is_valid(): form.save() else: form = CommentForm() return render(request, 'blog/blog_detail.html', context={'blog': blog, 'tags': blog.tags.split(','), 'form': form}) and I keep getting an error - (1048, "Column 'article_id' cannot be null"). I can't understand why, because I give it meaning. And yet: how … -
Auth0 login working only on localhost but won't redirect to my domain
I have no idea if I missed something, but I followed the Auth0 documentation and watched videos about is and set it up and everything works (localhost). Now I want to use it on my domain that I have. I added the settings for my domain over at auth0 website. But what happens is this I click on the login link on my website I go to the correct url http...../login/auth0 The request goes to the auth0 (my domain there) but with the redirect to localhost Removing the locahost from auth0 setting doesn't help since I'm still sending it as the return url. The issue here (I assume) are the arguments that I'm passing and I have no idea how to change them. I'm not sure if there is a way for creating a custom login view and then sending users over to auth0 or if there is some way to pass different value to the auth0 login view in order to change the returnTo url -
DJANGO: How to send and recieve data from a database with consumers
I have a working chat application made with Django. I want to send every last saved message from every group to one single group where they can all be preview. I have tried to do it for one group (General) so far but ran into problems. Here is my code: Consumers.py - Here is the first consumer for the messages that is working and the second one where I tried to send and receive the last message from group (General). import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from django.contrib.auth.models import User from .models import Message from channels.db import database_sync_to_async import datetime class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name print(self.room_group_name) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) @database_sync_to_async def get_user_profile(self): return self.scope['user'].profile async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = self.scope['user'].username profile = await self.get_user_profile() profile_pic = profile.image.url room = text_data_json['room'] date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") await self.save_message(username, room, message, date) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chatroom_message', 'message': message, 'username': username, 'profile_pic': profile_pic, 'date': date, 'room': room } ) async def chatroom_message(self, event): message = event['message'] username = event['username'] profile_pic … -
Circular Dependency Error when creating custom user for dj-stripe
I'm trying to create a subscription plan for my django app using stripe, essentially following the guide bellow to the letter: https://ordinarycoders.com/blog/article/django-stripe-monthly-subscription I'm using dj-stripe to sync my stripe products with my database. My problem is when I come to creating a custom user, I get a Circular Dependency Error when I attempt to migrate. from django.db import models from django.contrib.auth.models import AbstractUser from djstripe.models import Customer, Subscription class User(AbstractUser): customer = models.ForeignKey(Customer, null=True, blank=True, on_delete=models.SET_NULL, related_name='stripe_customer') subscription = models.ForeignKey(Subscription, null=True, blank=True, on_delete=models.SET_NULL, related_name='stripe_subscription') The full error: django.db.migrations.exceptions.CircularDependencyError: djstripe.0008_2_5, djstripe.0009_2_6, djstripe.0010_alter_customer_balance, custom_user.0001_initial, djstripe.0001_initial, djstripe.0007_2_4 I've tried deleting my database and all migrations, reinstalling the packages but nothing seems to work. Is there any way I can get around this? -
Django Infinite dynamic Multi-level nested category
I have three models for now suppose one is category another is subcategory and another is product. Before registering a product user should add subcategory and before adding subcategory we need to add category in subcategory table. So, now adding a products need to be like Men's Fashion (Category)-> Shirt(SubCategory)-> White shirt(Product). It is working fine and I have no issue with it. But there is sudden changes like If I need to add infinite subcategory suppose there maybe some products like to go through two subcategory Men's Fashion(Category) -> Footwear(SubCategory) -> Shoe(SubCategory) -> Premium shoe (Product) or maybe maybe some products like to go through two subcategory Men's Fashion(Category) -> Footwear(SubCategory) -> Shoe(SubCategory) -> Leather Shoe (Subcategory) -> Premium shoe (Product) It will depend on the user he can add as many as subcategory he wants. This has to be like dynamic but I am wondering how. If I take multiple data and add model dynamically (I don't know if I can do this with django because the how can I sync the db without using migrate command) this is pretty much confusing me and I am stuck here. Any kind of help would be really appreciated. class Category(models.Model): … -
Django JSON not being saved in sqlite database simply get an error and the database remains empty
I am trying to save JSON data to sqlite database on Django I have these small code chunks here which are giving me some problems. Here is a chunk of my models.py file class Recipes(models.Model): name = models.CharField(max_length=120, default='') pub_date = models.DateTimeField('date published') style = models.CharField(max_length=200, default='') brewer = models.CharField(max_length=100, default='') type = models.CharField(max_length=20, default='All Grain') version = models.CharField(max_length=20, default='1') batch_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_time = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) efficiency = models.DecimalField(decimal_places=1, max_digits=4, default=75.0) ibu = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) abv = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) notes = models.TextField(default='') carbonation = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) primary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) secondary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) __fermentables = [] @classmethod def create(cls,attr): recipe = cls() # do something with the book for k in Recipes._meta.fields: if k.name in attr: setattr(recipe,k.name,attr[k.name]) return recipe Here is the part of views.py which is giving me trouble def saveRecipe(request): try: data=json.loads(request.read()) print("printing values") print(data["name"]) #prints here works recipe = Recipes.create(attr=data) recipe.name = data["name"] recipe.save() recipe.addYeast(items=data["yeast"]) recipe.addFermentables(items=data["fermentables"]) recipe.addHops(items=data["hops"]) recipe.addMashStep(items=data["mash"]) return HttpResponse(serialize('json', [recipe]), content_type='application/json') except: return HttpResponse("error") Basically I have a button which parses JSON from filled forms and when I print name … -
How is the "required" attribute dynamically set on a MultiWidget?
There are 4x TextInput elements that comprise a MultiWidget. Only the first TextInput requires the required attribute. Yet required is being set on all four elements. Form.use_required_attribute is not suitable for my case due it's binary nature; either values for all form fields are required or not. I've set required=False to every possible place where it's potentially warranted, but I'm still not getting the desired result. How can I get just the first TextInput set to required? class MultiTagWidget(MultiWidget): def __init__(self, *args, **kwargs): widgets = [TextInput(attrs=kwargs['attrs']) for i in range(4)] super().__init__(widgets, *args, **kwargs) def decompress(self, value): if value: return value.split("_") return "" class TagField(MultiValueField): def __init__(self, *args, **kwargs): fields = [] for i in range(4): field = CharField(**{ "min_length": 1, "max_length": 25, "validators":[ RegexValidator("[<>`':;,.\"]", inverse_match=True) ] }) if i == 0: field.error_messages = { 'incomplete': "Provide at least 1 tag for your question" } field.required = True else: field.required = False fields.append(field) super().__init__(fields, *args, **kwargs) def compress(self, data_list): data_list = "_".join(list(set([tag.lower().strip() for tag in data_list]))) return data_list tags = TagField( widget=MultiTagWidget( attrs={"required": False} ), require_all_fields=False, help_text="Add up to 4 tags for your question" ) -
How to quickly see if all items in list of Primary Keys exist prior to bulk_create call?
I'm attempting to do a django bulk_create for a list of objects. However, every so often one of the objects in the bulk_create already exists (it's primary key has already been allocated) so an exception is raised and no objects get created. To fix this I added a loop over each of the new objects to test if they exist prior to the bulk_create call but this feels very inefficient. Is there way to accomplish the same result in fewer queries to the database? -
Is there a way to fill up a (multi)cell's remaining space with dots using pyfpdf2?
I'm currently working on a Django project in which the client needs to print reports where remaining spaces are filled up with dots up to the end of the line dynamically. I'm using the PyFpdf2 library for PDF reports. The outputs should look like this: This is line 1.................... This is line 2.................... I am using basic cells and multicells as: pdf = FPDF() pdf.add_page() pdf.set_font('Arial', '', 12) pdf.cell(40, 8, 'This is line 1........') Anyone can help? -
Django - class CreateView, how can I launch special function after success?
I have a form, where user can type song_name and upload .wav file in my views.py: from django.views.generic import CreateView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import AudioCompositionForm class AddAudio(LoginRequiredMixin, CreateView): form_class = AudioCompositionForm template_name = 'audio_test/add_audio.html' I have a special function which convert wav to mp3 How can I launch this function after success upload? Will be ideal if i can transfer a new object <class 'audio_test.models.AudioComposition'> into in my audio_convert funcion. Thanks -
How can I connect to postgresql database container from within another container?
It appears I can't access 127.0.0.1:5555 from my company_tasks container: version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data - ./init.sql:/docker-entrypoint-initdb.d/init.sql restart: always ports: - "5555:5432" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres rabbit: image: rabbitmq ports: - "5673:5672" depends_on: - db company_tasks: build: . command: > bash -c "pip install psycopg2-binary && pip install -r pip_requirements.txt && python manage.py migrate && python manage.py runserver && celery -A company_tasks worker -l info -B" volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db Though I can access it from the host system with: psql -h 127.0.0.1 -p 5555 -U postgres Company_tasks is a django app and it complains: company_tasks_1 | django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5555 failed: Connection refused company_tasks_1 | Is the server running on that host and accepting TCP/IP connections? my django settings.py: DATABASES = { 'default': { 'ENGINE': "django.db.backends.postgresql", 'NAME': 'company_tasks', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': '127.0.0.1', 'PORT': '5555', } } How Can I make database container visible to company_tasks container? I've tried setting up bridge networks but it didn't work. I can't use 5432 port on the host because another instance of postgres is taking it.