Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
set a form field as None value before saving it
i have a model filed like this : lat = models.DecimalField(max_digits=19, decimal_places=16,null=True,blank=True) in my views i need to set it as None before saving the form and somehow i can't figure out how! it raises this error: IntegrityError at /meeting/create-meeting/ NOT NULL constraint failed: meeting_meeting.lat how can i solve it? meeting=form.save(commit=False) meeting.number_of_member = len(form.cleaned_data['members_email'].split(',')) members = form.cleaned_data['members_email'] if "is_virtual" in request.POST: meeting.lat = None meeting.lng = None else: meeting.lat= round(form.cleaned_data['lat'],14) meeting.lng = round(form.cleaned_data['lng'],14) Many Thanks! -
How to update the status of a particular user type on creation of the User
I have a particular User_type model in my database. I use them to determine the types of the user and also determine what they have access to in my web application. I am able to set the user_type status to is_admin=True when using the create_superuser but it doesn't work when creating the user from the Django Admin Dashboard. models.py class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = datetime.datetime.now(pytz.utc) email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user = self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) user_type.objects.update_or_create( user=user, defaults={ 'is_admin': True } ) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) # CUSTOM USER FIELDS picture = models.ImageField(upload_to='images/users', blank=True, null=True, default='images/users/profile-pixs.jpg') created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) class user_type(models.Model): is_admin = models.BooleanField(default=False) is_manager = … -
Django 3 delete field items via Admin panel
I have a Django app, in which i have a model of Candidate, and the candidate has a field Video - goes as file. I do have the option to change the field, for example upload a new video, and it will replace it, but how can i delete a video of a candidate, and leave it empty? currntly i have something like this in the admin panel: Currently: uploads/VIDEOS/mediarecorder_11.mp4 Change: [Coose File] No file chosen how can i just delete the video, and leave it empty? -
Pagination in django keeps showing all the contents
Good day, I implemented pagination in my Django project, the pagination works ok, but all the contents keep showing. I used Django documentation I'd show some screen shots when the pages number is clicked, it reloads but nothing seemed to change, and it did not reduce the number of contents to the specified number views.py from django.shortcuts import render from django.core.paginator import Paginator from .models import Order def order_list(request): orders = Order.objects.all() current_user = request.user success = Order.objects.filter(user=current_user.id).filter(paid=True) fail = Order.objects.filter(user=current_user.id).filter(paid=False) success_paginator = Paginator(success, 10) success_page = request.GET.get('page') posts = success_paginator.get_page(success_page) fail_paginator = Paginator(fail, 10) fail_page = request.GET.get('page') failpost = fail_paginator.get_page(fail_page) return render(request, 'orders/order/order_list.html', { 'success': success, 'fail': fail, 'current_user': current_user, 'orders':orders, 'posts': posts, 'failpost': failpost, }) list.html (for posts) <nav aria-label="Page navigation example"> <ul class="pagination"> {% if posts.paginator.num_pages > 1 %} {% if posts.has_previous %} <li class="page-item"><a class="page-link" href="?page={{posts.previous_page_number}}">Previous</a> </li> {% endif %} {% endif %} <li class="page-item"><a class="page-link" href="#">{{ posts.number }}</a> </li> {% if posts.has_next %} <li class="page-item"><a class="page-link" href="?page={{ posts.next_page_number }}">Next</a> </li> <li class="page-item"><a class="page-link" href="?page={{ posts.paginator.num_pages }}">Last</a> </li> {% endif %} </ul> </nav> list.htm (for failpost) <nav aria-label="Page navigation example"> <ul class="pagination"> {% if failpost.paginator.num_pages > 1 %} {% if failpost.has_previous %} <li class="page-item"><a class="page-link" href="?page={{failpost.previous_page_number}}">Previous</a> … -
DRF How to change the field key names in JSON response
I want to display all objects of a particular model, and it's related objects ( object-wise ). Is there a way to change/customize the JSON output? (In terms of the key names, values, or the nesting?) views.py @api_view(['GET']) def api(request): q = Question.objects.all() s = QuestionSerializer(q, many=True) print(ChoiceSerializer()) return Response(s.data) serializers.py class QuestionSerializer(serializers.ModelSerializer): choices = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Question fields = '__all__' models.py class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField(auto_now_add=True, editable=False, name='pub_date') def __str__(self): return self.question_text def __unicode__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='choices') choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text def __unicode__(self): return f"{self.choice_text}" def related_question(self): q = self.question.question_text return q Output HTTP 200 OK Allow: OPTIONS, GET Content-Type: application/json Vary: Accept [ { "id": 1, "choices": [ 1, 2, 3 ], "question_text": "Question 1", "pub_date": "2020-12-19T23:07:25.071171+05:30" }, { "id": 2, "choices": [ 4, 5 ], "question_text": "Question 2", "pub_date": "2020-12-21T13:58:37.595672+05:30" } ] In the output, choices shows the pk of the objects. How can I change that to show, say, the choice_text or a custom string? Also, can the way the objects are nested be … -
Testing if a endpoint called a function using pytest
I want to create a test that returns if a function was called by an endpoint. This is my scenario: I have a function in file tasks.py: def function_called_by_endpoint(): pass And I have a endpoint in file views.py: class ExampleViewSet(viewsets.ModelViewSet): @action(detail=True, methods=["post"]) def should_call_the_function(self, request, pk=None): pass I would like to know if function_called_by_endpoint was called by should_call_the_function. I'm trying to do it that way: def test_call_func(self, db, client): resp = client.post( "/api/v1/example/1/should_call_the_function/", data={"something": "is ok"}, format="json" ) from my_app import tasks tasks.should_call_the_function() But I get this error: E AttributeError: 'should_call_the_function' object has no attribute 'assert_called' Does anyone have any idea what's missing? -
I am getting the following error after deploying the django project using NGINX. Using Django channels ASGI
My asgi files looks like this. After running daphne -b 0.0.0.0 -p 8001 ludomission.asgi:application this command I am getting this error. I am stuck with this error since 3 days. Please help """ ASGI config for ludomission project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os #from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter,URLRouter from django.urls import path from game import consumers from django.urls import re_path from django.core.asgi import get_asgi_application from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ludomission.settings') django.setup() application = get_default_application() django_asgi_app = get_asgi_application() ws_pattern= [ ] application= ProtocolTypeRouter( { # "http": django_asgi_app, 'websocket':(URLRouter(ws_pattern)) } ) -
Adding values in choices fields in form from django model
I have model called as settings, storing 'product_type' in key and {'product1','product2'} in its value class Settings(models.Model): key = models.CharField(max_length=100) value = models.CharField(max_length=1000) And I have Django form field called as product_type. From Settings models, I'm fetching the tuple value value and appending as choices in product_type form field class InspectionForm(forms.Form): PRODUCT_TYPES = [(product, product.upper()) for product in eval(Settings.objects.get(key='product_type').value)] product_type = forms.ChoiceField(choices=PRODUCT_TYPES) The problem I'm facing is that whenever I add new value in tuple ( which gets store in settings models ), the form field product_type is showing old values only, during rendering the template from view ( which calls the InspectionForm() class ) But when I do runserver, then its shows the lastest values. -
possible Form Field Errors for ChangePasswordForm Django
I'm trying to customize the form field errors for a changepasswordview in Django, however, to do that I believe I need to know the attribute names of the field errors so that I can do something like this: class UserUpdatePassword(PasswordChangeForm): class Meta: model = User fields = ('password') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['old_password'].label = "Password antiguo" print(self.fields['new_password1'].error_messages) self.fields['new_password1'].label = "Nuevo Password" self.fields['new_password1'].help_text = "Mínimo 8 caracteres, números y letras" self.fields['new_password2'].label = "Confirmar nuevo Password" self.fields['new_password1'].error_messages = {'password_mismatch': "Los Passwords ingresados no son iguales",} I know there are errors for password and password confirmation mismatch, when the password is not long enough, only letters or numbers, etc. Where can I find the attribute names? (e.g. 'password_mismatch') -
Open-Source Frameworks based on Django for E-Commerce?
Can someone help me with some good open-source frameworks / platforms based on Django to kickstart my E-Commerce Project? I have already tried the following: Saleor Django-Oscar Django-salesman -
Django: NOT NULL constraint failed: new__create_post.author_id
Error: NOT NULL constraint failed: new__create_post.author_id models: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) -
Import to database (mysql, django) very slow
Good day! I have some problems. I need import some data from txt-file to databes. Ok i wrote this function: def handle_import_airlines(f): reg = r"([A-Z]{3})\t([A-Z,\. ()]+)\t([A-Z ]+)\t([A-Z ]+)\n" with open('temp.txt', 'wb+') as n: for ch in f.chunks(): n.write(ch) with open('temp.txt', 'r') as r: for line in r: m = re.match(reg, line, re.MULTILINE) if m: a = Airlines(code=m.group(1), full_name=m.group(2), name=m.group(3), country=m.group(4)) a.save() os.remove('temp.txt') But it is very slowly. I think it is because i make request to database for write each item. How can i mak one big request for import all items in one request? -
How to get form field through html in Django
I unable to get gender data, because i am directly importing the other fields of django form like {{ form.name }}, What I tried in html to access the field is mentioned below: Want to use this .html <input type="radio" id='radio_button_value_male' name="gender" value="Male"> <label for="radio_button_value_male">Male</label><br> <input type="radio" id='radio_button_value_female'name="gender" value="Female"> <label for="radio_button_value_female">Female</label><br> Instead of this .html, <!-- <div class="">{{ form.gender }}</div> --> models.py, gender = models.CharField(choices=CHOICES,max_length=200,default=None) Please guide me... -
K8s - Celery liveness probe
can smb tell me how to setup a good liveness/readiness probe for celery worker/beat under K8s? Im Using celery in version 5.0.4 (Latest at the moment). This question has already been explained here: https://github.com/celery/celery/issues/4079 Problem now is that Celery has dropped the support for the Module celery.task, also see: Django and Celery - ModuleNotFoundError: No module named 'celery.task' So using something like this wont work anymore: readinessProbe: exec: command: [ "/usr/local/bin/python", "-c", "\"import os;from celery.task.control import inspect;from <APP> import celery_app;exit(0 if os.environ['HOSTNAME'] in ','.join(inspect(app=celery_app).stats().keys()) else 1)\"" ] Can smb help or maybe can share a snipped of his K8s manifest? Thanks in advance -
try to make my website see if there a used email
I am new to Django and i am trying to make my first registration app!! I used the UserCreationForm But when i run The code and try to register if i put the same email form many user it didn't give me any error My forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] my views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages # Create your views here. from .forms import RegisterForm def registerUser(request): form = RegisterForm() if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = RegisterForm() return render(request, 'register.html', {'form':form}) def loginUser(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username and password: user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Username or Password is Incorrect') else: messages.error(request, 'Fill out all the fields') return render(request, 'login.html', {}) def home(request): return render(request, 'home.html', {}) def logoutUser(request): logout(request) return redirect('home') def Profile(request): return render(request, 'profile.html', {}) so please any help or tips -
why does "Unknown command: 'startaap'. Did you mean startapp"?
the following happens when i try to make an aap (also i am C:\Users\lenovo\mysite>py manage.py startaap polls Unknown command: 'startaap'. Did you mean startapp? Type 'manage.py help' for usage. -
How to access Queryset returned to template by AJAX response - Django
I want to return a queryset to a template using ajax. this is my ajax function in a seperate js file: $(document).ready(function(){ $("#data_to_plot_button").click(function(){ var serialized_data = $("#data_to_plot_form").serialize(); $.ajax({ url: $("data_to_plot_form").data('url'), data: serialized_data, type: 'post', success: function(response){ $("#graph").append('<p>data returned successfuly</p>'); //this line is printed correctly. $.each(response, function(i, val) { $('graph').empty().append( $('<li>').addClass('list-group-item list-group-item-success').text(val) ) }); // this block adds nothing to the #graph div } }) }); }); and my views.py: def my_products(request): queryset_list_intro_products = Intro_products.objects.all().order_by('title') products = 0 if request.method == 'POST': products_checkbox = request.POST.get('products') if products_checkbox: products = serializers.serialize('json', list(queryset_list_intro_products)) context = { 'products': products, } return JsonResponse(context, status=200) return render(request, 'users/basket/my_products.html') based on an answer to this question, I try to access the returned products which is in response. but the js code adds nothing to the #graph div. in XHR section of network tab of inspects in chrome, the ajax call's status is 200 and in the preview section I can see the products as following: products: "[{"model": "products.intro_products", "pk": 5, "fields": {"products_intro": false, "ip_sensor_intro": false, "control_valve_intro": false, "water_quality_sensor_intro": false, "accessories_intro": true, "cover_intro": "photos/products/intro_cover/solutions.png", "title": "Accessories", "subtitle": "", "description": "description", "detailed_description": "", "video_link": "", "is_published": true, "image_left": "", "title_left": "", "description_left": "", "image_right": "", "title_right": "", "description_right": ""}}, … -
i keep recieving WSGi error when trying o deploy my django application to pythonanywhere
MY pythonanywhere error log details This is my error log file, i have been stucked on this for four day now, please someone help... -
Django cronjob not running
I am trying to create a cronjob from a custom Django command. When I run the command manually, it works perfect. Exactly what I want. The only thing is, that I want it scheduled (twice a day). But when I put the exact same command in crontab -e it doesn't work? Any suggestions? Crontab -e: # Edit this file to introduce tasks to be run by cron. # # Each task to run has to be defined through a single line # indicating with different fields when the task will be run # and what command to run for the task # # To define the time you can provide concrete values for # minute (m), hour (h), day of month (dom), month (mon), # and day of week (dow) or use '*' in these fields (for 'any'). # # Notice that tasks will be started based on the cron's system # daemon's notion of time and timezones. # # Output of the crontab jobs (including errors) is sent through # email to the user the crontab file belongs to (unless redirected). # # For example, you can run a backup of all your user accounts # at 5 a.m … -
Has anyone tried hosting Saleor on a cPanel shared hosting? Mine comes with a 'Python App' support as well
Can someone help me with steps to get a Saleor(https://saleor.io/) instance running on my shared hosting? I have managed to deploy other simple Django Apps earlier but Saleor seems to be a bit complicated. -
Save django template as image after rendering
I prepared a Django template witch to allow me to print charts. I use cdn for bootstrap and chartjs and with using render_to_string I save it to html file (look below). So if I open this file in the browser I can see everything as I want. But now I want to save it as an image or another type of file which will allow me to open results if I don't have an internet connection. content = render_to_string('my_template.html', { 'title': choosen_title, 'data', values,}) with open('file.html', 'w') as f: f.write(content) So have anybody has any idea how can I save automatically page content to an image file after rendering page? -
Python Django Pyrebase5
I tried every solution but I can't be able to remove this error, I think pyrebase5 is installed in my pycharm but I always got this error. I am using pip 20.3.3 and Python 3.7.7. and pyrebase5. please help me, I am stuck in it. File "E:\Hafr_Project\Hafr_Project\Hafr\HafrApp\urls.py", line 3, in from . import views File "E:\Hafr_Project\Hafr_Project\Hafr\HafrApp\views.py", line 3, in from pyrebase import pyrebase File "C:\Users\mians\AppData\Roaming\Python\Python38\site-packages\pyrebase_init_.py", line 1, in from .pyrebase import initialize_app ModuleNotFoundError: No module named 'pyrebase.pyrebase' -
django - this field is required error despite default value declared
Django error this field is required in a charfield, despite entering values the form doesnt seem to accept them. i have tried using default values for the charfield but the error persists, ran multiple migrations. attached are the screenshot and code Here is the models.py class brief_download(models.Model): metric_choices = [ ('insider_trans','insider_trans'), ('key_stats','key_stats'), ('news', 'news'), ('valuation', 'valuation_measures') ] company_name = models.CharField(max_length=100, default='ITC') metric = models.CharField(max_length=100, choices=metric_choices, default='key_stats') Here is the views.py def corpdata(request): if request.method == 'POST': form = comp_form(request.POST) if form.is_valid(): co_name = form.cleaned_data['company_name'] met_name = form.cleaned_data['metric'] tick = Ticker(co_name + '.NS') if met_name == 'insider_trans': dfs = tick.insider_trans data = dfs if met_name == 'key_stats': dfs = tick.key_stats data = dfs if met_name == 'news': dfs = tick.news() data = dfs if met_name == 'valuation': dfs = tick.valuation_measures() data = dfs return render(request, 'main/corpdata.html', context={'form':form, 'data':data}) else: form = comp_form() return render(request, "main/corpdata.html", context={'form':form}) Here is the forms.py class comp_form(forms.ModelForm): class Meta: model = brief_download fields = '__all__' Here is the template.html <div class="container"> <form method="post" name="corpdataform"> {% csrf_token %} <table>{{ form.as_table}}</table> <button type="submit" name="metric" class="btn btn-primary">Get Data</button> </form> </div> <div class="container"> {% if data %} {{ data }} {% endif %} </div> -
Wagtail "prefetch" image urls for multiple pages
My page contains links to multiple Wagtail pages. The pages come from a query which looks something like this: SubPage.objects.in_site(site).live() Now, each page can have an image, so I'm presenting them in the template: {% for page in pages %} {% if page.header_image %} <div class="text-center"> {% image page.header_image width-400 class="img-fluid" %} </div> {% endif %} <h3> <a href="{{page.url}}"> {{ page.title }} </a> </h3> {% endfor %} The image rendering results, however, in a separate SQL query per page! Is there a way to sort of prefetch these image URLs in one query, best in a join with the original page query? Or generate them without SQL? The whole page is presumably dynamic, so caching alone isn't the answer. -
ModuleNotFoundError: No module named 'debug_toolbar' Django 3.1
I'm facing a "common" problem apparently as I searched and found several topics about it. None of the answer provided worked for me as I already did everything mentionned. I setup the virtualenv Then, I installed django-degub-toolbar pip install django-debug-toolbar Add the application in the settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # External apps 'debug_toolbar', # Internal apps ..., ] And edited the middleware 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', # Django Toolbar interaction with the middleware 'debug_toolbar.middleware.DebugToolbarMiddleware', ] But nothing worked and I still got the error when I run the server.