Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to increment price if number of days increase in Django
view.py def booking(request): all_location = location.get_all_location() all_products = Product.get_all_products() data = { 'amount': 5000 } data['product'] = all_products data['location'] = all_location return render(request, 'booking.html', data) my html file put type='number' placeholder='enter days' </div> <div class="mb-5"> <div class="row"> <div class="col-6 form-group"> <input type="text" class="form-control p-4" placeholder="" required="required"> **{% comment %}Want to Get Value from days and save it variable {% endcomment %}** </div> </div> **<p>Amount = RS {{amount}} </p> **{% comment %}Want to Save amount in variable if user increase days then amount variable get increment {% endcomment %}** ** <div class="form-group"> <textarea class="form-control py-3 px-4" rows="3" placeholder="Special Request" required="required"></textarea> </div> </div> </div> I want to get and amount days value in variable then want to increment the amount if user increase days. I get the amount dynamically by view function and my other problem is that how to prevent user to change amount from source code. * -
Adding extra path to django get_full_path() through form
I just want to add something to mypath like: bla1/bla2/bla3/something or whatever pass in member! how can i do this? def to(request): if request.method == "POST": x = request.POST['username'] member = whome(unique_user=x) member.save() links.objects.create(path=request.get_full_path()) links().save() return render(request, "home.html") -
Django executing different url
urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("dashboardapp.urls")), ] My terminal is showing Starting development server at http://127.0.0.1:8000/. But when I click the url its changing to different url http://127.0.0.1:8000/sales. But my url has no sales/. but my other project has sales/. Can anybody help with the solution for this -
NoReverseMatch on Django project
I am doing the CS50 web programming course and I am stuck with a url href, when I try to load the page it gives me a NoReverseMatch error. entry.html {% extends "encyclopedia/layout.html" %} {% block title %} Wiki {% endblock %} {% block body %} {% if msg_success %} <p style="color:green">{{msg_success}}</p> {% endif %} {{entry|safe}} <a href="{% url 'editEntry' title %}">[edit]</a> {% endblock %} The href in entry.html gives me the NoReverseMatch error. urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry, name="entry"), path("search", views.search, name="search"), path("create", views.createEntry, name="create"), path("wiki/<str:title>/edit", views.editEntry, name="editEntry") ] If I visit the url wiki/TITLE/edit it renders the view but the href is not working. views.py def editEntry(request, title): if request.method == "GET": entry = util.get_entry(title) editForm = forms.EditPageForm(initial={'title': title, 'data': entry}) return render(request, "encyclopedia/edit.html", { "form": forms.NewSearchForm(), "editPageForm": editForm, "entry": entry, "title": title }) forms.py class EditPageForm(forms.Form): title = forms.CharField(label="", widget=forms.TextInput(attrs={ 'id': 'edit-entry-title'})) data = forms.CharField(label="", widget=forms.Textarea(attrs={ 'id': 'edit-entry'})) -
Is it possible to use a list of fields to query a model in Django
At the outset, let me be upfront that I am not too comfortable with what I am trying to achieve. But, here it is: I am trying to query a random model in my app for which the field names would be passed at runtime. Something like: fields_list = [field1, field2, ...] qs_target_model = target_model.values(fields_list) #, field3) Using the above setup, I get an error: 'list' object has no attribute 'split' The reason I am trying to do this: Both the model and its fields would be selected at runtime!! My question is: Is what I am trying to do possible at all? -
Context Processors in Python Django
context_processors.py from .models import Cart, CartItem from .views import _cart_id def counter(request): item_count=0 if 'admin' in request.path: return {} else: try: cart=Cart.objects.filter(cart_id=_cart_id(request)) cart_items=CartItem.objects.all().filter(cart=cart[:1]) for cart_item in cart_items: item_count += cart_item.quantity except Cart.DoesNotExist: item_count=0 return dict(item_count=item_count) Can someone explain these entire code to me. How's and what is the working of if loop here, return {}. -
Does Django model queries automatically make requests for foreign key reference objects?
Consider the following Django model: class Name(models.Model): pkid = models.BigAutoField(primary_key=True) person = models.ForeignKey(to=Person, on_delete=models.CASCADE) full_name = models.CharField(max_length=100) Will the following query automatically also do a join and retrieve the connected Person object, too? results = models.Name.objects.all() Or are all foreign key reference fields in Django automatically deferred until they are accessed? print(results[0].person) -
I don't want django to process path in order
Let say I have path something like bla1/bla2/bla3/bla4/...../something and I want django to look for last path something first instead of in order. I know we can do this with django-redirects but what if that something is dynamic? -
File not found when running django collectstatic with django pipeline
This is my pipeline setting: STATIC_URL = '/static/' STATIC_ROOT = SETTINGS_DIR + '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static_files"), ) STATICFILES_STORAGE = 'pipeline.storage.PipelineManifestStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', 'compressor.finders.CompressorFinder', 'beautycall.finders.LeftoverPipelineFinder', ) PIPELINE = { 'JAVASCRIPT': { 'main': { 'source_filenames': ( 'bower/jquery/dist/jquery.min.js', 'js/script.js', ), 'output_filename': 'compiled/main_script.js', }, 'datetimepicker': { 'source_filenames': ( 'bower/datetimepicker/jquery.datetimepicker.js', ), 'output_filename': 'datetimepicker.js' }, 'typeahead': { 'source_filenames': ( 'bower/typeahead.js/dist/bloodhound.js', 'bower/typeahead.js/dist/typeahead.jquery.js', ), 'output_filename': 'typeahead.js' }, 'remodal': { 'source_filenames': ( 'bower/remodal/dist/remodal.min.js', ), 'output_filename': 'remodal.js' } }, 'STYLESHEETS': { 'main': { 'source_filenames': ( 'css/style.scss', 'css/fonts.css', ), 'output_filename': 'compiled/main_stylesheet.css', }, 'datetimepicker': { 'source_filenames': ( 'bower/datetimepicker/jquery.datetimepicker.css', ), 'output_filename': 'compiled/jquery.datetimepicker.css' }, 'remodal': { 'source_filenames': ( 'bower/remodal/dist/remodal.css', 'bower/remodal/dist/remodal-default-theme.css' ), 'output_filename': 'remodal.css' }, 'website': { 'source_filenames': ( 'css/website/style.scss', ), 'output_filename': 'compiled/website/style.css', } } } Its return the error raise CompilerError(e, command=argument_list, pipeline.exceptions.CompilerError: [WinError 2] The system cannot find the file specified. When using custom pipefinder, the pipeline seem to miss all the file in source_filenames. Im using Windows and its no problem when i try it in Linux OS, if its help. It result in error when running this piece of code on django-pipeline : compiling = subprocess.Popen(argument_list, cwd=cwd,stdout=stdout,stderr=subprocess.PIPE, shell=False) At closer look the cwd argument seems fine, but 3 of 4 arguments in argument_list not exist … -
Does i need to use django.forms when i using ajax
I gonna made a few forms on one page and post it with ajax. So i got question - do i need use django forms for it, or just views? In my opinion django forms can validate html form by themself, but i actually don't know it. So what is the better decision in that case -
Is it possible to use Django ORM with JSON object?
I got two json objects that I need to combine together based on ID and do count and sort operations on it. Here is the first object comments: [ { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" }, ] This is second json object: [ { "postId": 1, "id": 1, "name": "id labore ex et quam laborum", "email": "Eliseo@gardner.biz", "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium" }, { "postId": 1, "id": 2, "name": "quo vero reiciendis velit similique earum", "email": "Jayne_Kuhic@sydney.com", "body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et" }, ] Is it possible to use django ORM to the json object? such as obj1.objects.count('title') or … -
How can I add atribute to webpage in django
screenshotI'm following a tutorial to create a website using django. I keep getting this error when running the server. path('page2',index.webpage2), AttributeError: module 'website.index' has no attribute 'webpage2'. Did you mean: 'webpage1'? Don't know what I'm missing, the tutorial ran the server without any problem. The only thing I noticed was that it also gave my a missing os error. I fixed this part. Thank you for your help -
django rest_framework how to display nested relationship
I'm trying to display foreign related fields like this example and it works { "reqid": 10, "reqdate": "2022-12-05", "reqdescription": "Aircon Not working", "officerequestor": "OVCAA ", "officeid": "PPD ", "inspection": { "insdate": "2022-12-06", "diagnosis": "need to buy prism", "inspector": "EMP-322 " } }, this is my serializers.py class RequestAdditionDetailsSerializer(serializers.ModelSerializer): class Meta: model = Inspection fields = ['insdate', 'diagnosis', 'inspector' ] class RequestorSerializer(serializers.ModelSerializer): inspection = RequestAdditionDetailsSerializer(read_only=True) class Meta: model = Request fields = ['reqid', 'reqdate', 'reqdescription', 'officerequestor', 'officeid', 'inspection' ] My question is can I do this the other way around like this { "inspectid": 5, "reqid": "10", "insdate": "2022-12-06", "diagnosis": "need to buy prism", "inspector": "EMP-322", "isinspected": { "reqdescription": "Aircon Not working", "reqdate": "2022-12-05", "officerequestor": "OVCAA" } }, this is what I've tried, tbh I don't think this will work is there a solution for this. if no maybe i'll add additional columns on inspection like reqdescription,reqdate etc.. just to show them class InspectionAdditionalDetailsViewSerializer(serializers.ModelSerializer): class Meta: model = Request fields = ['reqdescription', 'reqdate', 'officerequestor' ] class InspectionSerializer(serializers.ModelSerializer): request_details = InspectionAdditionalDetailsViewSerializer(read_only=True) class Meta: model = Inspection fields = ['inspectid', 'reqid', 'insdate', 'diagnosis', 'inspector', 'isinspected', 'request_details' ] this is my models.py class Inspection(models.Model): inspectid = models.AutoField(primary_key=True) reqid = models.OneToOneField('Request', models.DO_NOTHING, db_column='reqid', blank=True, null=True) … -
Cannot get url parameter to work in Django
I am trying to pass a parameter through the url in Django, but nothing seems to be working. This is my views.py: from django.shortcuts import render def show_user_profile(request, user_id): assert isinstance(request, HttpRequest) return render(request, "app/show_user_profile.html", {'user_id': user_id}) This is currently my urls.py: urlpatterns = [ path('', views.home, name='home'), path('profile/', views.profile, name='profile'), path(r'^show_user_profile/(?P<user_id>\w+)/$', views.show_user_profile, name="show_user_profile"), path('admin/', admin.site.urls), ] I've tried http://localhost:50572/show_user_profile/aaa, I've tried http://localhost:50572/show_user_profile/aaa/, and http://localhost:50572/show_user_profile/aaa//, even http://localhost:50572/show_user_profile/?user_id=aaa, but I always get that same screen saying it can't find the url pattern. enter image description here But I've tried, all failed. And neither does this: path('show_user_profile/<int:user_id>/$', views.show_user_profile, name='show_user_profile') This doesn't work either, by the way. path(r'^show_user_profile/$', views.show_user_profile, name="show_user_profile"), I've looked at the answers here and here, and I seem to be doing everything right. What am I missing? -
does using django for a mobile app backend is a good option? [closed]
I would like to create a fully working mobile application by using react native as the frontend and django as the backend. The reason of using django as the backend is because of the django rest framework (drf). Does using django will fulfil the needs of backend services for a mobile application? I tried to find a good reference and documentation to make this work. Since there is not much I found based on my research, does this mean that using django as the backend services for mobile application is not recommended or is it just not that common for developers? -
Django: is there a way to add users to a ManyToManyField of a model each for a certain amount of time?
i have a website that has video courses for my students that they can buy and use, title = ,,, price = ,,, buyer = models.ManyToManyField(User, blank=True, related_name='my_attendance_courses') i want this field to also have expiration date for each user it holds, so my students only have the course for 1 month after they bought it is there a way i can to this? -
Cloud build error: failed to build: executing lifecycle. This may be the result of using an untrusted builder: failed with status code: 51
I am trying to deploy a template Django project to cloud run using cloud shell from the following tutorial: https://codelabs.developers.google.com/codelabs/cloud-run-django In step 7, on running the command: gcloud builds submit --pack image=gcr.io/${PROJECT_ID}/myimage to build the application image, this error is coming: `ERROR: failed to build: exit status 1 ERROR: failed to build: executing lifecycle. This may be the result of using an untrusted builder: failed with status code: 51 ERROR ERROR: build step 0 "gcr.io/k8s-skaffold/pack" failed: step exited with non-zero status: 1 BUILD FAILURE: Build step failure: build step 0 "gcr.io/k8s-skaffold/pack" failed: step exited with non-zero status: 1 ERROR: (gcloud.builds.submit) build 75a52dae-9a4f-4591-af13-5fe1228533b4 completed with status "FAILURE"` The file migration.yaml is same as the tutorial and I have followed all steps exactly as they were in the tutorial. Can someone please help me with this error ? -
Extanding the User model
I am trying to build my first Django backend project, so i'm trying to creatre a REST API end-point that gets a user registration data in json file from the front-end and save it on the database if it's valid. I am trying to save the additional user information in a new model called Player and link it to the default User model using one-to-one-field. When i recive the json file with the data from the front-end the a new user with the data is created in the User model, also a new row is created in the Player model that connected to the user we just created in the User model. But the problem is the fields "height" and "handicap" remain empty. I don't know how to save the "height" and "handicap" parameters into the new Player instance. This is my models.py file: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save from datetime import * # This model extend the basic built-in User model, by adding additional information on the uesr like # handicap score anf height. class Player(models.Model): def __str__(self): return self.user.username user = models.OneToOneField(User, … -
Tried databse queryset on crontab but it doesn't work
Crontab works fine on simple task. e.g def test(): test.objects.create.(name='Dino') but when i tried to query my db it does nothing see example: def test_task(request): if Users_Machine.objects.filter(user=request.user).exists(): test.objects.create(name='Dino', user=request.user) The Users_machine object is present in the db. Here is my models class test(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) Please how can i make this work? -
How to access directory file outside django project
I'm trying to import files that are outside my Django folder, but I get the following error: No module named 'manage_db' It's important to note that I created this package on my local computer, so I don't need to do a pip install. The path from which I want to make a call to the file is: api-yahoo-finance/yahoo/api_yahoo/views I want to import on the following form from the following path: from manage_db.exc_get_symbol import get_symbol And I want to import all the files on the package into the following folder: whose path is manage_db and is outside the api-yahoo-finance folder (On manage_db existing all the files that I want to import) Note: I work with Django Framework. -
Django-wiki installed but root article throws global flag error
I have installed Django-wiki in a fresh virtual Django install. My initial page comes up, the site allows for user registration. Everything looks well until I enter my first Root article. I have kept it rudimentary with a title "Test" and the body just a simple "Hello" but when I save I get this error: error at / global flags not at the start of the expression at position 9 Request Method: GET Request URL: http://aassch1at01.preprod.des:8000/ Django Version: 4.0.8 Exception Type: error Exception Value: global flags not at the start of the expression at position 9 Exception Location: C:\python\Lib\re_parser.py, line 841, in _parse Python Executable: C:\daas_django_apps\env\Scripts\python.exe Python Version: 3.11.0 Error during template rendering In template C:\daas_django_apps\env\Lib\site-packages\wiki\templates\wiki\view.html, error at line 7 Line 7 is: {% wiki_render article %} I have tried checking all my configuration and it seems ok and matches Django-Wiki installation example. Tried changing user ownership of the article and creating a group for viewing but to no avail. Any help would be appreciated. Thank you! -
Filter only one row per one date for different priority
From query which returns multiple rows with different data priority. I need to create subtable with only one date with highest priority. My approach was to just do multiple queries and return query.first(). But this will fire database connection x times, where x is number of different days. list_of_queries = [] for date in dates list: list_of_queries.append( self.get_queryset().filter(date).order_by( Case( *[When(priority__iexact=priority, then=Value(i)) for i, priority in enumerate(priority_list)], default=None ).asc())) Table 1. | ID | DATE | PRIORITY | |---- |------| -----| | 1 | 2022/11/1 | 1 | | 2 | 2022/11/1 | 2 | | 3 | 2022/11/1 | 3 | | 4 | 2022/11/2 | 2 | | 5 | 2022/11/3 | 1 | | 6 | 2022/11/3 | 3 | Table 2. | ID | DATE | PRIORITY | |---- |------| -----| | 1 | 2022/11/1 | 1 | | 4 | 2022/11/2 | 2 | | 5 | 2022/11/3 | 1 | I think I could use some other approach and just gather all rows with date__lte to date__gte and from this subquery in some way just take only one date. But any idea how to do this in Django ORM? Or I have to do multiple … -
How do I find and alter my PATH variable on macOS?
I was forced to reinstall Python and Django after updating to Ventura 13.0.1. However, the Python executables are now in /Users/user/Library/Python/3.9/bin, while the command 'env' shows the PATH variable set to a totally different path. To change this, I need to know the location of my PATH variable, so that I can reference that in my $ echo export PATH="<PATH_TO_PYTHON>:$PATH" >> ~/.profile command in order to alter it, as described here, with ~/.profile being the name of the file containing the PATH variable. However, "ls -la" does not show a .profile, .login, .zsh_profile, .zshrc, or any of the other potential files for this variable. While I tried creating a .zsh_profile file and adding export PATH=$PATH:/Users/user/Library/Python/3.9/bin to it, the command 'env' still shows PATH set to the original file path/directory. Is there a specific command I can use to find the location of that PATH variable, like what file it is being stored in? -
Django + psycopg2 OperationalError could not open certificate file "/root/.postgresql/postgresql.crt": Permission denied
I have a server with ubuntu 22 and a postgres database on digitalocean. I'm deploying a django application there using docker swarm and when I try to access the /admin page I get this error: connection to server at "xxxx.db.ondigitalocean.com" (xx.xxx.xxx.xx), port 25060 failed: could not open certificate file "/root/.postgresql/postgresql.crt": Permission denied I will add that when I created a test script to connect to the database for tests on the server, everything works fine, and I can connect to the database from the local computer. The same project when I run locally connects to the database without any problems DB settings DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "dbname", "USER": "user", "PASSWORD": "pass", "HOST": "xxxx.db.ondigitalocean.com", "PORT": "25060", } } DOCKERFILE FROM python:3.11 ARG GIT_ACCESS_TOKEN RUN git config --global url."https://${GIT_ACCESS_TOKEN}@github.com".insteadOf "ssh://git@github.com" WORKDIR /backend ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY requirements.txt . COPY entrypoint.sh . COPY entrypoint-celery.sh . # ADD /backend /backend COPY /backend /backend RUN python -m pip install -r requirements.txt RUN mkdir -p /backend/tmp RUN chmod -R 777 /backend/tmp RUN mkdir -p /orders/xmls RUN chmod -R 777 /orders/xmls -
Deploying Django app to Remote Red Hat 8 Server. manage.py not working. What am I doing wrong?
I am a 1st year CS Graduate Student who has been put in charge of a refactoring project. The refactoring project has a Django backend that implements a postgresql database using python 3.8. I've never used Django previous to this project so I apologize if the answer is simple. I have the backend refactored and I can run our Django backend locally. However, when I try to run our backend with sudo python3.8 manage.py runserver on our new RHEL 8 server it seems to get hung up after the system check: runserver example I also know that I need to create a super user for the Django postgresql database, but when I run sudo python3.8 manage.py createsuperuser --username <username> Where <username> is an actual name, it also seems to get hung up without outputting anything. Neither of these are outputting an error so I'm unsure what's happening. I know that it's not common practice to use sudo with these commands, but the server gives me permission denied errors if I don't use sudo. I'm not the one who set up the server, our IT department did it and I'm unsure if I needed them to do something specific or not. …