Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CircleCI config for django
I have this circleci config version: 2.1 orbs: python: circleci/python@0.2.1 jobs: build: executor: python/default docker: - image: circleci/python:3.9 environment: DATABASE_URL: postgresql://circleci@localhost/circle_test - image: circleci/postgres:13.3 environment: PGHOST: localhost PGUSER: circleci POSTGRES_USER: circleci POSTGRES_DB: circle_test POSTGRES_HOST_AUTH_METHOD: trust steps: - checkout - python/load-cache - run: name: Installing dependencies command: | python3 -m venv venv . venv/bin/activate pip3 install -r requirements.txt - python/save-cache - run: name: Running tests command: | . venv/bin/activate python manage.py test When i commit django-test with TestCase, only choose test with SimpleTestCase, circleci comlete, but when i uncomment TestCase i have this errors RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead -
How Do I Override GET in Django Detailview?
I have a FORMVIEW that is redirecting to a DETAILVIEW and that is working perfectly. The issue I'm having is when I try to combine Pagination with DetailView. When I try to leverage the pagination, the GET is essentially redirecting me to the FORMVIEW. I get why it's doing this...I'm telling it to. What I'm trying to work out is how I can put in some logic in my overridden GET. I tried to do a self.GET_OBJECT.pk...to see if I could determine if I'm on the current page and not the FORMVIEW but that didn't work... Here's my DetailView.... def get_context_data(self, **kwargs): context = super(SuggestionByNameDetailView, self).get_context_data(**kwargs) attachments = SuggestionFiles.objects.filter(suggestion=self.object.pk).all() comment_form = SuggestionCommentForm() response_form = SuggestionCommentReplyForm() activities= self.get_related_activities() context['suggestion_comments'] = activities context['page_obj'] = activities context['attachments'] = attachments context['comment_form'] = comment_form context['response_form'] = response_form return context def get_related_activities(self): queryset = self.object.suggestion_comments.all() paginator = Paginator(queryset,5) #paginate_by page = self.request.GET.get('page') activities = paginator.get_page(page) return activities def get_object(self, queryset=None): return get_object_or_404(Suggestion, id=self.request.GET.get("dropdown")) def get(self, request, *args, **kwargs): dropdown=self.request.GET.get("dropdown") if dropdown is not None: if Suggestion.objects.filter(Q(id=self.request.GET.get("dropdown"))).distinct(): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) else: raise Http404 else: messages.add_message(self.request, messages.INFO, 'Suggestion is required.') return HttpResponseRedirect(reverse('Suggestions:suggestion_by_name')) As mentioned I did try to do something like...if DROPDOWN is … -
Insert multi selected option text into pg using django
For instance, I used Django to pull certain unique number data from my database. Then I created dropdown with search using select2. And used jQuery for search functionality. With this I could select multiple unique number at a time and with output printed in textarea field. my question is, how to insert multiple selected options in Postgrel using Django. I need help in backend as i m newbie in django I tried to served everywhere but I could see only php guide. this is my frontend code enter code here Search Models for CId {% csrf_token %} {% for x in searchmodels %} {{ x.cid }} {% endfor %} You can add multiple CID and click Add --> <br> <div class="resultbox"> <h2>Selected CIDs</h2> <textarea name="" id="cidresult" cols="70" rows="15"></textarea><br><br> <input type="button" id="addcid" value="Submit" onclick="searchresult();"> </div> </form> </tr> <style> .resultbox{ position: fixed; left: 30%; top: 10px; width: 550px; background-color: antiquewhite; padding-left: 30px; padding-right: 10px; } </style> Now here is my jQuery code $(document).ready(function() { $('#selectedcid').select2({ placeholder:'Search CID...', closeOnSelect:false }); $('#selectedcid').on('change',function() { var resultdisplay=$('#selectedcid option:selected').text(); $('#cidresult').val(resultdisplay).join(','); }) }); this is how it looks nowenter image description here -
Django custom permission not being assigned to newly created User
This seems pretty trivial but I can't figure out what I'm doing wrong. I've checked several SO posts that sounded similar but the issue apparently lies elsewhere. I have a custom permission on my model, can_key, and this is registered properly. When I try to add this permission to a newly created user, it's not added. from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission def create_dummy_user(self, username): username = 'dummy_user' user = get_user_model().objects.create(username=username, password='asdf4321') user.save() user = get_user_model().objects.get(username=username) permission = Permission.objects.get(codename="can_key") print(permission) user.user_permissions.add(permission) user = get_user_model().objects.get(username=username) print(f"{user.username} is_active - {user.is_active}") print(f"{user.username} has perm {permission.codename} - {user.has_perm(permission)}") return user This is the print outputs test_web | main_app | record case | Can key record case test_web | dummy_user is_active - True test_web | dummy_user has perm can_key - False So the user was created and the permission exists / is retrieved, but the permission isn't being added. Why? -
The styles and javascript files aren't showing when deploy Django application to a2hosting CPanel
I've deployed my Django application to the a2hosting web hosting the styles aren't showing. Also, the page that has swagger documentation is blank and doesn't have anything. Here in the image, you can see how the Admin page is showing. admin page I've made collectstatic and here is the setting.py configurations: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
How to send emails using Django All auth?
I'm trying to send emails for signup/account verification etc using django allauth, and it has worked correctly during development using the console as the email backend, however now I'm trying to send emails in using gmail, I'm getting the below error: SMTPAuthenticationError at /accounts/password/reset/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials q1-20020adfdfc1000000b0022e049586c5sm11068760wrn.28 - gsmtp') I've tried following the steps in the article mentioned in the error message, but they haven't worked. Not sure what I'm doing wrong, any help would be much appreciated! EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = '*****' -
Django Rest Framework: Not sending email from react form Error 400
I'm trying to send a form using the API endpoint beneath. The problem is that I get a 400 error when I use my react based application. If I'm using the api endpoint page it works. I checked the payload and the only difference seems to be that i'm not sending a csrf token in my react app. So far it was never neccesary when i used model serializers. I believe it is something inside the serializer but i cannot pin it down. Does anyone know what might be causing the 400 error? sendEmail.js const testmessage = "This is a test message" const testemail = "dsfds@dsfg.de" const clientnametest = "name" function sendProposal(values) { console.log("start sending proposal..."); setSendProp(true) const data = new FormData() data.append("Clientname", clientnametest || ""); data.append("Sender", testemail || ""); data.append("Message", testmessage || ""); axios.post(API.email.proposal, data, { headers: { "Authorization": `Bearer ${accessToken}`, 'Accept' : 'application/json', }, withCredentials: true, }) .then(res => { }) .finally(() => { setSendProp(false) }) success() } views.py class ProposalEmailView(APIView): permission_classes = [IsAuthenticated] serializer_class = ProposalEmailSerializer def post(self, request, *args, **kwargs): serializer_class = ProposalEmailSerializer(data=request.data) if serializer_class.is_valid(): data = serializer_class.validated_data ClientName = data.get('ClientName') Sender = data.get('Sender') Message = data.get('Message') send_mail('Contact Form mail from ' + ClientName, Message, Sender, … -
An admin view should be created to view the saved data.Create a employee database and create following api's
Add new employee Get employee by emp_id delete employee by id update employee salary -
How to validate unique attribute values of an object in respect to that object's other attributes?
I am making a school management system where each student takes 6 subjects. After trying to make dependent dropdown lists, I felt like it wasn't suited for what I was trying to achieve and I failed to implement them. I want to validate that each student's attributes concerning the subjects they're taking is unique, so that there aren't any subjects being taken twice (e.g. to prevent having Chemistry in science and Chemistry in science2) models.py from unittest.util import _MAX_LENGTH from django.db import models from django.utils.translation import gettext_lazy as _ from students.choices import * from django.core.exceptions import ValidationError # Create your models here. class Student(models.Model): def __init__(self, student_number, first_name, last_name, email, english, math, language, science, science2): self.student_number = student_number self.first_name = first_name self.last_name = last_name self.email = email self.english = english self.math = math self.language = language self.science = science self.science2 = science2 def __len__(self): return len(vars(self)) student_number = models.PositiveIntegerField() first_name = models.CharField(max_length=50) #Attribute containing student's first name, cannot exceed 50 characters last_name = models.CharField(max_length=50) #Attribute containing student's last name, cannot exceed 50 characters email = models.EmailField(max_length=100) #Attribute containing student's email, cannot exceed 100 characters #Subjects english = models.CharField(max_length=2, choices=English.choices, null=True, blank=False) math = models.CharField(max_length=2, choices=Math.choices, null=True, blank=False) language = models.CharField(max_length=1, … -
How can I update node version in docker container?
Now, I am developing some personal fullstack project using react, django, postgres and docker. I first use node version 8 but now I try to use node version 16. I tried like this. FROM buildpack-deps:bullseye ENV NODE_VERSION 16.18.0 RUN mkdir /code WORKDIR /code But when I check node version in docker shell, it still shows node 8.17.0 How can I fix that? I look forward to your great help. -
How to make REST API for booking 30 min slots. I have tried using django but it is confusing. any link would be helpful
REST API 30-minute timeslots available to schedule an appointment with a particular room. -
Django many to many field keeps adding every instance to itself
I have model "post" and model "profile". I need to add likes to the post, so I did "ForeignKey" at first, now I have ManyToMany relationship, but I keep seeing how every possible instance of "profile" is automatically being added to every instance of "post". Why is it happening? I didnt have problems like that in my previous projects. models.py for profile from django.db import models from django.conf import settings from django.contrib.auth.models import User class Profile(models.Model): """Fields that can be used to modify the profile page""" name = models.CharField(max_length=50, null=True, blank=True) bio = models.TextField(max_length=160, null=True, blank=True) profilePicture = models.ImageField(null=True, blank=True, upload_to='profiles/', default='default/default-pfp.jpg') """Technical fields unaccessable for users""" owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name='account') following = models.ForeignKey("self", on_delete=models.DO_NOTHING, blank=True, null=True, unique=False) def __str__(self): str=self.owner.username str=str + "'s profile" return str model.py for pot from django.db import models from django.conf import settings from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=360) body = models.TextField() image = models.ImageField(null=True, blank=True) likes = models.ManyToManyField(User, related_name="blog_posts") author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): str=self.author.username str= self.date.strftime("%d/%m %H:%M ") + str + "'s post" return str def date_posted(self): str = self.date.strftime('%H:%M %d/%m/%y') return str [![Admin panel][1]][1] [1]: https://i.stack.imgur.com/rwgBP.png -
How to set a field different from id as primary key in django rest model
I am new to django_rest framework and I am having a problem with setting another field as primary key and then use that field as foreign key in another model. These are my models: class Test(models.Model): test_id = models.CharField(max_length=50, default="A10", primary_key=True) issue_date = models.DateField() total_amount = models.FloatField(max_length=50, default=1.0) class AnotherModel(models.Model): test_identifier = models.ForeignKey(Test, on_delete=models.CASCADE) #The identifier refered_date = models.DateField(auto_now_add=True, blank=True) But when I try to create an AnotherModel in admin page it shows this error: IntegrityError at /admin/api/anothertest/add/ FOREIGN KEY constraint failed My question is how can I make the test_id primary key and use it as foreign in second model? -
Django-Extra-Views: Inlines child model gets author none. How do I set it the same as the parent?
I have been spinning my wheels on this issue for a day or two. I have django web application that has 3 models users/models.py: from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User # Create your models here. class ExtendedUser(models.Model): user=models.OneToOneField(User,null=True, on_delete=models.CASCADE) def full_name(self): return (self.user.get_full_name()) def __str__(self): return self.user.get_full_name() @receiver(post_save, sender=User) def create_or_update_user_extendeduser(sender, instance, created, **kwargs): if created: ExtendedUser.objects.create(user=instance) instance.extendeduser.save() playground/models.py: class Customer(models.Model): def __str__(self): return self.Customer_Name Customer_Name = models.CharField(max_length=100) SFDC_Customer_Record_Number = models.IntegerField(default='') Zone = models.CharField(max_length=50, default='') Government = models.BooleanField(default=False) date_posted = models.DateTimeField(default=timezone.now) customerauthor = models.ForeignKey(ExtendedUser, on_delete=models.DO_NOTHING,default=ExtendedUser) def get_absolute_url(self): return reverse('playground-home') class Vue_Quote(models.Model): def __str__(self): return self.Quote_Name Quote_Name = models.CharField(max_length=100) SFDC_Golden_Opp_ID = models.IntegerField() Vue_System_Count = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(ExtendedUser, on_delete=models.DO_NOTHING,default=ExtendedUser,blank=True,null=True) Quote_Type = models.CharField(max_length=100) Customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING, default='') def get_absolute_url(self): return reverse('quote-detail',kwargs={'pk': self.pk}) I am using the 3rd party application django-extra-views to create a single form which allows a user to create a customer and quote at the same time. Views.py: class QuoteInline(InlineFormSetFactory): model = Vue_Quote fields = ['Quote_Name','SFDC_Golden_Opp_ID','Vue_System_Count','Quote_Type',] factory_kwargs = {'extra':1} class CreateQuoteInlinesView(CreateWithInlinesView): model = Customer inlines = [QuoteInline] fields = ['Customer_Name','SFDC_Customer_Record_Number','Zone','Government'] template_name= 'quote_and_customer.html' def forms_valid(self, form, inlines): form.instance.customerauthor = ExtendedUser.objects.get(user=self.request.user) return super().forms_valid(form,inlines) All of this is working … -
When to use savepoint = False in django transactions?
I can use inner atomic blocks as savepoints and catch inner savepoint errors. This way, we proceed within the atomic outer scope, just rolling back the inner atomic block, as explained in this question, but there is this argument savepoint=False that I don't see any use case for. In the docs: You can disable the creation of savepoints for inner blocks by setting the savepoint argument to False. If an exception occurs, Django will perform the rollback when exiting the first parent block with a savepoint if there is one, and the outermost block otherwise. Atomicity is still guaranteed by the outer transaction. This option should only be used if the overhead of savepoints is noticeable. It has the drawback of breaking the error handling described above. If I understand correctly, it will just change the fact that even catching an error from the inner block, the outer scope will still rollback. Is it correct? -
Serializer user "Invalid data. Expected a dictionary, but got User"
I am trying to display the fields of my user model but I always get that my serializer is not valid { "non_field_errors": [ "Invalid data. Expected a dictionary, but got User." ] } this is my model from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin class UserManager(BaseUserManager): def _create_user(self, username, password, is_staff, is_superuser, **extra_fields): user = self.model( username=username, is_staff=is_staff, is_superuser=is_superuser, **extra_fields ) user.set_password(password) user.save(using=self.db) return user def create_user(self, username, password=None, **extra_fields): return self._create_user(username, password, False, False, **extra_fields) def create_superuser(self, username, password=None, **extra_fields): return self._create_user(username, password, True, True, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True) email = models.EmailField( max_length=255, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) age = models.PositiveIntegerField() is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] def __str__(self): return f"{self.id} {self.name} {self.username} {self.age}" this is my serializer class UserUpdateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'email', 'username', 'name', 'age'] this is my view class UserUpdateApiView(APIView): def get(self, request, pk): try: queryset = User.objects.get(pk=pk) serializer = UserUpdateSerializer(data=queryset) if serializer.is_valid(raise_exception=True): return Response(data=serializer.data) except User.DoesNotExist: return Response(data={"error": "User no found"}, status=status.HTTP_404_NOT_FOUND) -
How can i access the count of a field in Django model?
I want to display the total revenue which equals total price, and total price is a field in the appointments model i want the count of that specific field so i can display it in the html. HELP! The Appointment model -
Insert an HTML icon within a Javascript new div
In this Django project, there is a Javascript function creating a new div in which we display some data. for (var i = 0; i < files.length; i++) { var newDiv = document.createElement('div'); newDiv.setAttribute("class","files_div"); //Call the helper function to check if it's a PDF newDiv.setAttribute("onclick","check_files(this)") console.log(files[i]) //Print the files newDiv.innerHTML = files[i]; divParent.appendChild(newDiv); } I need to add icons next to this data. For example, a pdf icon if it's a pdf file. How do you add icons in Javascript once a new div is created? -
Mock Chained DB query in Django unit test
I have a function that allows users to create a new entry in DB. But before that, I had a check if the user's existing records are less than the permissible range. Below is the function implementation def is_allowed_to_create(permissible_range): count = MyModel.objects.filter(query)[:permissible_range].count() return not count >= permissible_range Inside the test file, I am doing @mock.patch('MyApp.models.MyModel.objects') def test_is_allowed_to_create(self, mock_qs, *args, **kwargs): mock_qs.filter.return_value = mock_qs mock_qs.count.return_value = 10 self.assertTrue(is_allowed_to_create(5)) And the error I am getting is TypeError: '>=' not supported between instances of 'MagicMock' and 'int'. So what I understood from the error is, my code is not setting the proper return value for the entire DB query ie MyModel.objects.filter(query)[:permissible_range].count() . How can I set mock value for MyModel.objects.filter(query)[:permissible_range].count() as an integer. Thanks! -
Django - Aggregate into array
I have the a django model with the below data: Name Value A 1 B 2 B 4 C 7 C 5 I would like to use an aggregate my table so that I can get my data in the below format: Name Value A 1 B [2,4] C [7,5] How do I do this with Django. I'm thinking this may be the answer but Django doesn't seem to have ArrayAgg. This looks to be a Django Postgres function Test_Model.objects.annotate(dname=ArrayAgg('name')).values() Do you know how I can achieve this using native Django functions and solutions? Thank you! -
Django CharField with dynamic default value
I want to add a new field to a PostgreSQL database. It's a not null and unique CharField, like dyn = models.CharField(max_length=50, null=False, unique=True) The database already has relevant records, so it's not an option to delete the database reset the migrations wipe the data set a default static value. How to proceed? -
What does Ajax really look like?
I just researching about Ajax for afew day (To use with Django Python framwork) But I found many result about Ajax. 1. function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("GET", "ajax_info.txt", true); xhttp.send(); } $.ajax({ type: "POST", url: actionUrl, .... }); fetch("api/xxx", { method: "post", } .then(...) Does 3 of these is the same? -
How can I re-build my Django Framework Sitemap?
I did my Django Sitemap, and it works in its sitemap.xml file, but I made some changes by adding more URLs to the map, even if I migrate them, my sitemap does not update. I've tried to create another branch and recreate everything, I've tried refresh_sitemap but it is not accepted. I really do not know how to rebuild it and I tried many things. -
using contents within a Django Zip File
I was sent a Django Project from a friend and want to start working on it. I'm mostly a JS developer but was wondering if there was an npm i equivalent for django that will download everything I need? Thanks in advance -
How to add a dropdown select to the django admin search form?
Is it possible to customize the django admin search form by adding a custom select input based on which later filter the queryset? 1 - Extended search_form.html for a given model admin {% load i18n static %} {% if cl.search_fields %} <div id="toolbar"><form id="changelist-search" method="get"> <div><!-- DIV needed for valid HTML --> <label for="searchbar"><img src="{% static "admin/img/search.svg" %}" alt="Search"></label> <input type="text" size="40" name="{{ search_var }}" value="{{ cl.query }}" id="searchbar" autofocus> <input type="submit" value="{% trans 'Search' %}"> # start of custom code <label for="search-type">Typ vyhledávání:</label> <select name="search-type" id="search-type" form="changelist-search"> <option value="all">Vše</option> <option value="pn">PN</option> <option value="email">Email</option> <option value="order-id">Id objednávky</option> </select> # end of custom code {% if show_result_count %} <span class="small quiet">{% blocktrans count counter=cl.result_count %}{{ counter }} result{% plural %}{{ counter }} results{% endblocktrans %} (<a href="?{% if cl.is_popup %}_popup=1{% endif %}">{% if cl.show_full_result_count %}{% blocktrans with full_result_count=cl.full_result_count %}{{ full_result_count }} total{% endblocktrans %}{% else %}{% trans "Show all" %}{% endif %}</a>)</span> {% endif %} {% for pair in cl.params.items %} {% if pair.0 != search_var %}<input type="hidden" name="{{ pair.0 }}" value="{{ pair.1 }}">{% endif %} {% endfor %} </div> </form> </div> {% endif %} 2 - I need to get the selected option from the select html tag when submitted. …