Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get a response with new line characters with Django Rest Framework's Response?
I am currently trying to understand how to use the Response class from DRF. Using Django's HttpResponse, and using the following code: return HttpResponse("Hello \n World", content_type="text/plain") I get the following response: Hello World Which is what I am expecting. However, using the following code: return Response("Hello \n World", content_type="text/plain") I get the following response: "Hello \n World" Notice how I also get the pair or quotes in the second one "". Since Response is a child of HttpResponse, how can I have the same result using Response? I've come to this problem because I want to present new line characters and tab characters with Response, but I have not been successful so far. The only the I've seen that might help me was using Renderers from DRF, and making a custom one for plain text. but I do not understand how to apply them to Responses, and I am a bit surprised that DRF doesn't support plain text considering it is a subclass of HttpResponse. Thank you -
Django form fields not rendering in template
I am trying to render a simple Django Form on my index page. I have stripped it way back in an attempt to get it to work. I can display other context elements when passing them in, and I know an instance of the Form is being created (by printing type(form)), it is just empty and I cannot figure out why. I have made similar forms multiple times before without running into this issue. I have tried rendering as {{ form.as_p }} as well as {{ form }}. All that renders is the heading, the hidden csrf_token, and the submit button. Thanks in advance... from django import forms class NewPostForm(forms.Form): title: forms.CharField(label='Title', max_length=100) content: forms.CharField(label='Content', max_length=100) def index(request): form = NewPostForm() return render(request, "network/index.html", { "form": form }) {% block body %} <div class="new-post"> <h5>New Post</h5> <form action="" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Add Post"> </form> </div> {% endblock %} -
ManyToMany Relationship with additional fields Django Forms
For my Django project I am trying to create a singular form that allows me to add a row in my Pipeline model and link that row to the Process model through the PipelineProcess model. This is fairly straightforward by using ModelForms IF the PipelineProcess model did not have an extra field (phase). models.py class Pipeline(models.Model): name = models.CharField(max_length=100) sector = models.CharField(max_length=100, blank=True, null=True) process = models.ManyToManyField(Process, through='PipelineProcess') class Meta: managed = True db_table = 'pipeline' class Process(models.Model): name = models.CharField(max_length=100) class Meta: managed = True db_table = 'process' class PipelineProcess(models.Model): pipeline = models.ForeignKey(Pipeline, models.DO_NOTHING, blank=True, null=False) process = models.ForeignKey(Process, models.DO_NOTHING, blank=True, null=False) phase = models.CharField(max_length=100) class Meta: managed = True db_table = 'pipeline_process' forms.py class PipelineForm(ModelForm): class Meta: model = Pipeline fields = ['name', 'sector', 'phase'] This form generates the following error which makes sense: django.core.exceptions.FieldError: Unknown field(s) (phase) specified for Pipeline I have tried looking up examples of other people but none of which are useful to me. Most were far too complicated for me to put into my own project. I am fairly new with Django and web dev in general. Any help would be greatly appreciated. -
user login changes automatically in django
whenever I login in my admin panel, automatically my user site login changes to admin in django I am using django's AuthenticationForm from django.contrib.auth.forms import AuthenticationForm this is my login form code class LoginForm(AuthenticationForm): username = UsernameField(widget=forms.TextInput(attrs={'autofocus':True, 'class':'form-control'})) password = forms.CharField(label=_("Password"), strip=False ,widget=forms.PasswordInput(attrs={'autocomplete':'current-password', 'class':'form-control'})) -
Django using PostGres Full Text Search not recognizing certain words when setting config='english'
So I'm running into a very weird issue. I'm using Django's SearchQuery app in Django, using Django 3.2.1 and the most up to date PostGreSQL. The issue emerges when I use a search query with websearch and config set to english. Here is the initial code for the instantiation of the search_query with config='english' search_query = SearchQuery(query_string, search_type='websearch', config='english') And this is the code for when I search for it: agenda_items = AgendaItem.objects.annotate(search=SearchVector('name', 'description', 'note'),search_rank=SearchRank('search', search_query)).filter(search=search_query).order_by('-search_rank').distinct() When I search for the word "cupcake" it displays nothing, despite the word actually being present. However, if I remove config='english' from the SearchQuery it works. However, I lose the English language support. Does anyone have any ideas. -
'AnonymousUser' object is not iterable at my index
So hello guys, Im new here at Django and while running my code i ran to this kind of error 'AnonymousUser' object is not iterable it highlight my error in my index line 37. patient=Patient.objects.filter(user = request.user) so this is my views.py def index(request): feature1 = Feature.objects.all() Appnt = Appointment() if request.user: patient=Patient.objects.filter(user = request.user) if request.method == 'POST': name = request.POST.get('name') Appnt.name = name email = request.POST.get('email') Appnt.email = email phone = request.POST.get('phone') Appnt.phone = phone Adate = request.POST.get('date') Appnt.Adate=Adate Dept = request.POST.get('department') Appnt.Dept=Dept Doc = request.POST.get('doctor') Appnt.Doc=Doc Content = request.POST.get('message') Appnt.Content = Content Appnt.ref = "ref_" + str(len(Appointment.objects.all()) + 1) Appnt.save() sendEmail(email, "Date: " + Adate + "\n" + name + "\n" + phone + "\n" + Dept + "\n" + Doc + "\n"+ Content) context = { 'feature1' : feature1, 'Appointment' : Appnt } return render(request, 'index.html', context) and this is my urls.py path('', views.index , name='index'), -
Adding custom permission to Django Rest Framework Function-Based view
I am trying to write a custom IsOwner permission for a DRF function based view that has a parameter of user_id. The view is as follows: @api_view(['GET']) @permission_classes([permissions.IsAuthenticatedOrReadOnly]) def return_credibility(request, user_id): credibility = utils.get_credibility(user_id) return Response({'id': user_id, 'credibility': credibility}) except I would want to replace permissions.IsAuthenticatedOrReadOnly with my custom IsOwner permission. I tried writing something like this: class IsOwner(permissions.BasePermission): def has_permission(self, request, view): return request.user.id == view.user_id except I am not sure how to access the user_id property from the view. Does anyone know how I can do this? Thanks! -
How Django handling long request in another request?
Issue about django handling a long request(50sec) in another request(3sec). I have a POST request will return some infomation for user, in this request will call another api in the same app and it will query database and generate pdf report then upload to s3, it will cost about 50sec. How can I let first request return infomation to user and generate pdf api run in background? I have done some research, found Celery may be can handle this task, is this recommend? or anyone have advice? Thanks in advance!!! -
Django 3.0 update a model inside of a detailview
I have a "project" model that has a "status" field. The status can be active, paused, or complete. I want to be able to update the field via form on the project detail view. I have read a few solutions to this problem but, as a newbie, I haven't been able to get this to work. When I submit the form I get an http 405 error and the instance is not updated. the model: class Project(models.Model): title = models.CharField(max_length= 200) description = tinymce_models.HTMLField() status = models.CharField(max_length=20, choices=PROJECT_CHOICES, default="active") date = models.DateTimeField(auto_now_add=True, null=True) created_by = models.ForeignKey(CustomUser, editable=False, null=True, blank=True, on_delete=models.RESTRICT) objects = ProjectManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('company_project:project_detail', args=[str(self.id)]) the view class CompanyProjectsDetailView(DetailBreadcrumbMixin, FormMixin, DetailView): model = Project id = Project.objects.only('id') template_name = 'company_accounts/project_detail.html' context_object_name = 'project' form_class = ProjectStatusForm notescount = Project.objects.annotate(num_notes=Count('notes')) documentscount = Project.objects.annotate(num_documents=Count('project_documents')) todoscount = Project.objects.annotate(num_documents=Count('todo_group')) def form_valid(self, form): project = get_object_or_404(Project, id=self.kwargs.get('pk')) theform = form.save(commit=False) theform.project = project form.save() return super(CompanyProjectsDetailView, self).form_valid(form) the form class ProjectStatusForm(forms.ModelForm): class Meta: model = Project fields = ['status'] labels = {'status': 'project status'} widgets = { 'status': forms.Select(attrs={'id':'PROJECT_CHOICES'}), } On the page I use this code to add the form <form action="" method="post"> {% csrf_token %} {{ … -
Deploying Django project on Window server with Nginx and Waitress issue
Basically, I follow all of the instructions from here: [https://github.com/Johnnyboycurtis/webproject#nginx-and-waitress] All things were going fine, the Django project was successfully deployed. But the problem that I faced was after I close the cmd of the running script of waitress (runserver.py): #runserver.py from waitress import serve from webproject.wsgi import application # documentation: https://docs.pylonsproject.org/projects/waitress/en/stable/api.html if __name__ == '__main__': serve(application, host = 'localhost', port='8080') the website stopped working immediately. After I run the runserver.py from cmd again, the website was back to work but stopped if I close my cmd again. The question is how do I keep my website alive without the cmd to running waitress, any help was appreciated. -
Direct assignment to the reverse side of a related set is prohibited. Use images.set() instead while using create()
I am building a simple images blog app, And I build two models and one with Parent ForeignKey. I made the serializer but when I try to create a new instance then it is keep showing me Direct assignment to the reverse side of a related set is prohibited. Use images.set() instead. models.py class Gallery(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) class Image(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, related_name="images") text = models.CharField(max_length=300) serializer.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = "__all__" class GallerySerializer(serializers.ModelSerializer): images = ImageSerializer(many=True) class Meta: model = Gallery fields = "__all__" def create(self, validated_data): return Gallery.objects.create(**validated_data) Then I also tried creating both model's instances separately. def create(self, validated_data): new_data = Gallery.objects.create(poll=1, images=validated_data["images"]) return new_data But it also showed me the same error it showed me before. I am new in Django-Rest-Framework, I have tried many times but it is still not creating. Any help would be much Appreciated. Thank You in Advance -
django getting declared with a lazy reference error
ı am developing a django project.After I deployed my project on aws,at first everything was fine.But after that have to create model.After migrations operand I get this error raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field socialaccount.SocialAccount.user was declared with a lazy reference to 'psycholog.customusermodel', but app 'psycholog' isn't installed. How can I fix that? -
Fetch API post data is not transferring data to views.py in Django
I am creating a Django app and for that I am trying to access data received from a POST request, using JavaScript fetch API but it is not working. I can see that the page is not refreshing after hitting the submit button because of the e.preventDefault(); but the values are not getting fetched at all. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where am I going wrong. views.py def home(request): if request.method=="POST": options_value=request.POST['dropdown_val'] value=request.POST['val'] print(options_value,value) index.html <form method="POST" action="" id="form"> {% csrf_token %} <div class="d-flex justify-content-center" style="margin-top: 6rem"> <div class="dropdown" style="display: flex" id="dropdown"> <select class="form-select" aria-label="Default select example" name="options_value" id="dropdown_val" > <option disabled hidden selected>---Select---</option> <option value="1">Profile UID</option> <option value="2">Employee ID</option> <option value="3">Email ID</option> <option value="4">LAN ID</option> </select> </div> <div class="col-3 bg-light" style="margin-left: 2rem"> <input type="text" class="form-control" id="in3" type="text" placeholder="Enter Value" name="value" id="value" /> </div> <div style="margin-left: 2rem"> <input class="btn btn-primary" type="submit" value="Submit" style="background-color: #3a0ca3" /> </div> </div> </form> <script> let form = document.getElementById("form"); let dropdown_val = document.getElementById("dropdown_val"); let val = document.getElementById("value"); const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value; form.addEventListener("submit", (e) => { e.preventDefault(); const newform = new FormData(); newform.append("dropdown_val", dropdown_val.value); newform.append("val", val.value); newform.append("csrfmiddlewaretoken", csrf); fetch("", { method: … -
Auto-update views.py
I created a function for editing tables but it is done by url address "get/by/int:pk/" and I need it to be done automatically after saving in Django Admin panel. How can I do that? def obj(request, pk,): reg = Registration.objects.get(pk=pk) room = Rooms.objects.get(pk=pk) if reg.room_bool == True: room.room_bool = True room.save() if reg.room_bool == False: room.room_bool = False room.save() how can this be implemented -
error deploy django app on digitalocen app platform
i tried to deploy my Django app from git hub to digital ocean, i didn't include a Dockerfile and used a basic image from digital ocean. when the app is launce I kept getting this error in the runtime log : [CRITICAL] WORKER TIMEOUT (pid:16) [WARNING] Worker with pid 16 was terminated due to signal 9 [INFO] Booting worker with pid: 36 my run command is : gunicorn --worker-tmp-dir /dev/shm xclusive.wsgi thank you for helping -
change max header size in django
I am using Django via gunicorn and Apache. In httpd.conf of Apache I have set globally (outside virtual host blocks) LimitRequestFieldSize 32000 and this seams to work. (Ssing curl sending 31995 Bytes to a static website results in Http response 200 while sensing 31996 Bytes results in 400.) When Django should return a JSON in a header (for a download request) I got: response.headers["content-length"] : 25544 len(response.headers['json']) : 8185 For me it seams like there is still a 8 kB limit somewhere. Is there a setting for this in the Django config. (As I found out it is not DATA_DOWNLOAD_MAX_MEMORY_SIZE.) -
Setting USER in Dockerfile prevents saving file fields (eg. ImageField) in Django
I am trying to containerize Django with Dockerfile and docker-compose.yml as defined below. I built the Dockerfile as (fiifidev/postgres:test) for the compose file. Everything works fine. However anytime I try to save a model with a file field (eg. ImageField or FileField), I get Permission Error PermissionError: [Errno 13] Permission denied docker. I suspect I am not adding the appropriate permission of user creation (useradd) in the Dockerfile (not sure). But when I remove the USER everything works fine. How can I fix this any help will be much appreciated. FROM python:3.10-slim-bullseye as base # Setup env ENV LANG C.UTF-8 ENV LC_ALL C.UTF-8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONFAULTHANDLER 1 FROM base AS python-deps # Install pipenv and compilation dependencies RUN pip install pipenv RUN apt-get update && apt-get install -y --no-install-recommends gcc # Install python dependencies in /.venv COPY Pipfile . COPY Pipfile.lock . RUN PIPENV_VENV_IN_PROJECT=1 pipenv install --deploy FROM base AS runtime # Copy virtual env from python-deps stage COPY --from=python-deps /.venv /.venv ENV PATH="/.venv/bin:$PATH" # Create and switch to a new user RUN useradd --create-home appuser WORKDIR /home/appuser/src USER appuser # Install application into container COPY --chown=appuser:appuser . . version: "3.9" services: web: image: fiifidev/postgres:test command: sh -c … -
how to use Django F() expression in `update` for JSONField
I have around 12 million records that I need to update in my postgres db (so I need to do it in an efficient way). I am using Django. I have to update a jsonfield column (extra_info) to use values from a different column (related_type_id which is an integer) in the same model. Trying to do it with an update. This seems to be the way to do it most efficiently. Example: Person.objects.all().update(extra_info={ "type": "Human", "id": F('related_type_id') }) This errors out with : "Object of type F is not JSON serializable". I thought the F() will give back the value of that column (which should be an integer) which should be serializable. Can this be done ? Or am I trying to do it in the wrong way. I don't really want to iterate in a for loop and update each record with a save() because it will take too long. There's too many records. -
Trying to make a 'friend request' signal in django but getting FOREIGN KEY constraint failed - Django
I am trying to make a feature where a student can send a teacher friend request and if the teacher accepts it, the student should get added to a students' list present in the teacher's profile model and the teacher should get added to the teachers' list present in the student's profile. To handle and store this relationship between sender and receiver I have made a different model (Relationship) and signal. But while the operation is being carried out by the signal I get this error FOREIGN KEY constraint failed Please look at my code below and correct me on what should I do to get rid of this error. teacher's profile model (TeacherDetail) class TeacherDetail(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, blank=True) student = models.ManyToManyField(CustomUser, blank=True, related_name='students') # this is the student's list student's profile (StudentDetail) class StudentDetail(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, blank=True) teacher = models.ManyToManyField(CustomUser, blank=True, related_name='teachers') # this is the teacher's list model that stores the sender and the receiver (Relationship) STATUS_CHOICES=( ('sent', 'sent'), ('pending', 'pending'), ('accepted', 'accepted') ) class Relationship(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='sender') # the student receiver = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name='reciever') # the teacher status = models.CharField(max_length= 10, choices=STATUS_CHOICES) … -
Django UNIQUE constraint fails with composite primary key
I have searched for similar cases but they do not seem to question the model.save() method. I am new to Django and, following the standard methodology, have declared a class to map it to a ddbb (autoincremental id): class Crudos(models.Model): cuenta = models.CharField(verbose_name='Cuenta', max_length=100) concepto = models.CharField(verbose_name='Concepto', max_length=100, default='indefinido') magnitud = models.FloatField(verbose_name='Magnitud') fecha = models.DateField(verbose_name='Fecha') documento = models.FilePathField(verbose_name='Documento') class Meta: unique_together = ('cuenta', 'fecha',) The view that uses this class also populates the table: for index, row in df.iterrows(): data = Crudos(cuenta=row.Cuenta, concepto=row.Concepto, magnitud=row.Magnitud, fecha=row.Fecha, documento=row.Documento) data.save() The dataframe is generated from a file and the process works without problems the first time. If I use the same file twice, then I get the error message of UNIQUE constrain failed. Models.save() should be an update instead of an insert when trying to insert a register with the same unique combination of values. It does so when the primary key is included in the data to save. The problem comes when there is a need for a composite primary key, as it is the case of the Crudo class, which is reflected by the unique_together condition. It seems Django is not able to interpret that condition as one to execute an … -
Django: Add Minus Cart Button Using JQuery
My models: class Cart(models.Model): cart_id = models.CharField(max_length=255, blank=True) date_added = models.DateField(auto_now_add=True) class Meta: verbose_name_plural = 'Cart' def __str__(self): return self.cart_id class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.IntegerField() is_active = models.BooleanField(default=True) def total(self): return self.product.price * self.quantity def __str__(self): return self.product My views: def _cart_id(request): cart_id = request.session.session_key if not cart_id: cart_id = request.session.create() return cart_id def add_to_cart(request, product_id): product = Product.objects.get(id=product_id) try: my_cart = Cart.objects.get(cart_id=_cart_id(request)) my_cart.save() except ObjectDoesNotExist: my_cart = Cart.objects.create( cart_id=_cart_id(request), ) my_cart.save() try: cart_item = CartItem.objects.get(product=product, cart=my_cart) cart_item.quantity += 1 cart_item.save() except ObjectDoesNotExist: cart_item = CartItem.objects.create( product=product, cart=my_cart, quantity=1, ) cart_item.save() return redirect('cart') def cart(request, sub_total=0, quantity=0, cart_items=None, sale_tax=0): try: current_cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=current_cart, is_active=True) for item in cart_items: sub_total += (item.product.price * item.quantity) quantity += item.quantity sale_tax = round((7 * sub_total)/100, 2) except ObjectDoesNotExist: pass context = { 'sub_total': sub_total, 'quantity': quantity, 'cart_items': cart_items, 'sale_tax': sale_tax, 'grand_total': sale_tax + sub_total, } return render(request, 'cart.html', context) My template portion: <tbody> {% for item in cart_items %} <tr> <td class="product-thumbnail"><a href="{{ item.product.get_url }}"><img src="{{ item.product.image_1.url }}" alt=""></a></td> <td class="product-name"><a href="{{ item.product.get_url }}">{{ item.product.product_name }}</a></td> <td class="product-price"><span class="amount">${{ item.product.price }}</span></td> <td class="product-quantity"> <div class="cart-plus-minus"><input type="text" value="{{ item.quantity }}" /></div> </td> <td class="product-subtotal"><span … -
AssertionError while working on django rest framework
I have this error, i don't know how to fix it AssertionError: Expected view ListingView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly class ListingView(RetrieveAPIView): queryset = Listing.objects.order_by('-list_date').filter(is_published=True) serializer_class = ListingDetailSerializer look_field = 'slug' urlpatterns = [ path('', ListingsView.as_view()), path('search/', SearchView.as_view()), path('<slug>/', ListingView.as_view()) ] -
Create object and display it in same page with htmx
The function I am trying to implement is that, when the form is submitted in the create view, I would like to display the created object beneath it without the page refreshing. I know the way to implement this is through HTMX. The object that is being created is a key which is unique and gets randomly generated. However it does not work properly. Right now, first time clicking the button it creates a key and displays it but the second time it tries to show the previous key and because it already exists it is not unique and therefore it shows nothing. This is the model class Key(models.Model): key = models.CharField(max_length=10, null=False, default=get_random_string(length=10), unique=True) amount = models.IntegerField(default=1) created = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse("key", kwargs={"id": self.id }) I have two views, a create view and a detail view, I would have liked to used CBV but I can't get my head around how I would implement that, so I am sticking to function based views. Right now the views are looking like this @login_required def key_create_view(request): form = CreateKeyForm(request.POST or None) context = { "form": form, } if form.is_valid(): obj = form.save(commit=False) obj.save() kod_url = reverse('key', kwargs={'id':obj.id}) if request.htmx: … -
Getting error in Linux printing Security group in azure
I have this code and I have written it in windows. and it works fine in windows but when I run it on Linux and I have to run it on Linux as of my project needs and it does not works there and gives me the following error AttributeError: 'ServicePrincipalCredentials' object has no attribute 'get_token' from azure.mgmt.security import SecurityCenter from azure.common.credentials import ServicePrincipalCredentials import Credentials from pprint import pprint client = SecurityCenter(Credentials.credential,Credentials.subscription_id,asc_location="") for score in client.secure_scores.list(): print(score) -
How to retrieve integer from database objects
I'm fairly new to Django and try to get a database for scientific reviews up and running. One of the things I would like to show is how many reviews have been published in each year. In this example I used the following data: | year | number of reviews published | | ---- | --------------------------- | | 1999 | 1 | | 2019 | 4 | | 2022 | 5 | models.py class Review(models.Model): title = models.CharField(max_length=100,null=True) doi = models.URLField(max_length=200,unique=True,null=True) author = models.CharField("First author",max_length=100,null=True) year = models.PositiveIntegerField(null=True) views.py from django.shortcuts import render from .models import Review from django.db.models import Count def about(response): reviews_year_count = Review.objects.values('year').annotate(Count('year')) context = {'reviews_year_count':reviews_year_count} return render(response, "main/about.html", context) reviews.html <html> <body> {{reviews_year_count|join:", "}} </body> </html> output on localhost Currently: {'year': 1999, 'year__count': 1}, {'year': 2019, 'year__count': 4}, {'year': 2022, 'year__count': 5} Aim: 1, 4, 5 What I can't figure out is how to get rid of the {'year': 1999, 'year__count': } and only have the integer value there. I looked at Django documentation pages. One of the things I tried was add defer() behind reviews_year_count = Review.objects.values('year').annotate(Count('year')) but calling defer()after values() doesn’t make sense according to documentation. My aim is to use the data as …