Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Some html attribute do not have autocomplete in VC Code
when i use django some html attribute do not have autocomplete in VC Code: for example attribute 'enctype' in tag 'form'. In file settings.json i written: "emmet.includeLanguages": { "django-html": "html", But it help partly, all tags have autocomplete, but some their attributes do not have autocomplete anyway. if i deactivate django - html autocomplete start work correctly. -
Python automation or Python for web?
I have a doubt: Is it recommended to learn Python for the web and Python Automation at same time? Or is it better to focus on just one area? I'm a programming beginner :D ------------------------------------------------------------- -
Store for loop queryset into one
I currently have an array with multiple objects. The for loop does a queryset based upon the array objects using a for loop of a model. search_post = ["1990", "2023"] for query in search_post: vehicle_result = Vehicle.objects.filter( Q(title__icontains=query) | Q(details__icontains=query) | Q(year__icontains=query) | Q(notes__icontains=query) ) print('vehicle_result: %s' % vehicle_result) The issue I'm having is when the array has multiple items it's going through the for loop for each object and it's outputting each objects result. Only the last object result is retained if I call this variable elsewhere in the code. Example Output: vehicle_result: <QuerySet [<Vehicle: BMW>]> vehicle_result: <QuerySet [<Vehicle: Toyota>, <Vehicle: Mercedes>, <Vehicle: Honda>]> I want to store/combine them all into one variable - prevent losing all the results (right now only the last one is retained I guess because the variable is overwritten) How can I achieve? -
Cannot read properties of null (reading 'getPassword') error in vs code
I am getting this annoying error in vs code in the bottom right. It shows when i try to connect vs code with my local mysql server. Any solutions to this? This is the image I properly checked mysql and made sure that all the information of the database is correct in my project. -
how to render URL patterns in Django with multiple apps
I am trying to build a booking system, using Django. I have multiple apps and rendering the urls patterns has been difficult to understand and i have found the documentation little help when you have multiple apps. Here is my core app urls: urlpatterns = [ path('admin/', admin.site.urls), path('', include('review.urls'), name='review_urls'), path('accounts/', include('allauth.urls')), path('bookings/', include('booking.urls'), name='booking_urls'), ] The booking app urls: urlpatterns = [ path('booking', views.customer_booking, name='booking'), path('display_booking', views.display_booking, name='display_booking'), path('edit_booking/<booking_id>', views.edit_booking, name='edit_booking'), ] I am trying to render my edit_booking view: def edit_booking(request, booking_id): booking = get_object_or_404(Booking, id=booking_id) if request.method == "POST": form = BookingForm(request.POST, instance=booking) if form.is_valid(): form.save() return redirect('display_booking') form = BookingForm(instance=booking) context = { 'form': form } return render(request, 'edit_booking.html', context) where it is being called: <a href="/edit_booking/{{ booking.id }}"> <button>Edit</button></a> I tried adding bookings/ into my edit button but this is requesting a page with bookings/bookings/edit_booking/7. without it, it is just requesting the endpoint edit_booking/7 -
Docker-Compose - Frontend service cannot use endpoint from backend
Context I am currently working on a multi-container project involving react, django, and (eventually) several datastores all containerized and tied together with docker-compose. This is all developed within vscode devcontainers. The host operating system is Windows 11. Problem I can make requests to my Django API via the browser (and Django's API web interface). However I cannot make requesets to the API via the frontend service. Using the javascript fetch api, I am unable to make requests to any of the following localhost:8000 (NOTE: Many tut's say this should function just fine) 0.0.0.0:8000 (NOTE: This will at least throw a NS_ERROR_CONNECTION_REFUSED error, which is still unsolvable) host.docker.internal:8000 192.168.99.100:8000 172.24.0.2:8000 What I've Tried Proper CORS configuration with Django Ensuring all appropriate ports are exposed and forwarded within docker Re-implementing the entire project and basing it off of some other halfassed tutorial. TWICE. Details Backend Dockerfile FROM python:3.10-alpine ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY . . RUN apk add poetry && poetry install EXPOSE 8000 Frontend Dockerfile FROM node:lts-alpine WORKDIR /app COPY . . RUN yarn install EXPOSE 3000 CMD ["yarn", "start"] docker-compose.yml services: frontend: build: ./frontend ports: - "3000:3000" volumes: - ./frontend:/frontend depends_on: - backend backend: build: ./backend ports: - "8000:8000" volumes: … -
How to break a long line of html code into multiple lines as "\" will do in python and C/C++
Suppose that I have the following code, <p>aaa<a>bbb</a>ccc</p> the rendered web page will be like this However, when the text "aaa", "bbb", "ccc" becomes pretty long, I want to split this single line into multiple lines for readability, like <p> aaa <a> bbb </a> ccc </p> But the rendered web page will be like There are whitespaces between two blocks of text. How can I make these lines work as the single line mentioned before. In python or C/C++, I can simply use "\" to notify the consecutive lines should be treated as a single line. Is there a similar funtionality in html file? Besides, as I'm using django template system, I tried the django official tag "spaceless". According to django's doc, "spaceless" tag should remove the whitespace between html elements. But in this case, the whitespace between two blocks of text remains. I get pretty puzzled about this. Thanks for any help! I tried to ask chatgpt, github copilot and search on google. But I found no functionality in html that can make consecutive lines work as a single line. A similar functionality to "\" in python and C/C++ which inform compiler to treat consecutive lines as a single … -
Django Passkeys and NextJs
I would like to create an app based on Django and NextJS 13 that uses an authentication system using Passkeys. I have seen that there is a django package for passkeys but it seems not to work properly, or at least following the documentation it is not explained correctly with implement the system if you use an external framework like NextJS. I am therefore looking for a solution that will allow me to use passkeys as my login system. -
How to add permissions from URL path parameter to DRF ViewSet?
I have an app that uses url paths like the following: account/<ACCOUNT_PK/project/<PROJECT_PK>/ When using Django permissions, the permissions of the last parameter (in this case project) are checked, but also want to ensure permissions are checked for Account too. curl -s -u test:password \ -H 'content-type: application/json' \ -X POST -d '{"name": "new_project", "account": 3}' \ 127.0.0.1:8000/account/3/project/ In this example I need to check permissions for both the data given in the request, and the parameters in the URL. I have solved this by creating a valid_account method for the serializer class, and also a custom permission inherited from rest_framework.permissions.BasePermission, but it is very dependent on paths not changing. Is there an option that I'm missing or third party package that can do this? I have tried different permissions classes, or adding app.change_account to permissions_required in the ProjectViewSet, but only get errors. -
MultiValueDictKeyError at /register/ and it have model error
"I'm trying to retrieve details using the POST method, but I encountered an error with the method name. I have attached my code below, so please help me resolve it." and also not get any info in the database Internal Server Error: /register/ Traceback (most recent call last): File "J:\good\test\Lib\site-packages\django\utils\datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) ^^^^^^^^^^^^^^^^^^^^^^^^ KeyError: 'name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "J:\good\test\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\mainone\threeapp\views.py", line 22, in register name=request.POST['name'] ~~~~~~~~~~~~^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\datastructures.py", line 86, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'name' model.py name model also found an error from django.db import models # Create your models here. class user(models.Model): name = models.CharField(max_length=30) Email= models.EmailField(max_length=254) phone= models.IntegerField() account = models.CharField(max_length=10) message = models.CharField(max_length=300) At the same time MultiValueDictKeyError in the register function. views.py from django.shortcuts import render,redirect from django.contrib.auth.models import User # Create your views here. def index(request): return render(request,"index.html") def contact(request): return render(request,"contact.html") def ideagained(request): return render(request,"idea_gained.html") def idea(request): return render(request,"idea.html") def ouridea(request): return render(request,"our_idea.html") def aboutpage(request): return render(request,"aboutpage.html") def register(request): name=request.POST['name'] email=request.POST['email'] phone=request.POST['phone_number'] account=request.POST['account'] message=request.POST['message'] user=user.objects.create_useryou(name=name, … -
Getting type error while try to log in Django
After creating username and password cant login get this error. TypeError at /login BaseModelForm.init() got multiple values for argument 'data' This is views and forms code & Image is also attached. This is view.py code from .forms import CreateUserForm, LoginForm from django.contrib.auth.models import auth from django.contrib.auth import authenticate from django.contrib.auth.decorators import login_required # Home page def home(request): return render(request, "webapp/index.html") # Register def register(request): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): form.save() return redirect("login") context = {"form": form} return render(request, "webapp/register.html", context=context) # login def my_login(request): form = LoginForm() if request.method == "POST": form = LoginForm(request, data=request.POST) if form.is_valid(): username = request.POST.get('username') password = request.POST.get('password') # checking user authentication here user = authenticate(request , username=username, password=password) if user is not None: auth.log(request, user) return redirect("dashboard") context = {'form':form} return render(request, 'webapp/my-login.html' , context=context) ``` [![This is the error i get when try to log in][1]][1] [1]: https://i.stack.imgur.com/9WvJ8.png -
How to create new meeting in Zoom with Python
I'm facing difficulties while trying to programmatically create a Zoom meeting, despite thoroughly reading the official Zoom documentation, I'm still unsure about the correct steps to follow. I've attempted to make requests to Zoom's API and have also explored the PyZoom library, but I'm encountering issues in successfully creating a meeting through code. If you have experience with this library or have successfully created Zoom meetings programmatically, your insights and guidance would be greatly appreciated. -
django simple history customising Base Class
I would like to start tracking changes made to a model using django-simple-history. I have a big model but would only need to track the history of a couple fields. I could use the exclude_fields parameter, but as the model gets larger, I do not want to manually keep on adding items that need to be excluded. I would like the basemodel history returns to be only the selected fields (bonus if history is only saved when one of these two fields changes, but not required). I have the following big model where I need to start tracking 2 fields: class Organisation(models.Model): .... lots of other fields balance = models.DecimalField( max_digits=15, decimal_places=2, default=Decimal('0.00')) costs = models.DecimalField( max_digits=15, decimal_places=2, default=Decimal('0.00')) history = HistoricalRecords() # only want to save history on fields balance and costs # basemodel that needs to be saved by history class OrganisationHistoryTrackedFields(models.Model): balance = models.DecimalField( max_digits=15, decimal_places=2, default=Decimal('0.00')) costs = models.DecimalField( max_digits=15, decimal_places=2, default=Decimal('0.00')) -
Changing django model structure produces 1054 unkown column error
I am trying to change the model structure (column names) of an existing Django app that was already working and had a database. Original Files: The original model.py file was: from django.db import models from django.core.validators import MinLengthValidator class Breed(models.Model): name = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Breed must be greater than 1 character")] ) def __str__(self): return self.name class Cat(models.Model): nickname = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Nickname must be greater than 1 character")] ) weight = models.FloatField() food = models.CharField(max_length=300) breed = models.ForeignKey('Breed', on_delete=models.CASCADE, null=False) def __str__(self): return self.nickname and the original /templates/cats/cat_list.html file was: {% extends "base_bootstrap.html" %} {% block content %} <h1>Cat List</h1> {% if cat_list %} <ul> {% for cat in cat_list %} <li> {{ cat.nickname }} ({{ cat.breed }}) (<a href="{% url 'cats:cat_update' cat.id %}">Update</a> | <a href="{% url 'cats:cat_delete' cat.id %}">Delete</a>) <br/> {{ cat.age }} ({{ cat.colour }} colour) </li> {% endfor %} </ul> {% else %} <p>There are no cats in the library.</p> {% endif %} <p> {% if breed_count > 0 %} <a href="{% url 'cats:cat_create' %}">Add a cat</a> {% else %} Please add a breed before you add a cat. {% endif %} </p> <p> <a href="{% url 'cats:breed_list' %}">View breeds</a> ({{ breed_count }}) … -
Django display different column from ForeignKey conditionally
I am implementing translation in my Django project. Last thing left for translation is translating category name, which is different model connected by foreign key. My models: class Category(models.Model): name = models.CharField(max_length=200) name_pl = models.CharField(max_length=200, default='none') slug = models.SlugField() def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Meta: verbose_name_plural = "Categories" class Note(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='note', null=True) title = models.CharField(max_length=200) note_text = models.TextField() add_date = models.DateTimeField('added date', auto_now_add=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=7) edit_dates = ArrayField( models.DateTimeField('edit dates', blank=True, null=True), default=list, ) members = ArrayField( models.CharField(max_length=200) ) allow_edits = models.BooleanField(default=True) def __str__(self): return self.title In Category model is field name, which is an english name of category and field name_pl - polish name of category. My form: class AddNewNote(forms.ModelForm): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={ 'multiple': True, 'style': 'font-size: 22px;'} ), required=False) class Meta: model = Note fields = ['title', 'note_text', 'category', ] widgets = { 'category': forms.Select(attrs={'style': 'font-size: 22px;'}), 'title': forms.TextInput(attrs={'style': 'font-size: 22px;'}), 'note_text': forms.Textarea(attrs={'style': 'font-size: 22px;'}), } def __init__(self, *args, **kwargs): super(AddNewNote, self).__init__(*args, **kwargs) self.fields['file_field'].label = _("Files") self.fields['title'].label = _("Title") self.fields['note_text'].label = _("Note text") self.fields['category'].label = _("Category") I am translating form labels using gettext_lazy, but I have no idea how to use … -
non_field_errors: ["State could not be found in server-side session data."] Status Code: 400 Bad Request
I deployed my django rest framework app on Railway and the frontend is deployed on vercel. For authentication I'm using djoser with social-auth-app-django. I'm getting above error when I make post request to /auth/o/google-oauth2/?state=''..."&code=''..." to generate tokens after getting state and code from google authorization url. But the same code work in my local dev environment perfectly fine. How can I fix this issue? -
How to use Subquery as datetime object in django
I am trying to use Subquery as a datetime object to compare with another datetime object from the model but it can't be possible because obviously the types are different .... I want to know how django treats Subqueries and how can i extract it to a valid form like int, string or datetime I am trying to use Subqueries inside a Case statement -
how can i show data using Veiw.py file
data enter in database but not showing on the Django website following error occur in view.py file File "C:\Users\usman\Downloads\OnlineCrime_ReportingSystem\firereport\views.py", line 5, in from .models import * Import Error: attempted relative import with no known parent package to solve this error I try a lot setting.py configuration urls.py the error are not solved overall project is working accurate but the data which is store on database not showing on website -
Accessing MySQL database with Django
Apologies in advance if this type of question already exists with a solution. I have been trying to get this solved for about 2 weeks now. So I had a Django project, which initially used the default Django database : SQLite3. I was able to access that database using /admin with the localhost, with 'admin' as password and username. I shifted the database to MySQL and everything was transferred properly, but I am not sure how to access the data using the /admin now. What should I enter in the username and password section? I have tried every possible combination with 'admin', database name, username, hostname and password which is provided in the settings.py when you change database. For reference, this is what the database section of my settings.py looks like DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'project', 'USER': 'root', 'PASSWORD': 'mysql-password', 'HOST': 'localhost', 'PORT': '3306', } } -
" Registration Sucessful" message is not showing in Django
Working on a Project"https://github.com/GargAnsh/donor_finder" wher i am having a "donor_add_form.html" which is having a donor registration form. While saving the form it's not displaying " regitration done succesfully " though entryn are succesfully hapening in data base and page redirecting to "Donor_finder.html " also I tried all the step, now need support to fix the problem. I also need help to expend the code further to add few feature. -
Can we create Attendance application inside Ms teams?
How to develop an attendence management application inside Microsoft teams app using python. My manager asked me to refer Microsoft SDK and its graph api. I have developed applications in django rest APIs but this is new for me. Dont know how to start and how to build this. How to use db for this and integrate here. Can anybody help me out -
Django rest auth - Custom validation error is not being caught
I am trying to overwrite the RegisterSerializer class provided by dj-rest-auth. I am running into an issue, which I believe is due to how I am trying to extend the ValidationError class I have overwritten the is_valid method as so: def is_valid(self, raise_exception=False): try: # we first replace password1 and password2 in initial_data (by default, dj-rest-auth # expects these fields -- our API just asks for 'password', and we rely on frontend # for password1=password2 verification) if "password" not in self.initial_data: raise CustomValidationError( GenericAPIErrorCodes.MALFORMED_REQUEST, "Password field is required" ) # Set "password1" and "password2" to the value of "password" self.initial_data["password1"] = self.initial_data["password"] self.initial_data["password2"] = self.initial_data["password"] output = super().is_valid(raise_exception=raise_exception) return output except CustomValidationError as exc: raise exc # furthering the error up the chain except DjangoCoreValidationError as exc: raise CustomValidationError( code=GenericAPIErrorCodes.MALFORMED_REQUEST.value, detail=exc.message ) except Exception as exc: print(exc) raise CustomValidationError( code=GenericAPIErrorCodes.MALFORMED_REQUEST.value, detail="" ) The error is getting thrown from line "output = super().is_valid(...)", which eventually ends up calling: def clean_password(self, password, user=None): # We catch errors coming out of clean password function and replace them with our own try: print("cleaning pass!") super().clean_password(password, user=user) print("cleaned!") except Exception as e: print("yes!") raise CustomValidationError( code=AuthErrorCodes.INVALID_PASSWORD.value, detail="Passwords must be at least 6 characters long, avoid … -
Problems with Django Websockets
I followed a Django Websockets tutorial in which I created a chatroom website. It didn't work so I doubble checked the code and I did everything the same as in the tutorial. I decided to clone the repository and check what is the problem with my code. I realized that the websockets didn't work with the downloaded project as well. Is there something wrong with the code or my computer? Link to the Tutorial: https://www.youtube.com/watch?v=jsxFEONN_yo Link to the repo: https://github.com/veryacademy/YT-Django-Project-Chatroom-Getting-Started.git I created a virtual env and installed django and channels. The only change I made is in the settings.py file where I replaced CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [os.environ['REDIS_URL']], }, }, } CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": os.environ['REDIS_URL'], "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" } } } With: CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } -
Celery Task received but not executing in Django project hosted on DigitalOcean
I have a Django project set up with Celery, hosted on a DigitalOcean droplet running Ubuntu 22.04. I'm running into a peculiar issue where a task is received by the Celery worker but doesn't seem to execute it. Here's the task that I am trying to run (provided by django-cookiecutter): from django.contrib.auth import get_user_model from config import celery_app User = get_user_model() @celery_app.task() def get_users_count(): return User.objects.count() I'm running the worker with the following command: celery -A config.celery_app worker --loglevel=DEBUG --without-gossip --without-mingle --without-heartbeat -Ofair --pool=solo I'm executing the task manually via django shell: get_users_count.delay() <AsyncResult: 821982b7-f256-462b-869c-e415da168c3f> The worker logs show that it received the task, but not that it's executed: [2023-10-06 23:57:25,568: INFO/MainProcess] Task myapp.users.tasks.get_users_count[821982b7-f256-462b-869c-e415da168c3f] received The task appears in Redis: 127.0.0.1:6379> keys * 1) "_kombu.binding.celery.pidbox" 2) "celery-task-meta-821982b7-f256-462b-869c-e415da168c3f" 3) "_kombu.binding.celery" When I query the task state and result manually, it shows that the task actually succeeded: >>> res = AsyncResult("821982b7-f256-462b-869c-e415da168c3f") >>> print("Task State: ", res.state) Task State: SUCCESS >>> print("Task Result: ", res.result) Task Result: 2 Despite the AsyncResult showing SUCCESS, there's no indication in the worker logs that the task was executed. What could be going wrong here? Any guidance would be greatly appreciated. The only thing that's really different … -
Django select the account from the account tree displays all the account details
I want when I select the account from the account tree using the checkbox it displays all the account details on the other side so I can add or edit an account later. What makes it difficult for me is that it relies on a tree system Please Help html {%load static%} <!DOCTYPE html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Daleel</title> <link rel="shortcut icon" href="{% static 'image/daleel.ico'%}" > <!-- Google Font: Source Sans Pro --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback"> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="{% static 'plugins/fontawesome-free/css/all.css'%}"> <!-- Bootstrap 5 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link href="https://unpkg.com/gijgo@1.9.14/css/gijgo.min.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="{% static 'css/acc.css'%}"> </head> <body> <h3 class="title">Accounts Tree</h3> <hr> <form method="POST"> {% csrf_token %} <div class='up'> <div class='acc'> <br> <div class="d-flex" role="search"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-secondary" type="submit">Search</button> </div> <br> {% for mainacc in mainaccs %} <ul class="tree" id="tree"> <li> <details > <summary class="mainacc" > <input class="form-check-input" type="radio" name="acc1" id="{{ aacc.acc_id1 }}" value="{{ mainacc.acc_id1 }}" style="margin-top:10px">&nbsp;&nbsp;{{ mainacc.acc_id1 }} ====>> {{ mainacc.E_name1 }}</summary> <ul> {% for aacc in mainacc.aacc_set.all %} <li> <details> <summary class="aacc"><input class="form-check-input" type="radio" name="acc2" id="{{ aacc.acc_id2 }}" value="{{ aacc.acc_id2 }}" style="margin-top:10px">&nbsp;&nbsp; {{ aacc.acc_id2 …