Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
django add url parameter in a view function
I am building a follower list view, frontrend allows user to search followers on a specific user by request.GET After adding the pk on the url in frontend, we use something like /?user=2 To find all followers of user 2. Here’s the issue. The frontend must have user parameter to indicate who you searching, show a user card in the search box. And the backend, if there is no user Param set, will target followers of request.user. When the url is /, I am actually going for /?user=request.user.pk, can I add this parameter in view function? Or how can I re-parse the url and call the view function again when default? Something to add manipulate param before redirect def userFollowerView(request): user = request.GET.get('user', None) if not user: request.path.setParam('user', request.user.pk) return userFollowerView(request) # or redirection return ... The reason I am not using a regex pattern to indicate user Pk and another url for redirection, is that, this is a minimised example, in real life I am dealing with a pk list on other scenario that must be passed as url param. -
command not found - Python Django app deployment issue with DigitalOcean
I’m having a problem with the package gunicorn on the app platform while it’s present in my requirements.txt file. bash: gunicorn: command not found With app platform, I am not able to find the flexibility to change the system configurations. Is there a way I can add the gunicorn binary to $PATH or add a symlink somehow? I tried to build the app again and changed my run configuration but it didn't help. The deployment fails after the build step. This error might make me to configure a bare metal server droplet which would be a bit tedious. Probably a noob question, but could someone help on this? I am blocked by this, so would really appreciate your help! Thank you in advance. -
Getting the most recent versions of entries in a Django model with versioned data
The application I'm working on has a schedule which assigns workers to work in different locations at different time blocks. The schedule is versioned through a ChangeSet model. Each ScheduleEntry references a ChangeSet. class Worker(models.Model): name = models.CharField(max_length=100) class Location(models.Model): name = models.CharField(max_length=100) class TimeBlock(models.Model) start_date = models.DateField() end_date = models.DateField() class ChangeSet(models.Model): published_on = models.DateTimeField(null=True) class ScheduleEntry(models.Model): change_set = models.ForeignKey(ChangeSet, on_delete=models.CASCADE) worker = models.ForeignKey(Worker, on_delete=models.CASCADE) time_block = models.ForeignKey(TimeBlock, on_delete=models.CASCADE) location = models.ForeignKey(Location, null=True, on_delete=models.CASCADE) A worker can only be assigned to one location for each time block. This location is is determined by the ScheduleEntry with the most recent non-null change_set.published_on for that worker and time block. A Worker could be unscheduled (have None for their location) either because there aren't any schedule entries for the worker in that time block, the entries are all linked to unpublished change sets, or the most recent published entry specifies null as the location. Getting the current published schedule location in a specific time block for a worker is easy: ScheduleEntry.objects.filter( change_set__published_on__isnull=False, worker=my_worker, time_block=my_time_block, ).order_by('-change_set__published_on').first() However, I can't figure out how to perform a query to get things like: Full schedule for a worker, across all time blocks All workers scheduled to … -
Django doesn't run if I remove 'command' from docker-compose
Here's how I want to run my container with the following commands: docker-compose up -d --build docker compose up -d docker exec -it app_api bash From there I will have a shell where I can run ./manage.py runserver 0.0.0.0:8000 or makemigrations etc. This docker-compose runs if I uncomment the 'command' line. However, I don't want runserver to run automatically, I just want the shell. docker-compose.yml version: '3.8' services: web: container_name: app_api build: . # command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/project ports: - 8000:8000 depends_on: - db db: image: postgres container_name: app_db environment: POSTGRES_PASSWORD: postgres volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: Dockerfile FROM python:3.9 ENV PYTHONDONTWRITEBYTECODE 1 WORKDIR /project COPY requirements.txt /project/ RUN pip3 install -r requirements.txt COPY . /project/ With the command line commented out and after running docker compose up -d I get: [+] Running 2/2 ⠿ Container app_db Running 0.0s ⠿ Container app_api Started As you can see, app_api is started but not running. -
Properly Structure Multi-app Django Graphene Queries
I started moving my REST API endpoints to using GraphQL with Graphene. Seems pretty straightforward so far, but one of the things that I like about the REST API (and I cannot figure out in Graphene) is the structure of "endpoints" for each app. I have a lot of apps in my Django application, and I would like to group the Graphene queries and mutations of each app under a single "endpoint" (just like you would do in REST by sending a request to app_1/endpoint and app_2/endpoint). Currently I have a graphql folder inside of each app, with files for my queries and mutations inside. Then, under my main schema file, I just create a giant query and mutation objects that inherit from the elements of all other apps. # app1/graphql/queries.py class Endpoint1(DjangoObjectType): class Meta: model = Element1 fields = ("id", "name", "date") # app2/graphql/queries.py class Endpoint2(DjangoObjectType): class Meta: model = Element2 fields = ("id", "name", "date") # Place where my main schema is located # django_project/graphql/queries.py class Queries(Endpoint1, Endpoint2): pass Would it be possible to group queries and mutations from a single app and then just inherit from each of the app's mutations and queries in the main schema, … -
"permission_classes = [IsAuthenticated]" causes error - 'dict' object has no attribute 'exception'
Whenever I add this permission " permission_classes = [IsAuthenticated]" to my viewsets in drf (django rest framework) it throws this exception on the browser when I am not logged in 'dict' object has no attribute 'exception' but if I am logged in everything works fine. If I am not logged in, I want a message like this. {"detail": "Authentication credentials were not provided."} on the browser, which tells the client side what the issue is. This is my views.py from django.shortcuts import render from rest_framework.viewsets import ModelViewSet, GenericViewSet from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin from rest_framework.decorators import action from .serializers import CategorySerializer, StoreSerializer, SubCategorySerializer, ProductSerializer, LikeProductSerializer, CartSerializer, CartitemSerializer, AddCartItemSerializer, UpdateCartItemSerializer, ReviewSerializer, CustomerSerializer, OrderItemSerializer, OrderSerializer, CreateOderSerializer, UpdateOrderSerializer, SimpleProductSerializer from .models import Category, SubCategory, Products, Cart, CartItems, Reviews, Customer, Order, OrderItem, Store from rest_framework.parsers import MultiPartParser, FormParser from rest_framework import parsers from django.contrib.auth import get_user_model from rest_framework.permissions import IsAuthenticated, AllowAny, IsAdminUser from rest_framework.response import Response from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import SearchFilter # Create your views here. class ProductViewSet(ModelViewSet): queryset = Products.objects.all() serializer_class = ProductSerializer parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.FileUploadParser) filter_backends = [DjangoFilterBackend, SearchFilter] filterset_fields = ["category_id", "subcategory_id"] search_fields = ["name", "description"] permission_classes = [IsAuthenticated] This is the error … -
what kind of the error is these [Errno 111] Connection refused and how to solved it?
i try to send mail using django send_mail but when i try send mail from local it can be work properly but production it say error "[Errno 111] Connection refused"