Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when re-entering a Django web application
In a web application, I get a CSRF-Token error when logging back in after the user logs out. Of course, this problem only occurs when working with a smart phone. I put the {%CSRF-TOKEN%} tag in the designed login form, but this error occurs only on smartphones and after logging out and when logging in again. -
How to add text AFTER inputs in Django forms
I have a form which ideally would render like this: <label>Price: </label> <input type="number" />USD Visually it would be Price: |___________| USD I know that the label attribute of a form field can add text BEFORE an input, but I want to know if it's possible to add text AFTER an input. (1) I understand if I iterate over fields in the template, I would be able to achieve this with something like {{ field }} {% if field.name == "price" %} &nbsp;USD {% endif %} However I do not want to go this route if possible. (2) I already tried help_text, but it adds an extra <br /> tag between the input and the help text, and it does not render what I want. <label>Price: </label> <input type="number" /> <br /> <span>USD</span> Price: |___________| USD -
How to display only subscribed posts in Python
So there is 2 apps in Python, one is for blog posts and second is for user profile. I want to display on my HTML main page only user's subscribed posts. blog post models.py class News(models.Model): user = models.ForeignKey( User, related_name='user_news', on_delete=models.CASCADE ) title = models.CharField( max_length=250 ) description = RichTextField() def __str__(self) -> str: return self.title def save(self, *args, **kwargs): updating = self.pk is not None blog post views.py def home(request): blogs= Blog.objects.order_by('-created_date') users = User.objects.order_by('-date_joined') context = { "blogs": blogs, 'users': users, } return render(request, 'home.html', context) user profile models.py class User(AbstractUser): followers = models.ManyToManyField("Follow") def __str__(self): return self.username class Follow(models.Model): followed = models.ForeignKey( User, related_name='user_followers', on_delete=models.CASCADE ) followed_by = models.ForeignKey( User, related_name='user_follows', on_delete=models.CASCADE ) def __str__(self) -> str: return f"{self.followed_by.username} started following {self.followed.username}" user profile views.py def follow_or_unfollow_user(request, user_id): followed = get_object_or_404(User, id=user_id) followed_by = get_object_or_404(User, id=request.user.id) follow, created = Follow.objects.get_or_create( followed=followed, followed_by=followed_by ) if created: followed.followers.add(follow) else: followed.followers.remove(follow) follow.delete() return redirect("view_user_information", username=followed.username) what i did and it did not show posts of subscribed accounts <div class="swiper-wrapper"> {% for blog in account.user_blogs.all %} {% for blog in blogs|slice:"2" %} <div class="swiper-slide subscription-card" > <a href="{% url 'news_details' new.slug %}"> <div class="subscription-card__header"> <div> <h5>{{blog.user.first_name}} {{blog.user.last_name}}</h5> <span>{{blog.created_date}}</span> </div> </div> … -
pipenv install django=~3.1.0 command giving error
Installing django=~3.1.0... Resolving django=~3.1.0... Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pipenv/patched/pip/_vendor/packaging/requirements.py", line 102, in __init__ req = REQUIREMENT.parseString(requirement_string) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pipenv/patched/pip/_vendor/pyparsing/core.py", line 1141, in parse_string raise exc.with_traceback(None) pipenv.patched.pip._vendor.pyparsing.exceptions.ParseException: Expected string_end, found '=' (at char 6), (line:1, col:7) I am getting above error in command line of mac for pipenv install django=~3.1.0 -
I want to send and an otp with REST Framework
self._otp = str(randint(100000, 999999)) AttributeError: 'str' object has no attribute '_otp' [25/Feb/2023 14:04:01] "POST /login1/ HTTP/1.1" 500 101590 class OTPGenerator: def init(self, phone_number): self.phone_number = phone_number self._otp = None def generate_otp(self): self._otp = str(randint(100000, 999999)) redis_conf.set(name=self.phone_number, value=self._otp, ex=30) otp_code = redis_conf.get('phone_number') return otp_code def __str__(self): return self.otp def send(self): send_sms(phone_number=self.phone_number, otp=self.otp) def value(self): return redis_conf.get(self.phone_number) def is_valid(self, otp): if redis_conf.get(self.phone_number) == otp: redis_conf.delete(self.phone_number) return True return False -
Apache2 using incorrect Python location
I'm using Apache2 with mod_wsgi to server a Django app, and from the error log I can tell that for some reason it's trying to use the system python library instead of the venv one. I have PYTHONPATH set to the venv (venv/lib/python3.8) and mod-wsgi built specifically for Py3.8 so that shouldn't be an issue, and in my Virtual Host file I have python home set to the venv's folder. Error: [wsgi:error] from . import ccompiler [wsgi:error] File "/var/www/djangoenv/lib/python3.8/site-packages/numpy/distutils/ccompiler.py", line 8, in <module> [wsgi:error] from distutils import ccompiler [wsgi:error] ImportError: cannot import name 'ccompiler' from 'distutils' (/usr/lib/python3.8/distutils/__init__.py) It is referring to many packages in the correct location, being the virtual environment, but in the end it seems to defer to the system Python for some reason and fails. -
Removing objects from a queryset by ID optimal implementation
I have a queryset of 1000000 objects MyModel. All objects in queryset have an ID. I pass a list of ids to remove, for example: ids = ['1', '23', '117', ...] # len = 100000 Then, i need to delete objects in queryset with ids. What is the best way to do it? My variant: for id in ids: obj = MyModel.objects.filter(pk=id) obj.delete() I'm not sure about it, because it will make a 100000 queries to the database, maybe it makes sense to convert the queryset to a list, then filter it by id? On the other hand, if there are a million objects in the database, and only one needs to be deleted, this will create an inverse relationship. -
Django: AutoFields must set primary_key=True
After doing a python manage.py inspectdb on my already existing PostgreSQL database, and generating the models, I'm getting this error when I want to migrate: app.PatientHasPhysicallocalization.id: (fields.E100) AutoFields must set primary_key=True. Here is my generated model: class PatientHasPhysicallocalization(models.Model): id = models.BigAutoField() uid = models.CharField(max_length=155) patientid = models.ForeignKey(Patient, models.DO_NOTHING, db_column='patientid', primary_key=True) physicallocalizationid = models.ForeignKey('Physicallocalization', models.DO_NOTHING, db_column='physicallocalizationid') creationdate = models.DateField() creatorname = models.CharField(max_length=45) isactive = models.IntegerField() class Meta: managed = False db_table = 'patient_has_physicallocalization' unique_together = (('patientid', 'physicallocalizationid'),) I don't want to modify my database table -
htmx:targeterror in django project
My objective is to click on a list item (an asset) to load and update a form, that is right next to the list, using htmx in django, but I am getting HTMX:Targeterror.. I believe I have given the hx-target correctly, I cannot figure out why this problem appears.. Someone, please help.. I am getting htmx:targetError when using the below code.. can u help me figure out the issue? TEMPLATE {% for asset in portfolio.children %} <tr id="asset-{{ asset.id }}" > <td class="col-md-12 col-lg-12 node-style" hx-get="{% url 'portfolio:asset-update' asset.id %}" hx-target="#assetUpdate" hx-swap="outerHTML">&emsp;{{ asset.name }}</td> </tr> VIEWS.PY ASSET_UPDATE def asset_update(request, id): asset = Asset.objects.get(id=id) update_asset_form = AssetForm(request.POST or None, instance=asset) if update_asset_form.is_valid(): update_asset_form.save() context = { "update_asset_form": update_asset_form, "asset": asset, } return render(request, "portfolio/partials/02-asset-update.html", context) 02-ASSET-UPDATE.HTML {% load crispy_forms_filters %} {% load crispy_forms_tags %} <div id="assetUpdate"> <form method="post" class="form-group" novalidate> {% csrf_token %} {% crispy update_asset_form %} <button type="submit" class="bland-button-style" hx-post="{% url 'portfolio:asset-update' asset_id=asset.id %}" hx-target="#assetUpdate" hx-swap="outerHTML"> <i class="fa-solid fa-cloud-arrow-down fa-lg header-icon-style portfolio-save-icon"></i> </button> </form> </div> -
can't able to host api using my mobile hotspot ipaddress in python?
app = Flask(__name__) app.run(host='192.168.184.101',debug=True,port=8000) app.config.from_pyfile('customerdbconfigure.py') and also i have included this ip in settings.py ALLOWED_HOSTS = ['192.168.184.101'] also tried running python manage.py runserver 192.168.184.101:8000 in cmd But its showing like this if anyone know about this help me. -
Django 4: How to modify MultiPolygonField from nullable to not-null
I am trying to convert my MultiPolygonField field from this: multipolygon = MultiPolygonField(null=True) to this: multipolygon = MultiPolygonField(null=False) It looks simple, so I execute "makemigrations" and I get the usual message warning that the database needs something to populate existing rows (I confirmed that there is no row in my database with that field being null): Whether I choose option 1: Provide a one-off default now (will be set on all existing rows with a null value for this column) And set the following as default: 'SRID=3857;POINT(0.0 0.0)' or option 2: Ignore for now. Existing rows that contain NULL values will have to be handled manually, for example with a RunPython or RunSQL operation I get the following error when I execute "migrate": ValueError: Cannot alter field borders.Border.multipolygon into borders.Border.multipolygon - they do not properly define db_type (are you using a badly-written custom field?) I have been able to make that same change with other simpler field types without any issue. How to do this with MultiPolygonFields? I am using Django 4 and sqlite 3.31, in case that matters. -
Django - authenticate() returning None even if user exists in database and the credentials are correct
authenticate() returns None for credentials even if the user exists in the database and the credentials are correct. The function for registration, register(): def register(request): registered = False ctx = {} if request.method == 'POST': username = request.POST.get("username") full_name = request.POST.get("fullname") password = request.POST.get("password") email = request.POST.get("email") if len(User.objects.filter(username=username)) == 0: ctx["username_exists"] = False user_form = UserForm(data=request.POST) if user_form.is_valid(): user = User.objects.create_user(username, email, password) user.save() user_profile = UserProfile(user=user, full_name=full_name, email_id=email) user_profile.save() if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Your account was inactive.") else: print("Someone tried to login and failed.") print("They used username: {} and password: {}".format(username,password)) return HttpResponse("Invalid login details given") else: return HttpResponse("Contains @") else: ctx["username_exists"] = True return render(request,'main/register.html', ctx) elif request.method == "GET": form = User() ctx["form"] = form return render(request,'main/register.html', ctx) Looking at the admin, I can see the user exists. The following proves it exists in the database: >>> from django.contrib.auth.models import User >>> user = User.objects.get(username='<username>') >>> print(user) <username> This is what I'm doing - python3 manage.py shell >>> from django.contrib.auth import authenticate >>> user = authenticate(username="<username>", password="<password>") >>> print(user) None This hasn't ever occurred to me before and I don't know what to do. Help? -
how to create virtual environment files in the project's directory
i want the pipenv to create the pipfile and .lock file in my project directory . there are suggestions to export PIPENV_EVNV_IN_PROJECT=1 but i dont know where this variable is and how to export them. and can i simply copy the pipfiles to my projects directory ? -
Method Not Allowed (GET): /cart/add/1/
I have a problem with allow method GET in my project, I find out problem but nothing working. I try everything, but nothing working, the messages in my postman is {Method Not Allowed (GET): /cart/add/1/} Please help me how to solve this problem? cart/view @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) print('privet') if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True}) return render(request, 'cart/detail.html', {'cart': cart}) cart/url path('', cart_detail, name='cart_detail'), path('add/<int:product_id>/', cart_add, name='cart_add'), path('remove/<int:product_id>/', cart_remove, name='cart_remove') shop/view def product_detail(request, id, slug): product = Product.objects.filter(id=id, slug=slug) cart_product_form = CartAddProductForm() return render(request, 'web/catalog.html', {'product': product, 'cart_product_form': cart_product_form}) shop/detail.html <form action="{% url 'cart:cart_add' product.id %}" method="post"> {% csrf_token %} {{ cart_product_form.as_p }} {{ cart_product_form.non_field_errors }} <div class="Card-hover"> <a class="Card-btn" href="{% url 'cart:cart_add' product.id %}" type="submit" value='add to cart'><img src="{% static 'img/icons/card/cart.svg' %}" alt="cart.svg"/></a> </div> </form> -
how can i dynamically generate divs in my HTML template after a form submission, when working with django?
I am building a MCQs Bank using django, I have created all the front end files for my project, I have created django project, i have written some functons in views as well and created some of the models as well, I haven't created any forms yet, i have design a page which contains a button on which the user click and it redirects to a page where I created a form with the help of which user can enter the new course details which he want to add. Now on the redirected page when user done filling the details about course and click on add course I want to return the user to previous page where he can see all the courses he added and the new course must be display there as well. i want to make a div in which I want to place divs of all courses. I dont want to display anything in that div untill the user enter a new course, now when the user add a new course it should be display in that div of containing all course in the form of a div, now everytime the user enter a new course … -
Django form.save() does not update database
I have a Django User model with a background and a profile picture, what I want to do is give the user the ability to submit a new background photo/picture and have it saved to the database. The way I have done this is like this settings.html: {% extends 'main.html' %} {% block content %} <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="user-settings-save" value="submit"> </form> {% endblock content %} forms.py class UserProfileForm(ModelForm): class Meta: model = User fields = ['avatar', 'background'] models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(blank=True, default='', unique=True) password = models.CharField(max_length=50) name = models.CharField(max_length=255, default='', unique=True) avatar = models.ImageField(default='default.png', upload_to ='uploads/') background = models.ImageField(default='default.png', upload_to ='uploads/') score = models.IntegerField(default=1) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) register = models.CharField(max_length=255, default='') objects = CustomUserManager() USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['name'] def __str__(self): return self.name views.py def userSettings(request): form = UserProfileForm(instance=request.user) if request.method == 'POST': if 'user-settings-save' in request.POST: form = UserProfileForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): if backendActionAuth(request, 'user-settings-save', form): form.save() return redirect('user-profile', request.user.id) context = {'form': form} return render(request, 'base/settings.html', context) and urls.py urlpatterns = [ path('', views.home, name="home"), path('post/<str:pk>/', views.post, name="post"), path('browse/<str:tk>/', views.browse, name="browse"), path('register/', views.register_user, … -
How to randomize key objects in model form and successfully submit in Django
I am trying to save user response (choice) in my Django application out of a set of values in the source model. The user is expected to select one of the many choices presented on the form (as radio buttons). The source model looks like this: class Emotion(models.Model): emote_id = models.AutoField(primary_key=True, ...) emote_state_grp = models.ForeignKey(EmotGroup, ...) # Grouping of Emotion State emote_state = models.CharField(max_length=55, ...) The response/s will be saved in the following model: class EmoteStateResponse(models.Model): emote_state_test = models.AutoField(primary_key=True, ...) emote_state_selected = models.ForeignKey(Emotion, ...) Using a model form I am able to successfully save user choice (i.e. the "emote_state" value) in table "EmoteStateResponse". However, as the choices might run into a number of instances of field "emote_state" (individual emotions) of table "Emotion", I am trying to select "at random" only a minimal number to display. To do that, I am trying to randomize the choices in my form that goes like the following: import random class EmoteTestForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(EmoteTestForm, self).__init__(*args, **kwargs) self.auto_id = True class Meta: model = EmoteStateResponse # ... fields = ('emote_state_selected', ...) def __init__(self, *args, **kwargs): super(EmoteTestForm, self).__init__(*args, **kwargs) qs_emot_state = Emotion.objects.all().values_list('emot_state_grp__emotion_grp_id', 'emote_id') # "emotion_grp_id": Key Field model "EmotGroup" list_qs_emot_state = list(qs_emot_state) rand_emot_state_list = … -
Sending emails in Celery tasks not executing
I have a view function in Django, which receives a post request with the data of sending letters (the poster post, the topic of the letter, message, etc.) from the user and transmits them to Celery Tasks, to send letters through standard function of the Django send_mail. For some reason, Celery Task is not performed. Using: Django, Redis, Celery, Docker Project structure: sender sender -- init.py -- asgi.py -- celery.py -- settings.py -- urls.py -- wsgi.py emails -- migrations -- init.py -- admin.py -- apps.py -- forms.py -- models.py -- tasks.py -- tests.py -- views.py templates venv db.sqlite3 docker-compose.yml Dockerfile manage.py views.py: from django.shortcuts import render, redirect from .tasks import * from .models import * from .forms import * def send_some_email(request): if request.method == 'POST': form = EmailForm(request.POST) if form.is_valid(): from_mail = form.cleaned_data['from_mail'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] cat = form.cleaned_data['cat'] limit = form.cleaned_data['limit'] try: send.delay(from_mail, subject, message, cat, limit) return redirect('home') except Exception as ex: print(ex) return redirect('errorpage') else: form = EmailForm() return render(request, 'emails/index.html', {'form': form}) tasks.py: from celery import shared_task from .forms import * from django.core.mail import send_mail @shared_task def send(from_mail, subject, message, cat, limit): for element in Emails.objects.filter(active=True, category__name=cat)[:limit]: send_mail(subject=subject, from_email=from_mail, message=message, recipient_list=[str(element), ]) print(str(element)) … -
Django-guest-user custom name
I am using 'julianwachholz/django-guest-user' library to login as a 'guest user'. The generated user name is long (based on uuid). The library has 3 functions: generate_uuid_username (default) generate_numbered_username generate_friendly_username It uses NAME_GENERATOR (in the AppSettings) to point the desired function. I am new to Django and want help to use this customization. -
Defining the unit of measurement when annotating a django queryset using Distance
I am very new to django / python. I am currently experimenting building a web application using GeoDjango on MySQL/Spatialite (later I will move to postgres/postGIS when I decide to pay for a dedicated environment). I use the following expression to get a queryset which is annotated with the distance of each Splitter's company's service_area's centroid (point field). sl = Splitter.objects.filter(company__in=companies, seats__gte=int(seatval), selfhire=selfval).annotate(distancefrom=Distance('company__service_areas__centroid', postcode_location)).order_by('distancefrom') Not sure if this is important, but I am importing Distance from django.contrib.gis.db.models.functions It works fine, however the default value for the "Distance" calculation is in metres. As such I get annotated values generated that look like this: 46035.39602585269 m I'd much rather get these values in miles or km. How can I alter the expression to force the annotation to be in these units instead? Alternatively what method could I use to update the annotations? I'd rather not iterate over the queryset. Typically distance.mi or distance.km would give me these values, but I am not sure how to do this as part of an annotation? What I tried: I tried simply adding .mi into the expression but it does not seem to work. sl = Splitter.objects.filter(company__in=companies, seats__gte=int(seatval), selfhire=selfval).annotate(distancefrom=Distance('company__service_areas__centroid', postcode_location).mi).order_by('distancefrom') I am reluctant to use a … -
I try to test django model method __str__()
I trying to test str method in model but it do not working. It is my Student model class Student(models.Model): name = models.CharField(max_length = 100) email = models.EmailField(max_length = 277) created_at = models.DateTimeField(auto_now_add = True, null = True) updated_at = models.DateTimeField(auto_now_add = True, null = True) degree=models.BooleanField(default=False) def __str__(self) -> str: return self.name It is my tests.py class StudentCreateTests(TestCase): def create_student(self): student=Student.objects.create( name="tami", email="tami@mail.ru" ) self.assertEqual(student.name, "tami") self.assertEqual(student.email, "tami@mail.ru") self.assertEqual(str(student), student.name) #self.assertEqual(student.__str__(), student.name) What is problem? -
Django managed=False option will not create migrations but will it run manual migration on the table?
I wanted to understand the working of managed = False option in Django models. If managed is set to False then the migrations for the table are not created by issuing the makemigrations command. However, I wanted to know that if there is a manual migration file created and there are altertable commands in the manual migration file for the table for which managed is set to False will running the migrations change the database. Thank you. -
Sorl-thumbnail dont create folder in cache
I get an error instead of thumbnail `[Errno 2] No such file or directory: 'D:\\developer\\love\\love_prim\\media\\Photo object (11)' Remote file [Photo object (11)] at [960x339] does not exist [25/Feb/2023 17:07:53] "GET / HTTP/1.1" 200 3634 Not Found: /media/cache/e5/e6/e5e60125af238c62ca330679f6c18c56.jpg [25/Feb/2023 17:07:53] "GET /media/cache/e5/e6/e5e60125af238c62ca330679f6c18c56.jpg HTTP/1.1" 404 5065 ` Cache directory not created in media folder. The cache directory is not created in the media folder. The image is immediately saved to folder profiles. [[enter image description here](https://i.stack.imgur.com/8NJCD.jpg)](https://i.stack.imgur.com/PrkIg.jpg) Tried to execute commands thumbnail cleanup and thumbnail clear. I also tried to create the cache folder myself with permissions 777. No result. -
how get the count of enum field items in django
I have a field of type enum: place_menu=models.CharField(choices=placeMenu.choices) How can I get count item with value enum? My enum field has four values. And I want to get the count of each value Optimally. -
Why the first() method and slices works differently in Django?
I have this code: print(Pet.objects.all().first()) print(Pet.objects.all()[:1].get()) it seemed to me that the same objects should be displayed, but different ones are returned. What's going on, isn't it an identical design?