Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
application error deploy using flask, heroku
successfully deployment app After successfully app deploy and when I click view then getting this error and in logs file not understand what is the problem. please help me out. enter image description here logs -
How To Fix create() takes 1 positional argument but 5 were given In python django
I'm Creating Login & Register Form In Django. I got an error create() takes 1 positional argument but 5 were given. code: def register(request): if request.method=="POST": username=request.POST['username'] name=request.POST['name'] email=request.POST['email'] password=request.POST['password'] user_create = User.objects.create(username,name,email,password) user_create.save() messages.success(request, " Your account has been successfully created") return redirect("/") else: return HttpResponse("404 - Not found") html https://paste.pythondiscord.com/amoturoqop.xml -
Django: STATIC_ROOT STATIC_ROOT can't join with BASE_DIR path
I set up my STATIC_ROOT like this STATIC_ROOT = os.path.join(BASE_DIR,'/vol/web/staticfiles') print('this is base_dir') print(BASE_DIR) print("this is static_root") print(STATIC_ROOT) When I run python manage.py runserver it print out this: this is base_dir F:\7.Django\BLOG_PROJECT\src_blog this is static_root F:/vol/web/staticfiles this is base_dir F:\7.Django\BLOG_PROJECT\src_blog this is static_root F:/vol/web/staticfiles When I run python manage.py collectstatic. Sure! It set my STATIC_ROOT AT F:/vol/web/staticfiles. I noticed that it print out the separate folder symbol different '/' and ''. I use windows os btw. Also don't know why it seems my app run settings 2 times. This is my settings ├── settings <br /> | ├──__init__.py <br /> | ├──base.py <br /> | ├──dev.py <br /> | ├──prod.py <br /> and my settings\__init__.py file contain: import os from dotenv import load_dotenv load_dotenv() # you need to set "ENV_SETTING = 'prod'" as an environment variable # in your OS (on which your website is hosted) if os.environ['ENV_SETTING'] =='prod': from .prod import * else: from .dev import * from .base import * -
Exception for 'NOT LIKE' in Oracle_SQL
in a database are many tables with the name 'D_...'. In a search query, all tables with 'D_%' should be ignored, except one. How do I handle this exception? many thanks Exception for 'NOT LIKE' in Oracle_SQL -
Sort django queryset using string field alphabetically
I want to sort users from model with their last names. I am using User.objects.filter(is_active=True).order_by('last_name') Still there is no luck. Pls suggest some solution. -
sender and instance arguments of post_save signal in Django
I'm confused with Django's post-save signal documentation: sender The model class. instance The actual instance being saved. Is "sender" the class of the model instance being saved? Is "instance" an instance of the sender model ? i.e. if I registered a signal receiver to receive post_save signals from the User model using signal.connect(), would "sender" be the User model and "instance" be the instance of the User model being saved ? -
How to set the global WEB_IMAGE and NGINX_IMAGE environment variables
I am following this tutorial and it says Set the global WEB_IMAGE and NGINX_IMAGE environment variables (export WEB_IMAGE = ? what exactly and where? on my local machine or in the droplet?) Add environment variables to a .env file (I created a .env file on the root directory and it is accessble by the Django settings - so this is done) Set the WEB_IMAGE and NGINX_IMAGE environment variables with so they can be accessed within the Docker Compose file I am not sure how to do these steps, can someone please explain? I am on ubuntu 20.04 -
Using filter__in via Foreignkey relationship returns en empty queryset
I'm trying to use the queryset category_filter as a filter__in // Django doc for another query qs_poller. However, the query returns an empty set. # View def render_random_poller(request): if request.user.is_authenticated: category_filter = Category.objects.filter(usercategoryfilter__user=request.user) # Returns <QuerySet [<Category: Sports>, <Category: Lifestyle>, <Category: Environment>]> qs_poller = Poller.objects.filter(poller_category__category__in=category_filter).order_by('-created_on')[:100] # Returns an empty set, although the database holds 5 entries matching the category_filter # Models class UserCategoryFilter(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.ManyToManyField(Category) class Poller(models.Model): created_by = models.ForeignKey(Account, on_delete=models.SET(get_deleted_user)) poller_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) class Category(models.Model): category = models.CharField(max_length=30) -
i have Erroor "Related Field got invalid lookup: icontains" when i try filter on views.py from models.py
here, on views.py I want to filter 'language' from the models.py but it said there is Errror. " raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: icontains" i dont know why just'language' has problem but not when i try to filter 'genre','title', i dont see the Error on the terminal what can be the solutions? here is the models.py from django.db import models from django.urls import reverse import uuid class Genre(models.Model): name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)') def __str__(self): return self.name class Language(models.Model): name = models.CharField(max_length=200, help_text="Enter the book's natural language (e.g. English, French, Japanese etc.)") def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book') isbn = models.CharField('ISBN', max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') genre = models.ManyToManyField(Genre, help_text='Select a genre for this book') language = models.ForeignKey('Language', on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library') book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), … -
I want to create multiple objects with single foreign key relation
I need to add multiple skills for one candidate. As now i am getting the error cannot assign multiple instances to skill models class CandidateSkill(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE,related_name="skills",) skills = models.ForeignKey("jobs.Skill", on_delete=models.CASCADE) ---------- class CandidateSkillSerializer(serializers.ModelSerializer): class Meta: model = CandidateSkill fields = ["id", "candidate", "skills"] -
Adding validator to a model field via __init__ of the class model results in duplication of error messages
I have a model like this: class Permission(models.Model): slug = models.CharField('Метка', unique=True, max_length=255) @staticmethod def slug_field_validator(value): raise ValidationError('Error message') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._meta.get_field('slug').validators.append( self.__class__.slug_field_validator) This results in duplication of error messages in admin interface. What am I doing wrong ? -
How to know blank and non blank fields after a django ajax form submission?
I have a modelform which allows a some non required fields. Where I am stuck is figuring out a way that will allow me to exactly know which field came with data, and which did not so while creating my model instance I won't miss any user data inputted. at beginning I thought of serializing the form by using serializeArray then get the non empty value and add it in the form.serialize() but this prevents the form from being valid. Here is the see question. Is there any way to know this even if it is before processing the ajax or in the django view itself ? Thank you in advance. Code: function CreateIssueAjax(e) { e.preventDefault(); const role = this.getAttribute('role'); const _form = $("#CreateIssueForm"); var formString = _form.serializeArray(); console.log(formString) function sendKwargs(arr) { let kwargs = {} arr.forEach(el => { if (!(el.value === "") | (!(el.name === 'csrfmiddlewaretoken'))) { kwargs[el.name] = el.value } }); return kwargs; } console.log(sendKwargs(formString)); var myData = _form.serialize(); console.log(myData); myData['kwargs'] = JSON.stringify(sendKwargs(formString)); $.ajax({ url: "/create-issue/", type: "post", data: myData, datatype: 'json', success: function (data) { console.log("success"); // add to ui function after success // alert the user(alertify.js) }, }); } def createIssue(request): form = CreateIssueForm(request.POST or None) … -
django.template.exceptions.TemplateDoesNotExist: templates/index.html Error
I am making a Django authentication program but keeps on giving me this error. django.template.exceptions.TemplateDoesNotExist: templates/index.html Error. PLS help me coz I have spent hours trying to solve this problem. Views.py from django.http import HttpResponse def home(request): return render(request, "authentication/index.html") def signin(request): return render(request, "authentication/signin.html") def signout(request): pass Urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('',views.home, name = "home"), path('signin',views.signin, name = "signin"), path('signout',views.signout, name = "signout"), ] Settings """ Django settings for gfg project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # 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/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '-tqa6(3cnb_f@3u(56)mu9z%d2c548xypd-@%6i&60@)mxbs$k' # 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', ] 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 = 'gfg.urls' TEMPLATES = … -
Logging SQL with Django logging configuration. The logger always trying to connect with the public schema
The following is the logging configuration for our Django application logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(asctime)s %(name)-12s %(lineno)d %(module)s %(levelname)-8s %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 15728640, # 100MB 'backupCount': 10, 'formatter': 'verbose', 'filename': 'log_files/acme-slcms.log', 'encoding': 'utf-8', }, 'mail_admins': { 'level': 'CRITICAL', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, }, 'loggers': { 'django': { 'propagate': True, 'level': 'DEBUG', 'handlers': ['file'], }, 'django.db.backends': { 'propagate': False, 'level': 'DEBUG', 'handlers': ['file'], } } }) We have added the django.db.backends logger to print the queries generated by the application. But from the output, it seems the logger is connecting to the public schema 2021-10-06 13:37:39,704 django.db.backends 123 utils DEBUG (0.089) SELECT c.relname, c.relkind FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'v', '') AND n.nspname = 'public' AND pg_catalog.pg_table_is_visible(c.oid); args=None After implementing the log, we are not seeing any queries other than this. The application is actually using another schema for storing and retrieving data and is using django-tenant as part of the homegrown … -
Return JSONResponse before updating database in django, python2
Im having a project running on python2.7. The project is old but still its necessary to update the database when a request is received. But the update process takes time and ends up with a timeout. Is there anyway return JsonResponse/Httpresponse, before updating the database so that timeout doesn't occur. I know its not logical to do so, but its a temporary fix. Also, i cant use async since its python2 -
Django and Django rest framework
I was following a resource https://blog.learncodeonline.in/how-to-integrate-razorpay-payment-gateway-with-django-rest-framework-and-reactjs Instead of using reactjs for the front end. How can i make the frontend using Django templates? Please help. Thank you. -
Showing multi-dimensional data in django
Hej! I have some multidimensional data in my django project, e.g. a status of an institution (containing e.g. a year to differ them). Every institution can have multiple status from different years. Also I have multiple institutions and want a table/list of them. Is there a possibility to show show those multi-dimensional data for each institution? Or maybe the newest? I couldn't find it in the docs. # models.py class StatusOfPlants(models.Model): """status (phases) of plants""" class StatusChoices(models.TextChoices): PLANNING = "planning", _("in foundation") IN_OPERATION = "in_operation", _("in operation") plant = models.ForeignKey( Plant, on_delete=models.PROTECT, related_name="status_of_plant" ) status = models.CharField( max_length=20, choices=StatusChoices.choices ) year_valid_from = models.SmallIntegerField( validators=[validate_year], blank=True, null=True ) year_valid_to = models.SmallIntegerField( validators=[validate_year], blank=True, null=True ) def __str__(self): return f"{self.status}" In the admin area can the multi data be added. I'm just wondering about the presentation in the view when I want more than just a list of the status 'names' in one field. Hope it is clear what I'm talking about and someone has an idea how to solve that! Thanks in advance :) -
How can I change referral of inactive user until I found active referral of current user in django
How can I change referral of inactive user until I found active referral of current user This is my models class ReferralCode(models.Model): user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) user_active = models.BooleanField(default=False) referral = models.ForeignKey( User, related_name='comp_active_user', on_delete=models.SET_NULL, null=True, blank=True) class PointValue(models.Model): user_id = models.ForeignKey( User, related_name='realtime_user', on_delete=models.CASCADE) rt_ppv = models.DecimalField( null=True, max_digits=20, decimal_places=2, default=0.00) this is my views def check_active(request): min_ppv = 20 for user in ReferralCode.objects.all(): try: user_point = PointValue.objects.get( user_id=user ) except: pass if user_point.rt_ppv >= min_ppv: user.user_active = True user.save() else: # getting all users referred by this user users_referred = ReferralCode.objects.filter( referral=user ) # changing referral of all users to parent user of current user for user_referred in users_referred: user_referred.referral = user.referral user_referred.save() user.user_active = False user.save() What I'm trying is I want to check each users in ReferralCode and check it's rt_ppv value from PointValue table if it's greater than min_ppv value than I'm changing it's status to True and if it's not than user status will be False and changing all the users whom he referred to parent of current user (check in the else block) Problem : It's changing referral but the new referral of all users it's rt_ppv it's not greater … -
Can't query Many-to-Many relationship in Django
I do have a Model UserCategoryFilter with a M2M relation to Model Category # View @require_GET def get_category_filter(request): # Get the existing user instance if any filter_instance = UserCategoryFilter.objects.get(user=request.user) # Get the current selections/filters selection = filter_instance.categories_selected print(selection) However, selection always returns None instead of a queryset even though there are three categories selected by the user and stored in the DB. # Models class Category(models.Model): category = models.CharField(max_length=30) category_color = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.category) class UserCategoryFilter(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.ManyToManyField(Category) -
How can I merge two or more queryset objects' field into one?
In my serializer, I have the following query: memberships = Membership.objects.filter( user__id=instance.user.id, project__id__in=instance.organization.projects.values_list('id'), ).order_by('project__name') which gives me: "projects": [ { "project": "3ba96c4c-0b82-4f2a-9e1b-f18a8b63912a", "name": "string 1", "role": 0 }, { "project": "5fab483c-9703-4ed8-a3e7-b1516855fb99", "name": "TestProj", "role": 0 }, { "project": "5fab483c-9703-4ed8-a3e7-b1516855fb99", "name": "TestProj", "role": 1 } ], But I would like the output (for frontend's sake) to be: "projects": [ { "project": "3ba96c4c-0b82-4f2a-9e1b-f18a8b63912a", "name": "string 1", "roles": [0] }, { "project": "5fab483c-9703-4ed8-a3e7-b1516855fb99", "name": "TestProj", "roles": [0, 1] } ], How should I modify my query in order to achieve such result? -
Unable to add data from admin panel to webpage in django
I was trying to add data dynamically from admin to my HTML page in django but when I try to add data in admin panel it is not showing anything in the HTML file. when I do makemigrations i am getting this below You are trying to add a non-nullable field 'link' to researchpaper without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: In admin panel I am getting this error why I am getting this problem please help -
docker python3 deployment fail
I deployed a docker container with this Dockerfile for my Django-rest-application: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ COPY . /app/ RUN /usr/local/bin/python -m pip install --upgrade pip RUN pip install -r requirements.txt However, docker doesn't install python3 on my virtual machine, instead it install python2. Is there a way to make sure the docker install the correct python? Thanks, -
How to change a field in django form after calling is_valid() on the form?
I am changing django model choice field to choice field the form renders fine, but when post data is received and is valid is failed, I change the form field but it renders original field? Is there some over ride? # field_1 is ModelChoiceField by defauly if request.method == 'POST': a_form = My_Form(request.POST, instance=assembly_order) if not a_form.is_valid(): a_form.fields['field_1'] = forms.CharField(max_length=50) return render (request, 'my.html', {'a_form': a_form}) # --------- returns modelchoicefield else: a_form.save() else: a_form = My_Form(instance=None) a_form.fields['field_1'] = forms.CharField(max_length=50) return render (request, 'my.html', {'a_form': a_form}) # renders CharField -
Form content not visible on django homepage?
I was trying my hands on learning django and tried creating a resume builder project where user can get form based template by entering some details on the form, but the form is not visible on the homepage. I'm attaching template code for more refrence. {% extends 'base.html' %} {% block content %} <form method="post" action="post-form"> {% csrf_token %} <p> {{form.as_p}} </p> <input type="submit" value="Save" /> </form> {% endblock %} -
like and unlike django ajax
write an application for like and like using Django and ajax, JQuery function but I noticed that it works fine but the problem is if click like button then I am getting 500 internal errors. Here is POST http://127.0.0.1:8000/like/ 500 (Internal Server Error)## here ajax code when run i get 500 internal error. $('#result').click(function() { var liked = $(".like").val(); var addLike = liked + 1 data = { 'liked': addLike } console.log('data', data) SendAjax(); }); // const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; function SendAjax() { $.ajax({ url: '/like/', method: 'POST', headers: { 'X-CSRFToken': csrftoken }, dataType: "json", data: data, success: function(data) { console.log('success', data.status); if (data.status === 200) { console.log(data.status) // let load_url = 'http://127.0.0.1:8000/' + name; // console.log('load url', load_url); // window.location.replace(load_url); } }, }) }; views.py def like(request) : data= {} name=get_object_or_404(Stylish, id=request.POST.get('id')) context= { 'name': name } print('context', context) print("like") if request.method=='POST' and "GET" : liked=request.POST('liked', None) print('liked', liked) like=likes.objects.create( liked=liked) print('like', like) return render(request, 'index.html', data) <div class="col"> <input type="text" class="form-control text-1 textfont copybutton " data-clipboard-action="copy" data-clipboard-target="#copy_0" for="textfont" style="text-align: center; " value="𝔓𝔯𝔢𝔳𝔦𝔢𝔴 𝔗𝔢𝔵𝔱" id="copy_0" readonly="readonly"> <!-- {% if instance.liked%} --> <span id="count"></span> <input class="like" type="image" src="{% static 'images/like.svg' %}" alt="Like" id="like" title="Like" width="10" height="10" id="heart" value="{{ liked }}"> …