Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django prefetch related by int PK?
I have a model "A" that has: class A: my_fk = models.IntegerField(...) Then doing a query like this: queryset = A.prefetch_queryset().prefetch_related("somemodel") that all works. Now I want to prefetch from table B where B.id = A.my_fk. my_fk isn't a model itself, just the int foreign key to one. Is that possible? Don't want to change the type of my_fk though... -
Infinite time threshold or bypassing time_threshold
Python & Django newbie here, so sorry if I am not making any sense. I am using a Django script where I want to set filter days value to infinite or none to get all data that entered at anytime. Script uses the structures below to filter posts/data based on the post creation date. self.posts.filter(date_created__gte=time_threshold(days=7)) So I am wondering what can I pass instead of days=7 to get all data/posts without any time&date restriction. -
Resolve AnonymousUser in Django
I have some problems when i create send email form using Django. the problem is when i cliked for send button in contact form. I see this problem. settings.py script here : """ Django settings for Connecting_System project. Generated by 'django-admin startproject' using Django 4.0.6. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-ix)p!+kk@f=47&2$%!7w98uflur_!n9o!tr77x3=r=4^r6b%bh' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login.apps.LoginConfig', 'Home.apps.HomeConfig', 'logout.apps.LogoutConfig', 'signup.apps.SignupConfig', 'contact.apps.ContactConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Connecting_System.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join( BASE_DIR , 'templates' )], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Connecting_System.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
It is impossible to add a non-nullable field 'id' to video without specifying a default
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 Video(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title=models.CharField(max_length=100, null=False) description=models.TextField(max_length=1000,null=True) video=models.FileField(upload_to="video/%y",null=False) def __str__(self): return self.title 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 when i try to makemigrations It is impossible to add a non-nullable field 'id' to video without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit and manually define a default value in models.py. This error occurs... Please suggest me what should i do and also suggest me about any changes in model -
Is it possible to get django info without running it
I have a django model, the whole code is completed. but I want to access my model info. a code like this to get field names. for f in myModel._meta.fields: print(f.get_attname()) is it possible to do it from an external python script without running django server? other possible automated ways of doing this and saving results to a file are also appreciated. -
no such table: django_plotly_dash_statelessapp
I'm trying to deploy my app through Render app, and everything is good, except for the HTML link, it shows"no such table: django_plotly_dash_statelessapp". Not really sure how to solve that. Also, does anyone know which app is free for deployment, I used to use Heroku, but they eliminate the free one from November.no such table: django_plotly_dash_statelessapp -
Cannot set up Oracle bucket for django static files storage
I've been trying to set my bucket as django static file storage, but I keep getting this error: botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden Fyi I'm using an oracle customer secret key as the AWS_SECRET_ACCESS_KEY, as instructed in: https://docs.oracle.com/iaas/Content/Object/Tasks/s3compatibleapi.htm I'm also sure that the information on the parametres is valid: ORACLE_BUCKET_NAME = '<snip>' ORACLE_BUCKET_NAMESPACE = '<snip>' ORACLE_REGION = 'sa-saopaulo-1' AWS_ACCESS_KEY_ID = '<snip>' AWS_SECRET_ACCESS_KEY = '<snip>' AWS_STORAGE_BUCKET_NAME = ORACLE_BUCKET_NAME AWS_S3_CUSTOM_DOMAIN = f"{ORACLE_BUCKET_NAMESPACE}.compat.objectstorage.sa-saopaulo-1.oraclecloud.com" AWS_S3_ENDPOINT_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}" AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = '' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/{ORACLE_BUCKET_NAME}/"