Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
missing 1 required positional argument django _id
I'm trying make cart for delivery site. I've got a lot of problems) there one of them: method remove() missing 1 argument: my view: def cart_remove(request, dish_id): cart = Cart(request) dish = get_object_or_404(Dish, id=dish_id) cart_remove(dish) return redirect('cart:cart_detail') My template: {% for item in cart%} {% with dish=item.dish %} <tr> <td> <a href="{{ dish.get_absolute_url }}"> <img src="{{ dish.picture.url }}" width="100" height="100"> </a> </td> <td>{{dish.name}}</td> <td>{{item.quantity}}</td> <td><a href="{% url 'cart:cart_remove' dish.id %}">Remove</a></td> <td class="num">$ {{item.price}} </td> <td class="num">$ {{item.total_price}} </td> </tr> {% endwith %} {% endfor %} my itter method in Cart class: def __iter__(self): dish_ids = self.cart.keys() dishes = Dish.objects.filter(id__in=dish_ids) for dish in dishes: self.cart[str(dish.id)]['dish'] = dish for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item My little error -
'MyApp' is not a registered namespace
I am trying to add a link from one page to another page. But it generating error of MyApp not registered while I have registered it in urls.py Here is my .html file: <body> <h1>Hello world </h1> <h1> <a href = " {% url 'MyApp: Variable' %} "> Variable Page</a> </h1> </body> Here is my urls.py(MyApp) file: apps_name = 'MyApp' urlpatterns = [ path('', views.simpleView, name = 'Example'), #domain.com\MyApp path('variable/', views.VariableView, name = 'Variable') Here is my urls.py(Mysite) file: urlpatterns = [ path('MyApp/', include('MyApp.urls')), path('admin/', admin.site.urls), and here is my error: NoReverseMatch at /MyApp/ 'MyApp' is not a registered namespace Request Method: GET Request URL: http://127.0.0.1:8000/MyApp/ Django Version: 3.2.14 Exception Type: NoReverseMatch Exception Value: 'MyApp' is not a registered namespace Exception Location: C:\Users\DELL\Desktop\DJango\venv\lib\site-packages\django\urls\base.py, line 82, in reverse Python Executable: C:\Users\DELL\Desktop\DJango\venv\Scripts\python.exe Python Version: 3.7.9 Python Path: ['C:\\Users\\DELL\\Desktop\\DJango\\MySite', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\python37.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0', 'C:\\Users\\DELL\\Desktop\\DJango\\venv', 'C:\\Users\\DELL\\Desktop\\DJango\\venv\\lib\\site-packages'] Server time: Sat, 30 Jul 2022 09:43:01 +0000 -
Why makemigrations in django doesn't work?
I wanted to insert into my database from an Excel file. So I created a model in my models.py file. models.py from django.db import models class Materiau(models.Model): designation = models.CharField(max_length=128) norme = models.CharField(max_length=128) temperature = models.CharField(max_length=128) epaisseur = models.CharField(max_length=128) symbole = models.CharField(max_length=128) rho = models.FloatField(default=0.0) E = models.FloatField(default=0.0) sigy = models.FloatField(default=0.0) Etan = models.FloatField(default=0.0) def __str__(self): return self.designation Then I created a Commands file : Path : my_app/management/commands/update_database.py from django.core.management.base import BaseCommand import pandas as pd from DataMat.models import Materiau from sqlalchemy import create_engine class Command(BaseCommand): def handle(self, *args, **options): df = pd.read_excel('dataframe.xlsx') engine = create_engine('sqlite:///db.sqlite3') df.to_sql(Materiau._meta.db_table, if_exists='replace', con=engine, index=True) Then when I run python manage.py update_database I can see the database being updated in my db.sqlite3 file. But when I run the makemigrations I get no changes detected and I can't see my database in the Django admin section. This is the error I get from Django : no such column: DataMat_materiau.id I don't understand because when I look into my database I can see an index but Django doesn't seem to recognize it. Also in my update_database.py file, I have this message Access to a protected member _meta of a class. Does anyone have an idea on how … -
Cant find the solution or mistake in jinja condition
When implementing the likes counter function, I encountered the fact that the condition for displaying different interface buttons does not work, depending on whether the user's "id" number is in the list of those who have already liked this post. HTML(fragment): {% for posts in current_page.object_list %} {% if user.is_authenticated %} <div class="line" style="display: flex; flex-direction: row; align-items: baseline"> {% if user.id in post.likes_list_id %} <div> <div style="color: green;"> it works </div> </div> {% else %} <div> <div style="color: red;"> not work </div> </div> {% endif %} </div> <div style="padding-left: 10px; color: orange;"> {{user.id}} {{post.likes_list_id}} {{post.likes_list_id.all}} </div> {% endif %} {% endfor %} views.py: def index(request): new_post = New_post_form() db_posts = Post.objects.all() # just for testing testing = Post.objects.get(id=2) foo = testing.likes_list_id() print(foo) posts_division = Paginator(db_posts, 10) requested_page = int(request.GET.get("requested_page", 1)) current_page = posts_division.page(requested_page) return render(request, "network/index.html", { "new_post": new_post, "current_page": current_page, }) model.py: class User(AbstractUser): pass class Post(models.Model): user_name = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, related_name="likes", blank=True) def likes_count(self): return self.likes.count() def likes_list_id(self): return self.likes.values_list('id', flat=True) class Meta: ordering = ["-timestamp"] def __str__(self): return f"{self.pk} - {self.user_name}" And I get the following result in the browser: [1]: https://i.stack.imgur.com/d9Jik.jpg Although the user number is … -
pre_save signal not firing on model create or edit
I've use pre_save signals in my django app quite often, including in the file that I'm trying to execute this code in. For some bizzaire reason, this presave signal does't fire on save of any HAddress (create or edit). Any thoughts on why this might not be firing? def assign_government_id(sender, instance, *args, **kwargs): print('hi you') pre_save.connect(assign_government_id, sender=HAddress) No hard errors or anything like that. It just doesn't seem to fire. Thanks! -
Comparing CSV and dictionary
I have a csv file with an entry named Registration Number which is unique. I have a dictionary that has keys as Registration Numbers and values as 'REPORTED' or 'NON-REPORTED'. I want to compare the Registration Number of csv with keys of dictionary and create new column in the csv named 'STATUS' having values as 'REPORTED' or 'NON-REPORTED' from the dictionary values. In djnago, how do I do that? -
Querying objects that is created minutes ago
So , We have a model called Status. Also we have a Datetimefield in it and we add the auto_now_add=True in the model. But the question is how can i query and find the objects that is created only two minutes ago ? -
pan_no field validation in django Template
Hi Everyone i am trying to validate pan_no filed using re in django template it is work, but when field is empty then still showing invalid pan no, i am trying to solve this issue if field is empty then do not check validation. pls help me out. models.py class Pan(models.Model): pan_no = models.CharField(max_length=10, null=True, blank=True) forms.py class PanForm(forms.Form): pan_no = forms.CharField(label='Pan Card Number', max_length=10, required=False) # validate pan_no if field is not none def clean_pan_no(self): pan_no = self.cleaned_data['pan_no'] if pan_no is not None: if not re.match(r'^[A-Z]{5}[0-9]{4}[A-Z]{1}$', pan_no): raise forms.ValidationError('Invalid PAN number.') return pan_no views.py def panview(request): if request.method == "POST": form=PanForm(request.POST) if form.is_valid(): pan_no=form.cleaned_data['pan_no'] form.save() messages.success(request, 'success') return redirect("driver_test") context{ 'form': form, } return render(request, 'pan_no.html',context=context) -
Django, custom 404 page redirects to 500 when Debug=False because Django cannot find exception parameter
When Debug = True django returns a Page not found (404) page which is totally fine But when I change Debug = False django return a Server Error (500) and the server shows these requests made: [30/Jul/2022 12:29:44] "GET /__reload__/events/ HTTP/1.1" 500 145 [30/Jul/2022 12:29:44] "GET /__reload__/events/ HTTP/1.1" 500 145 [30/Jul/2022 12:29:44] "GET /sdfs HTTP/1.1" 500 145 [30/Jul/2022 12:29:45] "GET /favicon.ico HTTP/1.1" 302 0 myproject main urls.py from django.conf.urls import handler404 handler404 = 'myproject.views.custom_page_not_found' please note here that hander404 is not found by django handler404 not found my views.py def custom_page_not_found(request, exception, template_name="errors/404.html"): return render(request, template_name, status=404) Please not here django cannot find the exception parameter exception parameter not found In previous community questions i could not find any question that points to the exception parameter not found issue. Please note that i am not using django templates {% %} in my 404.html file I think when django does not find the exception parameter it returns server error 500. -
What are the consequences of enforcing django foreign keys constraints at database level?
We'd like to add to an existing django app foreign keys implementation at the database level and we wonder what side effects we should expect from this. Some explanations more in details: We have a Django app, based on postgresql backend. Quite a lot of data, foreign keys, tables, etc. It used to be pure django based so we never even noticed that actually django does not implement foreign keys at database level but rather emulates it in the python stack. Now we try to integrate another project which ships SQL statements that we'd like to apply on the django database. So we receive statements like DELETE FROM foo WHERE id=bar. These statements can fail because of foreign keys which are implemented as ON DELETE RESTRICT (or maybe NO ACTION I don't remember right now) initially by django. To solve our issue, we though we could alter the foreign keys in postgres to mimic the django behavior (on delete cascade or set null mainly). This without changing anything in the django code. One comment by 'dirkgroten' found in Django does not honor ON DELETE CASCADE seems to suggest that this would not break the main application but, before we run … -
Django, form.is_valid() What does it check?
I do not use the form of models.form I received and stored each items of request.POST and request.FILES I will make my validation function. So I wonder what validation it does. (ex. input is empty, etc.) -
Django error: "ValueError: Unable to configure handler in 'database_file'
I have trouble with starting my backend in Django with the command python manage.py runserver I am using Anaconda for a virtual environment. Everything is working on Linux systems, but the two Windows developer get the following error: File "C:\Users\vu492\anaconda3\envs\sample_venv\lib\logging\config.py", line 570, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'database_file' There are similar questions already online. (ValueError: Unable to configure handler 'file': [Errno 2] No such file or directory:) Unlike my issue others get a directory in which something is missing. -
Integration problem Between reactnative app and Django server
When i run the server it shows me a message http://127.0.0.1:8000/. i want to do integration so i need to use this url in reactnative or anyother? -
change rows values in relate to another row
I'm working on leitner flashcards system the whole leitner sys is about BOXes order e.g box1, box2 ,box3 ,so when u solve a card in box1 it gets moved backward to box2 and vise versa .. now, what if I want to change the order of a box? or even delete it? wouldn't be better to change the other boxes orders? e.g [box1, box2, box3] => [box1, box2] so now you got the idea, here's how I implement it in django models: class Box(models.Model): name = models.CharField(max_length=100) order = models.IntegerField(blank=False) end_days = models.IntegerField(blank=False) end_hours = models.IntegerField(blank=False) end_minutes = models.IntegerField(blank=False, default=0) def __str__(self): return self.name now the big Question is , when some row('obj') deleted/order-changed how can I increment/decrement other rows ???! and if u have better idea than what I'm trying to do please share it . regards -
How to integrate dash app into react app?
I have built a dash app but to provide the full solution need to integrate with react app.is there a way to plug dash app within react framework -
Django ORM annotate Query
I have a subquery which returns an array. I want to perform certain operations to pick one data out of that array. I am not able to figure out how to do it. query_obj = VendorSecurity.objects.filter( valid_data=True ).values( "id", "rate", ).annotate( rating_val=Subquery( MySecurity.object.order_by("-date_of_credit_rating") .values("credit_rating_agency_code")[:1] ), ) ) I want to process my rating_val which will be an array. I tried pass the subquery result to a fun like: annotate( rating_val=myFun(Subquery( MySecurity.object.order_by("-date_of_credit_rating") .values("credit_rating_agency_code")[:1] )), ) ) But I am not able to access subquery value. I also tried passing later part of subquery to model manager but again I am not able to access subquery response. -
GitHub action couldn't find environment variable for Django
I was trying to use the environment variable in my Django application where I use the django-environ package with the .env file in my local machine. But I can't use the .env file in my GitHub action. I've configured action secret variables manually from my project settings. Here is my local machine code: import environ env = environ.Env() environ.Env.read_env() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env('POSTGRES_DB_NAME'), 'USER': env('POSTGRES_USER'), 'PASSWORD': env('POSTGRES_PASSWORD'), 'HOST': env('POSTGRES_HOST'), 'PORT': env('POSTGRES_PORT'), } } This code is working in my local environment but failed to load in GitHub actions. I have configured the same variables in GitHub actions too, but still, the application couldn't find the environment variable there in the GitHub action. django.yml name: Django CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.7, 3.8, 3.9] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Tests run: | python manage.py test The GitHub Action displays the following errors: Traceback (most recent call last): … -
I was trying to run my Django project visual code. I am getting the following error and I don't really know how to fix it
Traceback (most recent call last): File "c:\Users\PaVaN\Desktop\Run Project\Djungle-Online-Job-Portal-master\Djungle-Online-Job-Portal-master\dappx\views.py", line 3, in from django.contrib.auth.models import User, auth File "C:\Users\PaVaN\AppData\Local\Programs\Python\Python310\lib\site- packages\django\contrib\auth\models.py", line 3, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\PaVaN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\auth\base_user.py", line 49, in class AbstractBaseUser(models.Model): File "C:\Users\PaVaN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 127, in new app_config = apps.get_containing_app_config(module) File "C:\Users\PaVaN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "C:\Users\PaVaN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\PaVaN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\conf_init_.py", line 87, in getattr self._setup(name) File "C:\Users\PaVaN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\conf_init_.py", line 67, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. PS C:\Users\PaVaN\Desktop\Run Project\Djungle-Online-Job-Portal-master\Djungle-Online-Job-Portal-master> -
'user_model' referenced before assignment
I'm getting ---> UnboundLocalError at /signup local variable 'user_model' referenced before assignment The Error is occurring at* user_model = User.objects.get(username=username, id=user_model.id) *** In the Models.py File*** User gets created with pass and email in database, just not the profile models.py from django.db import models from django.contrib.auth import get_user_model # Create your models here. User = get_user_model() class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) profileImage = models.ImageField(upload_to='profile_images', default='blank-profile-picture.png') location = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from django.http import HttpResponse from .models import Profile def index(request): return render(request, 'index.html') def signUp(request): if request.method =='POST': username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] if password1 == password2: if User.objects.filter(email=email).exists(): messages.info(request, 'Email Already In Use!') return redirect('signup') elif User.objects.filter(username=username).exists(): messages.info(request, 'Username is Taken') return redirect('signup') else: user = User.objects.create_user(username=username, email=email, password=password1) user.save() user_model = User.objects.get(username=username, id=user_model.id) new_profile = Profile.objects.create(user=user_model, id_user=user.model.id) new_profile.save() return redirect('index') else: messages.info(request, 'Password Mismatch1') return redirect('signup') else: return render(request, 'signup.html') In the past I've just created my own user models rather than using the Django one. If you could include any ref documents in your reply … -
request.POST doesn't detect the name of input field
I would like to know which form was submitted in django, and I did this by using the name of the input field and detect it if it's also the name in request.POST. However, this doesn't seem to work. HTML <input type="file" name="coverPhoto" accept="image/*" id="id_coverPhoto"> <input type="file" name="profilePic" accept="image/*" id="id_profilePic"> views.py if request.method == 'POST': if 'profilePic' in request.POST: profile_photo_form = ProfileForm(request.POST, request.FILES, instance=user) if profile_photo_form.is_valid(): profile = profile_photo_form.save(commit=False) profile.save() return HttpResponseRedirect(reverse("my-profile")) if 'coverPhoto' in request.POST: cover_photo_form = CoverPhotoForm(request.POST, request.FILES, instance=user) if cover_photo_form.is_valid(): cover = cover_photo_form.save(commit=False) cover.save() return HttpResponseRedirect(reverse("my-profile")) -
How do I display specifically user home in django?
I want to implement to see specifically user home by other users. I did this method by def function. Is there a way to do it with a class function? How does urls.py set? views.py def Userrequest(request,user_id): user = CustomUser.objects.filter(id= user_id) return render(request, 'account/userpage.html', {'user': user}) urls.py path('<int:user_id>/', Userrequest, name= 'Userrequest'), -
django.contrib.sessions legacy? What should I use instead?
I'm following a tutorial to build a full-stack app using Django and Next.js. In the process of identifying users, the tutorial uses sessions. I have a basic understanding of sessions, so I decided to go along and learn about them. I eventually ran into a problem where one of my states wasn't updating with the response from the backend. I noticed that when sending a request to the backend, the session_key printed None. This is the code in views.py: class CreateRoomView(APIView): serializer_class = CreateRoomSerializer def post(self, request, format=None): print(self.request.session.session_key) if not self.request.session.exists(self.request.session.session_key): self.request.session.create() print(self.request.session.session_key) I scoured the web to find a solution. In the process, I learned a ton, and I kept reading information about the django.contrib.sessions app was legacy and would be a problem with new chrome versions. What should I make of this and what alternatives are there to sessions? I want to keep following the tutorial, but I'd like to apply the current best practices. What should I use instead of sessions? Thanks -
Django Rest Framework error: {'user': [ErrorDetail(string='This field is required.', code='required')]}
Unable to add a new customer to the database.. I made a class Named customer that has a one-to-one relationship with a class named User that is an AbstractUser I want to send the data through rest API so that I can create a new customer in the customer table and a new user that is One To One Related to the customer from the same view. User Model class User(AbstractUser): # Add additional fields here id = None email = models.EmailField(max_length=254, primary_key=True) name = models.CharField(max_length=100) password = models.CharField(max_length=100) is_patient = models.BooleanField(default=False) is_doctor = models.BooleanField(default=False) is_homesampler = models.BooleanField(default=False) is_pathologist = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) first_name = None last_name = None username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'password'] objects = CustomUserManager() def __str__(self): return self.email # Ensure that the password is hashed before saving it to the database def save(self, *args, **kwargs): self.password = make_password(self.password) super(User, self).save(*args, **kwargs) def has_perm(self, perm, obj=None): return self.is_superuser User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() # fields = (['id', 'username', 'email', 'name']) fields = '__all__' customer Model class customer(models.Model): user = models.OneToOneField( get_user_model(), on_delete=models.CASCADE, primary_key=True) real = models.BooleanField(default=False) … -
Create Multiple Instances From One Model Django
I'm trying to understand how to create multiple instances on creation of a model in django. Eventually I want to create more than one but I'm just trying to get the signal to work at the moment. This is what I have so far that isn't working. I want it to create a duplicate of this model. from datetime import datetime, timedelta import django from django.conf import settings from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class BudgetTransaction(models.Model): """ Individual transaction for Budget """ transaction_types = [ ('FI', 'Fixed Income'), ('FE', 'Fixed Expenses'), ('EC', 'Extra Cashflow'), ] frequencies = [ ('one', 'one off'), ('wk', 'weekly'), ('fort', 'fortnightly'), ('mon', 'monthly'), ('yr', 'yearly'), ('day', 'specific day'), ] today = datetime.today().strftime('%Y-%m-%d') owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, help_text="Owner of the item" ) transaction_type = models.CharField(max_length=40, choices=transaction_types, default=1) transaction_name = models.CharField(max_length=100, null=False) transaction_amount = models.IntegerField(null=False) next_date = models.DateField(null=False, default=today) frequency = models.CharField(max_length=20, choices=frequencies, default=1) complete = models.BooleanField(default=False) def __str__(self): return self.transaction_name class Meta: ordering = ['next_date'] @receiver(post_save, sender=BudgetTransaction) def create_forecasted(sender, instance, created, **kwargs): if created: today = datetime.today() this_month = today.month months_left = 12 - this_month if sender.frequency == "mon": BudgetTransaction.objects.create(owner=instance.owner) Thanks, Mitchell -
Find if a model object is assigned the last instance of another model
Working on fee management case in Django. Code is given below: class Student(models.Model): name = models.CharField("name",max_length=200) cell_no = models.CharField("cell No",max_length=200) address = models.CharField("address",max_length=500) class Meta: verbose_name_plural = "Student" def __str__(self): return self.name class FeeType(models.Model): name = models.CharField("fee Type", max_length=200) class Meta: verbose_name_plural = "Fee Type" def __str__(self): return self.name class CollectFee(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) feetype = models.ForeignKey(FeeType, on_delete=models.CASCADE) amountdue = models.PositiveIntegerField("amount Due") amountpaid = models.PositiveIntegerField("amount Paid") balance = models.PositiveIntegerField("Balance") class Meta: verbose_name_plural = "Collect Fee" def __str__(self): return self.student.name Fee Type is like Admission Fee, January Fee, February Fee etc. I want to get the list of all students who have not yet been assigned the last instance of the FeeType. For example, if in the CollectFee the student is assigned January, February month fee then Ok, if the student is not assigned March Fee, he should be included in the list. I could get the list of all students through: students= Student.objects.all() I can deal with simple filters but don't know how to apply the filter to solve the above mentioned problem.