Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? ] -
Django redirecting to page with post requet
hey can anyone help me my django website has login page with post as home page then it goes to main content page there is a button to delete my record after delete i want to redirect to the content page but it has a post request of login page so how can i manage it help me out flow chart login(home page)--(Post)--> Content page--> delete function in content page then redirect to content page after deleting item but content has come by post request -
close connection in `StreamingHttpResponse` and do something after that
I use StreamingHttpResponse in django framework. I want to save some records in database after response finished and connection closed. What should I do? class foo(View): def get(self, request): response = StreamingHttpResponse(self._load_stream(request)) return response def _load_stream(self, request): yield('<html><body></body></html>') time.sleep(5000) # close the connection and then save something to database -
how to display serializer in delete action with django rest swagger
By default, django serializer swagger doesn't displayed the Serializer in DELETE method. But, for some reason I need to implement prevent deletion & force deletion case. So, basicly to implement it, we need to add e.g this example inside the request body: { "forceDelete": true } I'm trying to update the serializer inside get_serializer_class function, but it still doesn't work properly. class GroupViewSet(ModelViewSet): permission_classes = (IsOrganizationAdmin,) serializer_class = GroupSerializer search_fields = ('display_name',) def get_serializer_class(self): if self.action == 'destroy': return ForceDeleteSerializer return self.serializer_class -
Clean expected ExclusionConstraint IntegrityError in Django Admin or Form
The docs show a way to embrace the data integrity constraints PostgreSQL provides, f.e. the ExclusionConstraint for overlapping Ranges. You can read the suggested solution from the docs here. I want to have a reservation system which makes sure that a "thing" (here a trainer/teacher) can't be booked twice for a overlapping period of time. I am going with the 2nd example from the documentation where the overlapping criteria is derived from existing fields: from django.contrib.postgres.constraints import ExclusionConstraint from django.contrib.postgres.fields import ( DateTimeRangeField, RangeBoundary, RangeOperators, ) from django.db import models from django.db.models import Func, Q class TsTzRange(Func): function = 'TSTZRANGE' output_field = DateTimeRangeField() class Reservation(models.Model): trainer = models.ForeignKey('Trainer', on_delete=models.CASCADE) start = models.DateTimeField() end = models.DateTimeField() cancelled = models.BooleanField(default=False) class Meta: constraints = [ ExclusionConstraint( name='exclude_overlapping_reservations', expressions=( (TsTzRange('start', 'end', RangeBoundary()), RangeOperators.OVERLAPS), ('trainer', RangeOperators.EQUAL), ), condition=Q(cancelled=False), ), ] So, this works just fine for me and when trying to save an invalid Range, I'll get the expected IntegrityError: IntegrityError at /admin/trainer/trainingevent/add/ conflicting key value violates exclusion constraint "exclude_overlapping_reservations" DETAIL: Key (tstzrange(start, "end", '[)'::text), trainer_id)=(["2020-12-19 16:20:00+00","2020-12-19 16:55:00+00"), 1) conflicts with existing key (tstzrange(start, "end", '[)'::text), trainer_id)=(["2020-12-19 16:15:00+00","2020-12-19 16:45:00+00"), 1). Which leads to my question: How can I validate the fields or rather make … -
Django DEPLOYMENT on pythonanywhere - SECRET KEY
I'm trying to deploy my Django Project on pythonanywhere. This is my first time doing anything of the sorts, so I'm pretty confused. On my pc, in the project folder I've created a .env file in which I stored private datas like the SECRET_KEY. Then I created a .gitignore file and inside I wrote .env. So my .gitignore is: .env and my settings.py contains: import os SECRET_KEY = os.getenv("SECRET_KEY") Then I pushed my project on GitHub. Then I cloned it into pythonanywhere. I followed this instruction: https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/ so on pythonanywhere I changed the wsgi file. When I write in the console: python3 manage.py migrate I get this error: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I really don't know how to solve this! I've tried several things including saving the private datas on a .bash_profile file, and I tried to store them in a file saved on my Desktop by doing: with open('/.../secret_key.txt') as f: SECRET_KEY = f.read().strip() but on pythonanywhere I get the error: No such file or folder Can someone please help me? Because it's days that I'm trying to solve this! -
best practice django project models
Actualy I am working on a django project and i would like to organize my project as follows : - Backend application (Django) with many applications (client, products,...) - API (Rest Framework) - Frontend (react js). Now my question is about models. what's the best way to organize my models files? Create a template file for all projects as (app with juste models file)? Create a template file by apps like default? or create many models files by applications? Thank you so much -
Get id from path variable url Django
I want my end-point to be like api/units/:id so to pass the id as path variable I have writeen the following code urlpatterns: path('api/units/', UnitDetailsView.as_view()) views.py class UnitDetailsView(APIView): http_method_names = ['get'] permission_classes = (permissions.AllowAny,) serializer_class = UnitDetailsSerializer def get(self, request, id_unit): unit = Unit.objects.get(id=id_unit) return JsonResponse({ 'id': unit.id, }, status=200) However is het a 500 error, because it doesnt recognise the path variable as the id_unit TypeError: get() missing 1 required positional argument: 'id_unit' What is the error and how could i fix it? -
how to display image in django template on browser while showing to user
While trying to display the image on django template from django ckeditor , it shows as follows let me know how to display the image on django template and thanks in advance -
Django model with foreign key throws error on save
I have a model with a foreign key that throws an error when I try to create a new object. I believe that the foreign key field (user_profile_id) is NULL for some reason (it shouldn't be), and when attempting to create, the error is thrown (the field should never be null). This is the error I get: IntegrityError at /api/sensors/ NOT NULL constraint failed: sensors_api_sensor.user_profile_id Request Method: POST Request URL: http://127.0.0.1:8000/api/sensors/ Django Version: 2.2 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: sensors_api_sensor.user_profile_id Exception Location: /home/vagrant/env/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /home/vagrant/env/bin/python3 Python Version: 3.6.9 Python Path: ['/vagrant', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/vagrant/env/lib/python3.6/site-packages'] Server time: Mon, 21 Dec 2020 08:29:01 +0000 models.py: class Sensor(models.Model): """Database model for users' sensors""" user_profile = models.ForeignKey( settings.AUTH_USER_MODEL, # first argument is the remote model for this foreign key on_delete=models.CASCADE # if ForeignKey is deleted, delete all associations ) name = models.CharField(max_length=255) sensor_type = models.CharField(max_length=255) surrounding = models.CharField(max_length=255) latitude = models.FloatField() longitude = models.FloatField() created_at = models.DateTimeField(auto_now_add=True, null=False) # auto adds creation timestamp UTC for each object updated_at = models.DateTimeField(auto_now=True, null=False) # other fields required REQUIRED_FIELDS = ['user_profile','name','type','surrounding'] # model to string conversion method def __str__(self): """Return the model as a string""" return self.name …