Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Add field with default value, without triggering full rewrite of table?
I want to add new field in existing model current Model class InfoModel(models.Model): id = models.UUIDField(default=uuid.uuid4) New Model where I want to add new field count class InfoModel(models.Model): id = models.UUIDField(default=uuid.uuid4) count = models.IntegerField(default=0) this model creates following migration file from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('info', '0001_auto_20220303_1048'), ] operations = [ migrations.AddField( model_name='infomodel', name='count', field=models.IntegerField(default=0), ), ] but If I migrate using above migration file it will trigger full table overwrite for existing rows. how can I avoid it? I tried suggestion from documentation https://docs.djangoproject.com/en/4.0/ref/migration-operations/#addfield not sure, If I did it correctly by creating 2 migrations file because after second migration it was still filling default value for existing rows. I want only new entry into model should have default value, existing rows not required. -
django m2m form is not saving although using form.save_m2m()
i have manyToMany relationship with two models: researcher and program class Program(BaseModel): researcher = models.ManyToManyField('researcher.Researcher',blank=True ,verbose_name=_('Researchers')) i was trying to add some researchers to the program so that's what i did: self.object = form.save(commit=False) researchers=[] for uuid in researchers_uuid: researcher=Researcher.objects.get(uuid=uuid) researchers.append(researcher) self.object.bounty_type = bounty self.object.researcher.set(researchers) logger.info(self.object.researcher.all()) ## => 1 self.object.save() form.save_m2m() logger.info(self.object.researcher.all()) ## => 2 the first logger gives me all the researchers, while the other one give me an empty QuertSet so, how can i save an m2m relationship? and what's wrong in my code -
Django - Cannot assign "<Product: Test Product>": "Reply.comment" must be a "Comment" instance
I'm trying to add a commenting and replying system to my products model. I'm getting a Cannot assign "<Product: Test Product>": "Reply.comment" must be a "Comment" instance. error at new_reply = Reply(content=content, author=self.request.user, comment=self.get_object()) views.py: class ProductFeedbackView(DetailView): model = Product template_name = 'store/product_feedback.html' def get_context_data(self , **kwargs): data = super().get_context_data(**kwargs) connected_comments = Comment.objects.filter(product=self.get_object()) number_of_comments = connected_comments.count() data['comments'] = connected_comments data['no_of_comments'] = number_of_comments data['comment_form'] = CommentForm() connected_replies = Reply.objects.filter(comment=self.get_object()) number_of_replies = connected_replies.count() data['replies'] = connected_replies data['no_of_replies'] = number_of_replies data['reply_form'] = ReplyForm() return data def post(self , request , *args , **kwargs): if self.request.method == 'POST': reply_form = ReplyForm(self.request.POST) if reply_form.is_valid(): content = reply_form.cleaned_data['content'] new_reply = Reply(content=content, author=self.request.user, comment=self.get_object()) new_reply.save() return redirect(self.request.path_info) if self.request.method == 'POST': comment_form = CommentForm(self.request.POST) if comment_form.is_valid(): content = comment_form.cleaned_data['content'] new_comment = Comment(content=content, author=self.request.user, product=self.get_object()) new_comment.save() return redirect(self.request.path_info) models.py: class Product(models.Model): author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) title = models.CharField(max_length=120, unique=True) description = models.CharField(max_length=300, blank=True, null=True) class Comment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.CharField(max_length=200, null=True, blank=False) class Reply(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.TextField(null=True, blank=False) -
The timezone application in django is not working even when I have it configured in the settings
The TIME_ZONE of my application in django is currently not working I have been reading about it and what I currently have in the settings of my application corresponds to what is in the django documentation, the configurations are the following: TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = True USE_TZ = True Now when I try to use timezone.now() , imported from django.utils import timezone , I get this in the following code The output is this As you can see, the timezone.now() brings me a completely different time than it should be, and I test that with date_now . I don't understand why if I'm using TIME_ZONE = 'Europe/Paris' in the application settings it doesn't bring me the exact time of the city. On the other hand a possible solution would be to use this But if I use this I would have to change in all parts of my application to put timezone.localtime(timezone.now()) when according to the documentation just using timezone.now() should work -
Django style active element url in for loop
{% for i in menu_categories %} <a href="{% url 'category' i.slug %}" class="mr-4 font-light{% if i.slug == url_name %}text-emerald-500 text-3xl{% endif %} hover:text-emerald-600"> {{ i.title }} </a> {% endfor %} I was looking for similar questions, but I didn’t check the url in the for loop. What's wrong? -
Can i add a edit button in my list display in django admin page
[I want to add edit button beside price attribute][1] -
Is it possible to save data directly to django without using forms?
If I have a model like this: class SomeClass(models.Model): title = models.CharField(max_length=100) field1 = models.FloatField() field2 = models.FloatField() field3 = models.FloatField() field4 = models.FloatField() field5 = models.FloatField() def __str__(self): return self.title and I have a set of data, for example data_list = ('title', 10, 20, 30, 40, 50) How can I save data directly without asking for input to user, or using forms? thanks -
Django saves as Object (1) instead of value?
Am using ModelChoiceField in form and trying to save the form but it saves as Object (1) and Object (2) instead of data name. I know that i can change that by adding def __str__(self): return self.name to the model, but i dont want to change this as its connected with other things. Is there any other way to attain this without adding str to model ? My model: class TrendingCourse(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) course = models.CharField(max_length=256) course_slug = models.CharField(max_length=256) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now = True) And my form: class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.name class CourseForm(ModelForm): course_slug = forms.CharField(widget=forms.TextInput({'class': 'form-control'}), required=False) course = MyModelChoiceField(queryset=Course.objects.filter(owner_id=2), widget=forms.Select(attrs={'class': 'form-control form-select', 'data-placeholder':'Select any trending course'})) class Meta: model = TrendingCourse fields = [ 'course', 'course_slug' ] -
Accept only authentificated requests to backend
I have this question. I am quite new in this area. I have web app. This consist of services deployed on Docker engine. The main services/containers are: Frontend : React on Nginx web server Backend (API) : Django, DRF on gunicorn on Nginx For frontend I use Auth0 provider. It works as expected. If user is not authenticated/authorized it is redirected to login page. Now I want also to "secure" my backend that it only would accept authenticated connections from frontend. For backend (Django) I also have CORS enabled (django-cors-headers package), but I still can connect from my browser my-site/api/ and get the response. Does anybody know which strategy should I use. Should I somehow secure it using JWT tokens. Somehow pass it to backend in my request? -
Using OR in if statement to see if either query param present
I am looking to implement a simple filter using a single query param (eg age=gt:40, name=eq:bob). I am wondering if it is possible to check if either name or age is present in the GET request at once? An example might clarify what I'm after: if ('age' or 'name') in request.GET: This will only match when the first one is used. When I hit the endpoint with the query param name it doesn't match true. I know I could do something like: if ('age' in request.GET) or ('name' in request.GET) : but this could grow quite quickly and become ugly. -
Django prefetched attribute returns null value
The requirement is to have subtopics prefetched at the Campaigns queryset as the attribute prefetched_subtopics but it currently returns null Models class SubTopic(Base): name = models.CharField(max_length=100, unique=True) class CampaignSubTopicAssn(HistoryMixin, Base): campaign = models.ForeignKey(Campaign, related_name='subtopic_assn', on_delete=models.CASCADE) subtopic = models.ForeignKey(SubTopic, related_name='campaign_assn', on_delete=models.PROTECT) View def get_queryset(self): return super(CampaignViewSet, self).get_queryset().prefetch_related(Prefetch('subtopic_assn', queryset=CampaignSubTopicAssn.objects.prefetch_related(Prefetch('subtopic', queryset=SubTopic.objects.all(), to_attr='prefetched_subtopics')))) -
CSRF verification failed. Request aborted. in django rest framework
halo i'm working on a project, using drf, but i'm getting CSRF verification failed. Request aborted at first everything was working, but now when i test my api i keep keep getting,CSRF verification failed below is my setting codes REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), 'DATE_INPUT_FORMATS': [("%Y-%m-%d")], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } can anyone help out -
CORS error on React with Django deployed on heroku
I've been trying to use React + Django rest framework I've deployed the API on heroku and configured the settings.py with django-cors-headers, My settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', 'account', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True but when I make a post request with React on localhost I get: login:1 Access to XMLHttpRequest at 'myapi' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. My React: const login = async (email, password) => { const response = await createSession(email, password); console.log('login', response.data); const loggedUser = response; const token = response.data.access; localStorage.setItem('user', JSON.stringify(loggedUser)); localStorage.setItem('token', token); api.defaults.headers.Authorization = Bearer ${token}; setUser(loggedUser); navigate('/'); }; -
Django 3.2 formsets - how to filter product by the list of components that belong to this product?
I am trying to create a formset where the user will be able to do the following: Click on the button and display formset that is relevant to this particular product. I want to display all products and all components after page is loaded so user will see which components belong to which products. Once the user will select the product formset will expand and the user will be able to put a number of units. After inserting all numbers of units in all forms user should click Submit and all forms should be saved at once. QUESTION: How to connect components in each formset to button so after expanding it will show components that are related only to this product. I managed to filter components by creating a loop in my initial method but I am not sure how to make it dynamic. My idea was to somehow filter all components in each product based on product slug value in the data-bs-target attribute but I am not sure how to do it. My second question is how can I make 1 formset so the user will need to click submit button only once? class CostCalculatorView(TemplateView): template_name = "cost_calculator.html" def … -
How to display multiple photos via API
models.py class UserRoom(models.Model): objects = None categoty = [ ('President Lux', 'President Lux'), ('Lux', 'Lux'), ('Double', 'Double'), ('Standard', 'Standard'), ] name = models.CharField(max_length=150, choices=categoty, verbose_name='Категория') room_num = models.CharField(max_length=150) about = models.TextField(verbose_name='Подробности') price = models.IntegerField(verbose_name='Цена') img360 = models.FileField(verbose_name='Фотография в 360') class Meta: verbose_name = 'Номер (About)' verbose_name_plural = 'Номера (About)' class UserImg(models.Model): name = models.ForeignKey(UserRoom, on_delete=models.CASCADE, verbose_name='img2') img = models.FileField(upload_to='User img', verbose_name='Фотография') how to write in serializers.py so that all data from the database is displayed? how to write in serializers.py so that all data from the database is displayed? now when I connect serializers.py it displays either only the first model or pictures from the second and ID of the attached model class UserRoomSer(ModelSerializer): class Meta: model = UserRoom fields = '__all__' -
sql query or django filter for string
hello i need a query that search in database and return a row that has most similarity from starting character with a value. imagine, given string is 'abcdefghijklmnop' our database table has a column named x and for this column, rows are: 1- 'a' 2- 'abc' 3- 'absde' 4- 'abcdef' 5- 'abcdefg' 6- '1abcdefg' and it should return the row number 5 -
Django select_related doesn't optimize query
I have a problem with select_related. I don't know what I'm doing wrong but it doesn't work. models.py class OrganizerUser(models.Model): """This user manage Agents""" user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.user.username class Agent(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) organizer = models.ForeignKey(OrganizerUser, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.user.username class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) age = models.IntegerField(default=0) organizer = models.ForeignKey(OrganizerUser, on_delete=models.CASCADE) agent = models.ForeignKey(Agent, null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey( Category, related_name="categories", null=True, blank=True, on_delete=models.SET_NULL ) description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) phone_number = models.CharField(max_length=20) email = models.EmailField() converted_date = models.DateTimeField(null=True, blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" views.py class LeadsApiView(generics.ListCreateAPIView): serializer_class = LeadSerializer permission_classes = [IsAuthenticated, IsAdminOrOrganizer] def get_queryset(self): user = self.request.user #if user.is_staff: #return Lead.objects.select_related('organizer', 'agent').all() if user.is_organizer: return Lead.objects.select_related('organizer').filter( organizer=user.organizeruser) else: return Lead.objects.select_related('agent').filter(agent=user.agent) for agents everything is fine. Django makes 3 queries but for other users, it makes extra queries for each existing user. -
Cannot query "Product": Must be "Comment" instance
I'm trying to add a commenting and replying system to my products model but I can't add replies to comment. This is being done in the same page where the product details are being shown to the user. views.py class ProductFeedbackView(DetailView): model = Product template_name = 'store/product_feedback.html' def get_context_data(self , **kwargs): data = super().get_context_data(**kwargs) connected_comments = Comment.objects.filter(product=self.get_object()) number_of_comments = connected_comments.count() data['comments'] = connected_comments data['no_of_comments'] = number_of_comments data['comment_form'] = CommentForm() connected_replies = Reply.objects.filter(comment=self.get_object()) number_of_replies = connected_replies.count() data['replies'] = connected_replies data['no_of_replies'] = number_of_replies data['reply_form'] = ReplyForm() return data models.py class Product(models.Model): author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) title = models.CharField(max_length=120, unique=True) description = models.CharField(max_length=300, blank=True, null=True) class Comment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.CharField(max_length=200, null=True, blank=False) class Reply(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.TextField(null=True, blank=False) -
How implement django.views.generic if earlier used request[Django]
How implement Django.views.generic if earlier used request? from django.shortcuts import render,redirect from django.http import HttpResponse from .models import * from django.contrib.auth import login,logout,authenticate from .forms import * from django.views.generic import ListView Create your views here. New class HomePage(ListView): model = Book template_name = 'book/templates/home.html' Old def home(request): books=Book.objects.all() context={'books':books} if request.user.is_staff: return render(request,'book/templates/adminhome.html',context) else: return render(request,'book/templates/home.html',context) -
Django test uses wrong database in some cases
I try to setup my Django tests, and I noticed that when I run all tests TestRunner uses correct test database (for all aliases): docker-compose exec my_project python manage.py test --keepdb from django import db from django.test.runner import DiscoverRunner from apps.settings.models import Settings class KeepDBTestRunner(DiscoverRunner): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.verbosity = 2 self.keepdb = True self.db_base_name = 'test_postgresdevuser' def run_checks(self): super().run_checks() print(db.connections.databases) ---------------------------------------------- result ---------------------------------------------- {'default': {'NAME': 'test_postgresdevuser', 'USER': 'user', 'PASSWORD': '*******', 'HOST': 'postgres', 'PORT': 5432, 'ENGINE': 'apps.core.db_backends.open', 'TEST': {'SERIALIZE': False, 'DEPENDENCIES': [], 'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None}, 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None}, 'vk_master': {'NAME': 'test_postgresdevuser', 'USER': 'user', 'PASSWORD': '*******', 'HOST': 'postgres', 'PORT': 5432, 'ENGINE': 'apps.core.db_backends.open', 'TEST': {'SERIALIZE': False, 'DEPENDENCIES': [], 'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None}, 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None}, But when I run tests for specific module, it uses the original database: docker-compose exec my_project python manage.py test --keepdb apps.my_module ... print(db.connections.databases) ---------------------------------------------- result ---------------------------------------------- {'default': {'NAME': 'postgresdevuser', 'USER': 'user', 'PASSWORD': '*******', 'HOST': 'postgres', 'PORT': 5432, 'ENGINE': 'apps.core.db_backends.open', 'TEST': {'SERIALIZE': False, 'DEPENDENCIES': [], 'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None}, 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': … -
How to check model fields type?
I have an API class that we use across our app that lets us to simplify HTTP request and create new API end points by just assining what model to use, without needing to write custom handler for each model request. However, I want to include wildcard searches in the requests, so I want to be able to check if the model field is a text field and if it is, check the given field for wild cards. I know how to do deal with wild cards and do wild card searches, but I want to know how I can check if the any given field is a text field? To give pseudocode example, what I roughly want to do: model = ModelWeAreUsing for field in search_terms: if model[field] is TextField: doTextField() else: doGenericField() -
model instance not getting created on triggering signals post save when tested with pytest
While i was trying to test my model, it was linked to a signals file where when.save() is called on that model, the signals file is triggered and then a instance on different model is also created in that signals file. But when i try to test with Py-test, factory boy and fixtures the instance that was getting created in the signals file for different model is not triggered. Below is the code for reference: signals.py @receiver(post_save, sender=Candidate, dispatch_uid="create_candidate_user") def create_candidate_user(instance, **kwargs): """ Create candidate user does not exist """ if instance.user is None: try: user = None if instance.email or instance.mobile: email_user = None mobile_user = None mobile = instance.mobile if instance.mobile and not instance.mobile.startswith("+"): mobile = f"+91{instance.mobile}" if instance.email: try: email_user = User.objects.get(email=instance.email) except User.DoesNotExist as ode: print(ode, f"for {instance.email}") if mobile: try: mobile_user = User.objects.get(mobile=mobile) except User.DoesNotExist as ode: print(ode, f"for {mobile}") if email_user and mobile_user: if email_user != mobile_user: raise Exception( f"Duplicate Users found! ids are: {email_user.id} and {mobile_user.id}" ) else: user = email_user elif email_user or mobile_user: if email_user is not None: user = email_user if mobile: user.mobile = mobile if mobile_user is not None: user = mobile_user if instance.email: user.email = instance.email else: query … -
Access delete method body send via axios.delete
I am building a react-django simple blog app and I am trying to delete blog post but I also want to send body with delete to backend But I have no idea, How can I access delete body ?. I can do with post like self.request.POST with how with delete ? App.js class BlogPost extends React.Component { deleteBlog = (blog_title) => { const body = ({title: blog_title}); const headers = { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json", } axios.delete("delete_blog/", blog_title, {headers:headers}).then(res => {console.log}) } render() { return ( <div> { this.state.blogs.map(res => <div> {res.blog_title} <button onClick={() => deleteBlog(res.blog_title)}></button> </div> } </div> )}} views.py class BlogPost(APIView): def post(self, *args, **kwargs): ....... def delete(self, *args, **kwargs): # Trying to access delete body here...... print(self.request.POST) # It printed empty dict like <[QueryDict = {}]> I have tried many times but it is still not showing. Any help would be much Appreciated. Thanks You in Advance. -
Best way to get cords of Html elements around canvas?
I am trying to make a dynamic graph that changes based on the numbers it receives and have the last 5 business days on the X axis and the prices on the y axis. This is all on the edge of a canvas I was wondering what the best approach to getting the coordinates of the html elements were to dynamically draw the lines. Here is my html <div class="homepage-relativePrices"> <p id="first_highest">{{ first_highest }}</p> <p id="second_highest">{{ second_highest }}</p> <p id="third_highest">{{ third_highest }}</p> <p id="fourth_highest">{{ fourth_highest }}</p> <p id="fifth_highest">{{ fifth_highest }}</p> </div> <canvas id="homepage-stockGraph" style="background-color: white;"></canvas> <!--Last 5 Business days from 4 days ago to today--> <div class="homepage-dayDisplays"> <p id="four_days">4D</p> <p id="three_days">3D</p> <p id="two_days">2D</p> <p id="one_days">1D</p> <p id="today">Today</p> </div> and the drawLine function I have been playing around with const canvas = document.getElementById('homepage-stockGraph'); const ctx = canvas.getContext('2d'); function drawLine(el, el2){ ctx.strokeStyle = 'black'; ctx.lineWidth = 1; ctx.beginPath(); ctx.lineTo(x, y); ctx.moveTo(x2, y2); ctx.stroke(); } Canvas with elements around it -
Django - Query with extra method that use python Function
I would like to make a query in Django that use a function that take parameters from db e from python program. The function is shown below: > def myFunc(a, b): > val = mathematical expression with a and b > return val I would like that: a comes from myTable (represent the field 'num') b comes from python Code class myTable(models.Model): num = models.IntegerField(default=0) I would like to do a query similar to this in views.py: b = 4 #it must be variable c = 10 #it must be variable myTable.objects.all().extra(select = {'new_param' : myFunc(num , b)}, where = ['new_param > %d'], params = [c]) How can I do that? Thanks