Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django customized authentication Session bug
I'm working on a Django project using a customized authentication build by me, I run into a problem where users can bypass my login and get into the home page by simply typing the URL like this: "127.0.0.1/account/Adam" , "127.0.0.1/account/Bob" , "127.0.0.1/account/Alice" , those people are not registered in the database and yet they receive "welcome Adam", "welcome Bob", "Welcome Alice" I have been trying different methods from adding a global variable called Auth = False, and once a user is found in the database and the password is matched Auth will receive True, this kinda solved my problem but not as expected because once that variable becomes Auth = True example: if bob is registred in database and login has been successfully made, with same session Bob can type those urls and manipulating the last url parameter and get Welcome sam, Welcom Alfred.... from django.http import HttpResponse from django.contrib import messages from django.contrib.auth.models import auth from users.models import Composter from django.core.exceptions import ObjectDoesNotExist class MyView(): Vuser = None # Create your views here. def home(request): return render(request, 'users/home.html') #def compost_supplier_register(request): return render(request, 'users/compost_supplier_register.html') def composter_register(request): if request.method == 'POST': #extracting form data from a POST request and assigning it … -
How to use the address of the site inside the url tag django
I want to know if it is possible to use such an address?? {% url request.get_full_path page %} For example, pages like product list and search are on the same page and have separate links for the paginator -
FieldError at /store/submit_review/1/ Unsupported lookup 'id' for DateTimeField or join on the field not permitted
views.py def submit_review(request, product_id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': try: reviews = ReviewRating.objects.get( user__id = request.user.id, product__id=product_id) form = ReviewForm(request.POST, instance=reviews) form.save() messages.success(request, 'Thank you ! your review has been updated.') return redirect(url) except ReviewRating.DoesNotExist: form = ReviewForm(request.POST) if form.is_valid(): data = ReviewRating() data.subject = form.changed_data['subject'] data.rating = form.changed_data['rating'] data.review = form.changed_data['review'] data.ip = request.META.get('REMOTE_ADDR') #REMOTE_ADDR will stor the ip address data.product_id = product_id data.user_id = request.user.id data.save() messages.success(request, 'Thank you! Your review has been submitted.') return redirect(url) error I got: FieldError at /store/submit_review/1/ Unsupported lookup 'id' for DateTimeField or join on the field not permitted. Request Method: POST Request URL: http://127.0.0.1:8000/store/submit_review/1/ Django Version: 3.1 Exception Type: FieldError Exception Value: Unsupported lookup 'id' for DateTimeField or join on the field not permitted. -
How to use a relative path for Django FileStorage location in migrations?
I am defining a Model containing a FileField and cannot save the Files this FileField should contain in the media folder for unrelated reasons. Therefore I need to define a FileStorage that saves into a different Path. When defining said FileStorage in my model and passing it the DJANGO_ROOT variable from my django settings to build my location path, this gets resolved into a system specific path once I generate migrations for my models. Because the path is now specific to my development directories, I cannot apply the generated migration file on all of the production servers and generating migrations on all of the production servers is obviously not an option. I have also tried editing the path inside the auto generated migration itself, making it dependent on the django settings in there. Sadly, the manage.py migrate command tells me that it wants to generate new migrations for that model. How can I pass a relative path to my FileStorage location, allowing me to generate migrations for my production servers? My model: class ModelWithFile(models.Model): file = models.FileField( storage=FileSystemStorage(location=os.path.join(settings.DJANGO_ROOT, "folder_name"), verbose_name=_("FileObject"), ) Auto generated migration: from django.db import migrations, models from django.conf import settings import django.core.files.storage class Migration(migrations.Migration): dependencies = [ … -
django, path parameter in form don't work
My path looks like so: path('edit/<str:entry_name>/', views.edit, name='edit'). I want to access this path through a form like so: <form action="{% url 'edit' entry_name=entry_title %}" method="get"> {% csrf_token %} <input type="hidden" name="title" value="{{ entry_title }}"> <input type="hidden" name="content" value="{{ entry_content }}"> <input type="submit" value="Edit"> </form> But then I get this error: Reverse for 'edit' with keyword arguments '{'entry_name': ''}' not found. 1 pattern(s) tried: ['edit/(?P<entry_name>[^/]+)/\\Z']. It seems like entry_name is empty, but I use the entry_name parameter elsewhere on the page and it works fine. {% block title %} {{ entry_title }} {% endblock title %} is not empty, since I can see the titel on the tab-title. -
How to convert field values of a model into field names of a new one (model) in DJANGO 4?
I'm building models for a project in DJANGO 4, but I got stuck when it came to CONVERTING FIELD VALUES OF AN EXISTING MODEL INTO THE FIELD NAMES OF A NEW ONE (MODEL). As may be seen from the image I do attach, I have MODEL A with 'fieldName_3'. I'd appreciate a help to convert the values of this field into the field names of the MODEL B.Descriptive Image My advancing thanks! from django.db import models CHOICES = (('option1','option1'),('option2','option2')) class Model_A(models.Model): fieldName_1 = models.CharField(max_length=50) fieldName_2 = models.CharField(max_length=20) fieldName_3 = models.CharField(max_length=3) class Model_B(models.Model): def values_from_fildName3(): values = Model_A.fieldName_3 for value in values: value = models.CharField(max_length=4, choices=CHOICES) yield value With the code above I get the error "TypeError: 'DeferredAttribute' object is not iterable" -
Get form-data for Django tests
I would like to test a Django form, without spelling out myself all the POSTed data that would normally go into it. In a real application, this data would be provided by the browser, based on the form as rendered (as HTML) by Django. How do I get the data without going through the browser? form0 = MyForm(instance=obj) # form which would be shown in normal usage data = the_magic_function(form0) # data which would be posted if user just pressed submit right away # potentially manipulate some parts of this data to make the test interesting form1 = MyForm(instance=obj, data=data) # actual tests are on form1 -
Didnt print anything in response while using asnycio
So i use asnycio libruary to send response while task running in the backend but the response is being sent but display nothing in conole in backend. Here is my code: def http_call_sync(): for num in range(1, 6): sleep(1) print(num) r = httpx.get("https://httpbin.org/") print(r) async def async_view(request): loop = asyncio.get_event_loop() loop.create_task(http_call_async()) return HttpResponse('Non-blocking HTTP request') I need output like 1 2 3 4 5 in console -
Django Session across apps
request.COOKIES.get("myapp_sessionid") how above code line can be used to get session values across apps? I want to share session values across django apps in same django project. But session values get cleared in new second app. -
Django inline formset render by order
I Use Django 4.0.6 and Python 3.10. I have a Form with nested inline formset. The inline formset is orderable (can_order=True). The 'ORDER' value of the form will be set to an instance field "index". I use Javascript to order those forms in the template. When I submit the whole form and the form is not valid then the forms are not rendered by the 'ORDER'/'index' attribute. They will be rendered in the order they were created. To solve this I overwrite the __iter__ function of the formset to "Yield the forms in the order they should be rendered." (see django docs - BaseFormSet). My __iter__ function: def __iter__(self): """Yield the forms in the order they should be rendered.""" if self.is_bound: return iter(sorted(self.forms, key=lambda x: x.instance.index, reverse=False)) #return iter(sorted(self.forms, key=lambda x: x.cleaned_data['ORDER'], reverse=False)) else: return iter(self.forms) When I submit the form I get the following errors according to the values that I want to access (cleaned_data or instance). Error when accessing order through cleaned_data: FormXY has not attribute 'cleaned_data' Error when accessing index through instance: '<' not supported between instances of 'NoneType' and 'NoneType' I set a breakpoint in the __iter__ function to see whats the problem, but there is … -
How to feel test DB in Django with models with ManyToMnayFields?
I want to test speed of my project, so I need to feel my DB with test data. I have a model with lots of ManyToManyFields (later I will create more models): class Deciduous(PlantBasicCharacteristics): soil_type = models.ManyToManyField(SoilType) soil_moisture = models.ManyToManyField(SoilMoisture) soil_fertility = models.ManyToManyField(SoilFertility) soil_ph = models.ManyToManyField(SoilPh) And I am trying to create utility to feel DB with test data: from random import randint from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.db.models.fields import CharField, DecimalField from django.db.models.fields.related import ManyToManyField from django.shortcuts import get_object_or_404 from plants.models import Deciduous from plants.web_page_filter_fields import get_plant_class_fields PLANT_CLASSES = [Deciduous, ] TEST_DATA_AMOUNT = 3 class Command(BaseCommand): def handle(self, *args, **options): for plant_class in PLANT_CLASSES: fields_and_names = get_plant_class_fields(plant_class) data = [] for _ in range(TEST_DATA_AMOUNT): data.append(self.create_data(fields_and_names)) print(data) plant_class.objects.bulk_create([ plant_class(**values) for values in data ]) def create_data(self, fields_and_names): data = {} for field_name, field_model in fields_and_names.items(): if ('ptr' not in field_name and 'synonym' not in field_name and field_name != 'id'): if isinstance(field_model, CharField): data[field_name] = self.get_string_random() elif isinstance(field_model, DecimalField): data[field_name] = self.get_number_random() elif isinstance(field_model, ManyToManyField): data[field_name] = [self.get_choice_random(field_model)] return data def get_string_random(self): letters = [chr(randint(97, 122)) for _ in range(randint(5, 20))] return ''.join(letters).capitalize() def get_number_random(self): return randint(10, 15000) / 100 def get_choice_random(self, model): field_model = model.related_model field_choices … -
ImproperlyConfigured at /api/v1/auth/registration/account-email-verification-sent/
I'm getting this error after updating dj-rest-auth package to 3.0.0 from 1.1.0 main urls.py [![from allauth.account.views import confirm_email from dj_rest_auth.registration.views import VerifyEmailView from dj_rest_auth.views import PasswordResetConfirmView from django.urls import include, path, re_path][1]][1] path("api/v1/auth/", include("dj_rest_auth.urls")), path( "api/v1/auth/registration/", include("dj_rest_auth.registration.urls") ), path("api/v1/auth/registration/verify-email/", VerifyEmailView.as_view()), path( "api/v1/auth/password/reset/confirm/<slug:uidb64>/<slug:token>/", PasswordResetConfirmView.as_view(), name="password_reset_confirm", ), re_path( r"^api/v1/auth/accounts-rest/registration/account-confirm-email/(?P<key>.+)/$", confirm_email, name="account_confirm_email", ), -
How to insert count() value when using Django to develop Web front end
I'm developing a web visual board using Django. Here is the part of html that I want to insert database's values into. <tbody> {% for obj in data_list %} <tr> <th>{{ obj.id }}</th> <th>{{ obj.major }}</th> <th>{{ obj.name }}</th> <th>{{ obj.age }}</th> </tr> {% endfor %} </tbody> As you can see, this can help me to insert data: id, major, name and age. But now I want to insert values that use count() function in MySQL, which is fuzzy lookup: SELECT COUNT(Issue_date) AS NumberOfProducts FROM first_project.itsec_china WHERE Issue_date like '2022%'; Basically, I want to insert the number of those items issued in year 2022. How can I change my code, for example, this part: {{ obj.age }} I'm trying to find someone have the knowledge to give me the answer or a place to study about it. Thank you in advance. -
Django Rest Framework Testing
I have a LoginSerializer that has the block of code as below def validate(self, attrs): username = attrs.get('username', '') password = attrs.get('password', '') user = auth.authenticate(username=username, password=password) if user: if user.is_active is False: raise AuthenticationFailed( 'Account is disabled, contact admin') if not user.is_verified: raise AuthenticationFailed('Email is not verified') return { 'username': user.username, 'firstname': user.firstname, 'lastname': user.lastname, 'role': user.role, 'tokens': user.tokens } else: raise AuthenticationFailed('Invalid credentials, try again') and a test case as below; class UserLoginTest(BaseTest): def test_inactive_user_can_login(self): self.client.post( self.register_public, data=valid_user, format='json') user = User.objects.get(username=valid_user['username']) user.is_verified = True user.is_active = False user.save() response = self.client.post( self.login_url, valid_login_user, format='json') print(response.data) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) When I run the test with is_active = False I get Invalid credentials, try again. Why is it that when is_active=False the user is not found even though the user is there? Same with when I try to login from swagger. -
Why is VS Code loading all my previous logs when I run docker-compose up for django rest framework?
I run docker-compose up I don't know why but all the previous logs that took alot of time, generate again. which is why it takes 5 minutes for the server to be up and running. To avoid that previously I used to quit the server, clear the window, remove the terminal and added new terminal and it solved the problem and started the server from fresh. but now it is not working too. kindly help I am new to django and docker. -
Bootstrap striped table format lost when updating table with fetch
I am using Django and I have a table which is formatted using bootstrap. The class is class="table table-striped". The table initially looks good. It has a delete button which allows users to delete a row. When clicked the data is deleted from the Django model and the table rows are removed and repopulated using fetch. Everything works well but the striped formatting is lost. The bootstrap formatting is still working to some degree and the table is the same size/shape but the background colour of alternating striped rows is lost. I've tried removing and re-adding the class with the javascript but it doesn't work. Any suggestions would be great. HTML {% if pairs %} <table class="table table-striped" id="pairs_table"> <thead> <tr> <th scope="col">Primer</th> <th scope="col">Product(bp)</th> <th scope="col"></th> </tr> </thead> <tbody> {% for pair in pairs %} <tr> {% if pair.forward.pk == primer.pk %} <td> <a href="{% url 'primer' pair.reverse.id %}">{{ pair.reverse }}</a> </td> <td>{{ pair.product }}</td> <td id="delete_pairing"> <button type="button" class="btn btn-warning" onclick="delete_pair('{{primer.id}}','{{pair.reverse.id}}')"><i class="bi bi-trash3"></i></button> </td> {% else %} <td> <a href="{% url 'primer' pair.forward.id %}">{{ pair.forward }}</a> </td> <td>{{ pair.product }}</td> <td id="delete_pairing"> <button type="button" class="btn btn-warning" onclick="delete_pair('{{primer.id}}','{{pair.forward.id}}')"><i class="bi bi-trash3"></i></button> </td> {% endif %} </tr> {% endfor %} JAVASCRIPT … -
How to run threads with django
How to run thread with Django how to send data inside views file from django.shortcuts import render from django.http.response import HttpResponse from datetime import datetime from .pnet import Worker1 global value value = False def home(request): global value if value == False: Worker1.start() print(a) value = True today = datetime.today() return render(request, "home.html")` pnet.py import threading class Worker1(threading.Thread): def run(self): a = 10` -
Not Working the Migrationfrom Django to Postgres and MongoDb
I am a newcomer to MongoDB and currently attempting to establish a connection between MongoDB and Django. However, I have been successful in establishing a connection with Postgres, but I am facing difficulties in connecting to MongoDB. Although there are no errors occurring during the migration process, I am not seeing any migration on the MongoDB side. Setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'base_app.apps.BaseAppConfig', 'document_app.apps.DocumentAppConfig', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('POSTGRES_HOST'), 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'PORT': os.environ.get('POSTGRES_PORT'), }, "mongodb": { "ENGINE": "djongo", "NAME": os.environ.get('MONGO_DB_NAME'), "CLIENT": { "host": os.environ.get('MONGO_DB_HOST'), "port": int(os.environ.get('MONGO_DB_PORT')), # "username": os.environ.get('MONGO_DB_USERNAME'), # "password": os.environ.get('MONGO_DB_PASSWORD'), }, 'TEST': { 'MIRROR': 'default', }, } } DATABASE_ROUTERS = ['base_app.utils.routers.MyRouter', 'document_app.utils.routers.MyRouter'] base_app/model.py class PostgresModel(models.Model): # fields for Postgres database here title = models.CharField(max_length=100) content = models.TextField() class Meta: db_table = 'postgres_model' app_label = 'base_app' managed = True abstract = False document_app\models.py from djongo import models as djmodels from django.db import models class MongoDBModel(djmodels.Model): # fields for MongoDB database here name = models.CharField(max_length=100) age = models.IntegerField() address = models.CharField(max_length=200) class Meta: db_table = 'mongodb_model' app_label = 'document_app' managed = True abstract = False class MongoDBDocument(djmodels.Model): # fields for MongoDB database here name = … -
django - mariadb 1146 error after change database
used pytest-django==3.5.0 aws rds-mariadb 10.6 To upgrade the version 10.3 to 10.6 of my mariaDB, I upgraded and switched the version of green using blue/green of aws rds. On the surface, both the table and the data seemed fine. But after the change, django throws error 1146. After changing the database, I thought it was a cache problem, so I tried changing the url route address, but it didn't work. I also tried running makemigrations and migrate in manage.py but it didn't work. Now, I think the django Model's meta doesn't seem to apply. Because my actual table name is alarminfo in lowercase but the error log says (1146, "Table 'db.AlarmInfo' doesn't exist") are indicated in uppercase. class AlarmInfo(models.Model): alarmUID = models.BigAutoField(db_column='AlarmUID', primary_key=True) # Field name made lowercase. userUID = models.BigIntegerField(db_column='UserUID') # Field name made lowercase. alarmType = models.IntegerField(db_column='AlarmType') # Field name made lowercase. content = models.TextField(db_column='Content') # Field name made lowercase. registerDate = models.DateTimeField(db_column='RegisterDate') # Field name made lowercase. class Meta: managed = False db_table = 'alarminfo' I'm assuming this might be the problem, but I haven't been able to find a solution. Is this something that has changed in mariadb 10.6 or the action I need to take … -
Trying to get the other user but keep getting the current user
I have this simple friendship model for users. I am trying to get the friends of the user that is currently logged in. Since friends means a relationship doesn't matter if you are user or friend I would like to get all the users that are not the current user. The friendship model: # WHEN A USER BECOMES FRIENDS WITH ANOTHER USER class Friendship(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE ) friend = models.ForeignKey( User, on_delete=models.CASCADE, related_name="friends" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: unique_together = ["user", "friend"] verbose_name = "friendship" verbose_name_plural = "friendships" ordering = ["created_at"] def __str__(self): return "{} is friends with {}".format(self.user, self.friend) def save(self, *args, **kwargs): if self.user == self.friend: return "Same person friendship should happen mentally" else: super().save(*args, **kwargs) The function I am using to get the friends: def get_friends(queryset, request, *args, **kwargs): id = kwargs['user'] user = User.objects.get(id=id) friends = [f.user for f in Friendship.objects.all().filter((Q(user=user) | Q(friend=user)))] return queryset.filter(user__in=friends) I keep getting the logged in user as friend instead of the other users that are not the logged in user. What am I doing wrong here please? -
How to Update file name in FileField after file is uploaded on s3 via presigned post URL in Django?
I have integrated django-storages in Django Project. for large file sizes, I have used a pre-signed URL to upload files from externally without taking a load on my server. by pre-signed URL, Files uploaded successfully in the s3 bucket AWS, after uploading the file in s3 I need to update the name of the file in FileField. -
How to change Log out icon in jazzmin django theme?
i have django project with jazzmin theme library i use, i've change icon for sidebar with "icons:{...}" and i want to change the user menu icons, the logout menu: what i know is, we can use this line: "usermenu_links" : {} but i don't quite understand how to pointing for the log out button, any idea? -
How to add multiple options to a feature in Django?
My last question for today. I created a filter to only show items with certain values. A list of social measures is displayed. There are two questions about having children and unemployment. We have or don't have children, and we are or aren't unemployed. The main problem is that the filter doesn't work correctly, due to the fact that I only add one option "no" to the entity. For example, we have a social measure "child allowance", and it's paid regardless of income. I created this measure with having children "yes" and unemployment "no". And if the user selects having children "yes" and unemployment "yes", then the page won't show this measure, although the person is entitled to it. Because only "no" was introduced into unemployment. How to enter "no" and "yes" at the same time when creating a measure? And for the site to show this measure regardless of the choice of unemployment. measure_list.html <div class="headtext"> <h3>Choose your life features</h3> </div> <form action="{% url 'filter' %}" method="get" name="filter"> <h3>Do you have children?</h3> <ul> {% for measure in view.get_children %} <li> <input type="checkbox" class="checked" name="children" value="{{ measure.children }}"> <span>{{ measure.children }}</span> </li> {% endfor %} </ul> <h3>Are you unemployed?</h3> <ul> … -
Add values to django database from an external python streamlit app
I have a streamlit app that runs machine learning on an image given by the user. I also implemented authentication using django along with a gallery type app that allows users to view stored images if logged in. I want to add the ability to automatically apend the image uploaded on my streamlit app to the database if the user is logged in. What would be the best way to do this? I tried importing my create view into the streamlit app and defining the variables manually. I also tried to import the model and work with that but I couldn't get either of them to work. I also shifted my streamlit app into the same directory as the django app to prevent PATH errors. -
all of my venv is suddenly unable to create process
it's showing Unable to create process using '"C:\Users\JUNG HAN\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe"' I dont know where PythonSoftwareFoundation folder was created from but it was installed today few hours ago I just found. What is this and why it suddenly created and my venv is referencing the python.exe file in that folder? I haven't tried anything yet ...................................................................................................