Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to make an electronic queue for bank visitors on django?
I would like to make an electronic queue for bank visitors. When the client comes to the bank, he presses the button, then the terminal prints out the number. And I want to do it on django. Please advise what useful libraries are there in python django? Ideas will also be helpful. -
Why is an item displying at the very bottom of a django template/page?
I cannot resolve the following; I'm using django calendar module and I try to display it in a template like this. It is a very first shot with the calendar and what is happening I haven't seen before. The {{ calendar }} renders correctly-ish but it renders at the very bottom of the page regardless of what I do (positioning within the html file, wrapping in divs with positioning etc. Any idea why this might be happening? calendar.html {% extends 'base.html' %} {% block content %} <div class="container background-style min-vh-100"> <a href="{% url 'calendar' %}?{{ prev_month }}"> Previous Month </a><a href="{% url 'calendar' %}?{{ next_month }}"> Next Month </a> {# <div style="display: flex; height: 20px; width: 200px; background: white; border: red 6px solid"></div>#} {{ calendar }} <h3 class="first_heading">Vyberte si volný termín, který Vám vyhovuje</h3> <h4 style="text-align: center">Níže naleznete kalendář. Zde si vyberte volný slot, ve kterém byste si rád(a) domluvila konzultace</h4> <a href="{% url 'booking_step_1' %}" ><button class="button2">Další »</button></a> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </div> {% endblock %} Any advice would be appreciated -
How do I logout Google user in Django app?
I´m trying to logout a Google user using Django. I have seen this post and I have written this in my index.html file: <div> {% if not status %} <a href="/gmailAuthenticate" onclick="gmailAuthenticate()" title="Google">Google</a> {% else %} <p>Your are verified</p> <form id="myform" method="post" action="{% url 'logout' 'google-oauth2' %}5/?next={{request.path }}"> {% csrf_token %} <input type="hidden" name="name" value="value" /> <a onclick="document.getElementById('myform').submit();">discon</a> </form> {% endif %} </div> I have also modified my urls.py: url(r'^logout',views.logout, name='logout'), The problem is that when I run it, I´m getting this error: django.urls.exceptions.NoReverseMatch: Reverse for 'logout' with arguments '('google-oauth2',)' not found. 1 pattern(s) tried: ['logout'] -
Aggregate Sum on Django2
I have 2 tables. Table A is +--+------------------+ | ID | Fastival | +--+------------------+ | 1 | 2020Xmas | +--+------------------+ | 2 | 2019Xmas | +--+------------------+ | 3 | 2020Thanksgiving | +--+------------------+ | 4 | 2019Thanksgiving | +--+—————————+ Fastival isForeignKey for table B,and table B is +--+------------------+ ------------------+------------------+ | ID | fastival_id | money | useofmoney | +--+------------------+ ------------------+------------------+ | 1 | 1 | 100 | game +--+------------------+ ------------------+------------------+ | 2 | 1 | 20 | clothes +--+------------------+ ------------------+------------------+ | 3 | 3 | 50 | food +--+------------------+ ------------------+------------------+ | 4 | 4 | 10 | game +--+------------------+ ------------------+—————————+ | 1 | 2 | 30 | food +--+------------------+ ------------------+------------------+ | 2 | 3 | 15 | game +--+------------------+ ------------------+—————————+ Please someone tell me how to get the "sum of money in game of 2020xxx" in Django2? I tried context["money"] = TableB.objects.filter(fastival_id=TableA.objects.filter(Fastival__startswith=2020.values('id')[0]['id']).filter(useofmoney="game").aggregate(Sum('money'))['money']. But that response "None"... -
Request to Django project fails due to no referer, whats the best way round it?
When I send requests to my API django project, I get a 403 stating "CSRF failed, referee checking failed - no referer". the only way to fix this I've found is setting the Referer header on the request. but should I have to do this? should the referer not be taken from the url? I should add that i have two apps that call this api with POST requests- one works fine without setting the header explicitly, the other doesnt. I have DRF and corsheaders installed. -
How to get Model.objects with a parameter
How could I get a list of Posts and get an extra field saying if some fixed user has liked the post or not? I know how to do it in Python but I wonder how this could be done with SQL instead. Post.objects.all()... # pass the user somehow These are my User and Post models from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): following = models.ManyToManyField("self", blank=True, related_name="followers") class Post(models.Model): TEXT_MAX_LENGTH = 140 text = models.CharField(max_length=TEXT_MAX_LENGTH) poster = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") timestamp = models.DateTimeField(auto_now=True) likes = models.ManyToManyField(User, blank=True, related_name="liked_posts") def is_liked_by(self, user: User): return self.likes.filter(pk=user.pk).exists() -
How to access foreignkey/ OneToOneField table's data from a ModelForm?
I have a model called Profile that is related to the User Model. I would like to make a ModelForm for the model Profile. I would like that form to be able to access user's fields. class Profile(models.Model): user=models.OneToOneField(settings.AUTH_USER_MODEL,related_name='profile',on_delete=models.CASCADE) address = models.CharField(max_length=250) contact_number = models.IntegerField(max_length=20) def __str__(self): return self.user.first_name class ProfileForm(forms.ModelForm): class Meta: model=Profile fields=['first_name','address','contact_number'] The error shown is django.core.exceptions.FieldError: Unknown field(s) (first_name) specified for Profile Thank you. -
How can I fix this : ERROR: Command errored out with exit status 1 : when trying to "pip install psycopg2"
I'm trying to connect Postgresql to my Django app , I know that I should Install psycopg2 using pip "Note: I read other questions and answers in stackoverflow and the other websites but I couldn't fix my problem with their solutions" But I throw an ERROR like this: Collecting psycopg2 Using cached psycopg2-2.8.6.tar.gz (383 kB) Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/banji-x/Projects/real_state_Django/venv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-aoxyqloe/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-aoxyqloe/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-j5i8ukkq cwd: /tmp/pip-install-aoxyqloe/psycopg2/ Complete output (40 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/psycopg2 copying lib/_lru_cache.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/errors.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/sql.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/compat.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-3.8/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.linux-x86_64-3.8 creating build/temp.linux-x86_64-3.8/psycopg x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DPSYCOPG_VERSION=2.8.6 (dt … -
How to handle to GET request in in same FBV(function based View.)
Hello Everyone I am a beginner in Django and I have created one webpage where the user is able to search/Filter results and for this, I have used the Django-filter concept. Now my requirement is user should be able to download that filtered data. To achieve this I have created one separate View class with a download name and trying to pass the same Filter Class Queryset but with no luck, it is giving me all model data (records). Please find the Post: how to use Django filtered class data to 2 seperate view After this, I have checked by keeping the download view in the same render view and found that it is working. (Here problem is that both get requests and at a time only one is working.) My requirement is after doing a search if a user is clicking on download then the second download logic should execute. ############### CTA ############# def retrievecta_view(request): if request.method == 'GET': allcta = CTA.objects.all() allcta1 = allcta allctagen = allcta1.filter(Shift_timing__exact='General') allctamor = allcta1.filter(Shift_timing__exact='Morning') allctseve = allcta1.filter(Shift_timing__exact='Evening') allctatotal = allcta1.filter(Shift_timing__exact='Total') # For filtering using 'django_filters', cta_list = CTA.objects.all() cta_filter = CTAFilter(request.GET, queryset=cta_list) allcta = cta_filter.qs paginator = Paginator(allcta, 50) page_number = request.GET.get('page') … -
How to change the timezone in the particular django admin Model?
I want to change the timezone just within the one Particular Model in django admin, how can I do that? -
How to pass two conditions as parameters to get() query in django?
I have passed two conditions to the filter() method so it is returning queryset . But how to pass those two conditions to the get() method in order to get response as single object Code: class DailyHolidayView(APIView): def post(self,request): city_name=request.data['city_name'] date=datetime.strptime(request.data['date'], '%d/%m/%Y') print(date) res=Holiday.objects.filter(city_name=city_name,date=date) if (res): ser = MonthSerializer(res, many=True) return Response(ser.data, status=status.HTTP_200_OK) Because i am getting error as below: AssertionError: [{'id': 12, 'date': '05/01/2019', 'holidayName': 'testHoliday2'}] != {'id': 12, 'date': '05/01/2019', 'holidayName': 'testHoliday2'} -
Is it possible to get 'CORS_ALLOWED_ORIGINS' from models in django? | django-rest-api, django-cors-headers
I want to get those site addresses (in settings.py for CORS_ALLOWED_ORIGINS) which are allowed to access in my API from my models.py. But don't know any process how to config CORS_ALLOWED_ORIGINS in settings getting data from models.py. note: site addresses are stored in AllowedSite model. And here is my code: models.py class AllowedSite(models.Model): SiteAddress= models.URLField(max_length=200, default='') settings.py CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", # in this config, How can I add those AllowedSite from models.py? ]