Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Assign values to Django form fields without using initial? [closed]
Im tryin to create a django form with two int(Salary, days) and one disabled fields(Total). I want it to work in a way when user clicks on submit it prompts the user with Total salary in that disable field. I tried doing it using clean method, didnt work. Is there any other way to do it!? -
Django Rest Framework Serializer do not want to accept returned list, and returns AttributeError 'str' object has no attribute 'x'
So I'm trying to aggregate a list of colors and return the queryset to the serializer, the serialzier, however, does not seem to accept this for some reason. When running the the commands in shell i get: >>> from django.contrib.postgres.aggregates import ArrayAgg >>> from inventory.models import Product >>> products = Product.objects.filter(category__parent__name__iexact='fliser').distinct().aggregate(colors_field=ArrayAgg('colors__name')) >>> print(products) {'colors_field': ['Beige', 'Grå', 'Hvit', 'Sort', 'Beige', 'Gul', 'Rød']} Which is the expected result. The serializer is structured like this: class ProductFiltersByCategorySerializer(serializers.ModelSerializer): """ A serializer to display available filters for a product lust """ colors = serializers.StringRelatedField(read_only=True, many=True) class Meta: model = Product fields = ['colors'] The viewset looks like this: class ProductFiltersByCategory(generics.ListAPIView): """ This viewset takes the category parameter from the url and returns related product filters """ serializer_class = ProductFiltersByCategorySerializer def get_queryset(self): category = self.kwargs['category'] queryset = Product.objects.filter(category__parent__name__iexact=category).distinct().aggregate(colors_field=ArrayAgg('colors__name')) return queryset And the relevant part of the model looks like this: class Product(models.Model): ... colors = models.ManyToManyField( ProductColor, related_name='product_color' ) ... The error when trying to access the endpoint is 'str' object has no attribute 'colors'. -
Django in GAE - OAuth 2.0 redirecting to localhost - authorization problem
I am quite new to python and especially app deployment. My goal is to create an app that is using multiple Google APIs and running on a schedule. For testing purposes, I created a django app which is simply appending a row into a Google Sheet with the current timestamp. I created the Google API credentials for an installed app, as I want this script to run in the background. Everything is working fine when running the app on the localhost: I visit the localhost path which is triggering the script and I'm redirected to the Google authentication page. After authorization, I end up and the "you may close this window" page and the testing Google Sheet is appended correctly. However, when I deploy the app on App Engine, I see the authorization screen, but after the confirmation I am redirected to the localhost, and get the warning: "this site can't be reached localhost refused to connect". As for the credentials JSON, the following redirect_uris are listed: ["urn:ietf:wg:oauth:2.0:oob","http://localhost"] But I also tried removing the localhost from there, without a result. My goal is to have an app which is using Google Sheets as an interface, so I'm not sure if … -
django: password change template customization
I want to change password change template in django but I cant. django is seeing the django/contrib/admin/templates/registration/ versions of the templates instead of my beautifully crafted myapp/templates/registration/password*.html urls.py from django.contrib.auth.views import PasswordChangeDoneView,PasswordChangeView urlpatterns = [ path('password_change/', PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', PasswordChangeDoneView.as_view(), name='password_change_done'), ] setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Django error Invalid block tag on line 21: 'endblock'. Did you forget to register or load this tag? How do i fix it
{% extends 'miromi_first/base_template.html' %} {% load static %} {% block content %} <img src="{% static 'miromi_first/images/miromi_logo.png' %}" /> <div class="topnav"> <div class="topnav-right"> <a href="#about">Login</a> </div> </div> <div class="main-stuff"> <h2>Welcome to Our fashion app</h2> <h4> Lorem ipsum dolor sit amet consectetur adipisicing elit. Natus voluptates nihil corrupti incidunt hic, quasi fugiat quaerat esse veniam sed, blanditiis voluptatem saepe velit eligendi voluptas dicta architecto doloremque magnam. </h4> </div> {% endblock %} I try to load the image i want using this but get the error : Invalid block tag on line 22: 'endblock'. Did you forget to register or load this tag? in django (if i remoce the load static and image URL stuff it works fine -
Get the url from custom tag in beautifulsoup$
I need to get url the from custom html tag. So im extracting the img like this qwe = [] for x in carList: try: carPicture = x.find('img', class_="lazyload", attrs={"data-src":True}) except: carPicture = static("images/human.jpg") qwe.append(carPicture) The result of that is: <img class="lazyload" data-src="https://prod.pictures.autoscout24.net/listing-images/58878dbf-083a-4685-af3a-f745a6534426_cdde08fb-999b-488a-86c8-d252bcadaaff.jpg/420x315.jpg"/> How can i get only the link from data-src tag? -
Django 'User' object has no attribute 'profile' when I'm trying to log in
I had a OneToOne Field relation, but when I added a related name attribute to it, every time I try to log in I get this error: 'User' object has no attribute 'profile' Profile model: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile') weight = models.FloatField(max_length=20, blank=True, null=True) height = models.FloatField(max_length=20, blank=True, null=True) goal = models.FloatField(max_length=20, blank=True, null=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
IntegrityError at /admin/auth/user/11/delete/ FOREIGN KEY constraint failed
when i delete user from my admin panel it shows me given error I dont understand what is the reason of this error or where i am making mistake. I can update and create new users and delete those user who dont have profile but the users which have profiles they are unable to delete because of the following here which i given below. accounts/models.py from django.urls import reverse from django.db import models from django.contrib import auth from PIL import Image from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) class Profile(models.Model): user = models.OneToOneField(auth.models.User, on_delete=models.CASCADE) avatar = models.ImageField(default='1.jpg', upload_to='displays', height_field=None, width_field=None, max_length=None) def __str__(self): return f'{self.user.username} Profile' def save(self,*args, **kwargs): super(Profile,self).save(*args, **kwargs) #it will take data and save it dp = Image.open(self.avatar.path) #storing avatar in variable if dp.height >300 or dp.width >300: output_size =(300,300) #set any size you want dp.thumbnail(output_size) dp.save(self.avatar.path) #after resizing it save it in data base in place of uploaded once by user def get_absolute_url(self): return reverse("Profile_detail", kwargs={"pk": self.pk}) @receiver(post_save, sender=User) def create_profile(sender, created,instance,**kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance,**kwargs): instance.profile.save() accounts/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError … -
create a folder for each user automatically when they first sign-up and saving their files to it
So I am trying to create a folder automatically for each user as soon as they sign up. This is my code: def create_folder(instance): folder = Path("users/myfolder/".format(instance.user)).mkdir(parents= True, exist_ok= True) return folder class MyModel(models.Model): folder_to_upload = models.FileField(upload_to= create_folder, null= True) The folder does not get created unless I upload a file. What I want to achieve is, to create a folder for each user automatically when they first sign-up, so the users can save their files to it. -
post_save signal vs method as property
I am setting up a web app with django, in which I have a model for employee profile, which will handle over 20 thousand entries in the table. I have a requirement to have the reporting line of each employee, which will be derived based on the employee's Reporting Manager's reporting line. I am in contemplation on how to set up the Reporting Line of an employee, as a CharField, to be filled in based on the indicated Reporting Manager with a post_save signal Pros Does not have to be loaded everytime an admin loads up the admin page for Employees Since it is a field (i.e. a column in the table), it can be sorted in the admin page and on queries Cons The reporting lines of subordinates will not get updated when a Reporting Manager gets an update in his/her reporting line (though it is possible to include in the signal to update all subordinates' reporting line as well) as a method declared with a @property decorator, which will always be updated since it is always freshly derived Pros Always updated Cons Worried about the performance of having to re-derive all employees' reporting line whenever the admin page … -
Error: net::ERR_ABORTED 400 (Bad Request) on using AWS File Storage?[Python]
[Using Python Django] hi there I'm using aws filestorage to store files for static folder I'm using S3 bucket(free tier) I think I have established the connection of aws with my project correctly but still I'm getting error of net::ERR_ABORTED 400 (Bad Request) for every page i'm getting from aws -
python manage.py runserver error max recursion error
i am making a simple website with django, using django==2.2.7 on windows(python 3.7). the error is: F:\Arduino\my_new_django_folder\my_blog\blog>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Jigam\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\Jigam\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Jigam\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Jigam\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Jigam\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Jigam\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Jigam\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Jigam\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Jigam\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "C:\Users\Jigam\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "C:\Users\Jigam\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) [Previous line repeated 983 more times] File "C:\Users\Jigam\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\urls.py", line 59, in _load_all_namespaces ':'.join(parents + (url.namespace,)) for url in url_patterns File "C:\Users\Jigam\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\urls.py", line 60, in <listcomp> if getattr(url, 'namespace', None) is not None RecursionError: maximum recursion depth exceeded while calling a Python object The code is just a basic code with HttpResponse. -
django.db.utils.OperationalError: no such table - operating on model inheriting from not managed model
I'm having an issue building database schema for an app which includes model with image and which is being preloaded with some default data. The idea is that when application starts it's being prepopulated with default data (static images) but after that users can upload their own images. To simplify let's say that model has only two fields - shared_one and image: class Some(models.Model): shared_one = models.CharField() image = [???] I tried to define image as FileField but it doesn't work with static files - while creating new record Some model will try to save new file image in MEDIA_ROOT directory. Then I found out that Django introduces field type for managing static files in models - FilePathField but obviously it doesn't comply with files uploaded by users. Then I came up with an idea to make Some as an abstract class like that: class Some(models.Model): class Meta: abstract = True shared_one = models.CharField() class DefaultSome(Some): media = models.FilePathField() class UsersSome(Some): media = models.FileField() The issue with that approach is that DefaultSome and UsersSome are now completely different beings - I cannot for example access media from other model using ForeignKey to Some, I'd need to create different sets of … -
Reverse for 'delete' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['delete/(?P<task_id>[0-9]+)/$']
First time writting to stack. If this problem is so stupid, don't condemn me pls. I need to delete the task from main page. I will be so grateful for the hepl Exception Type: NoReverseMatch Exception Value: Reverse for 'delete' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['delete/(?P<task_id>[0-9]+)/$'] urls.py path('delete/<int:task_id>/', delete_task, name='delete'), or path('delete/<int:task_id>/', TaskDelete.as_view(), name='delete'), models.py def get_absolute_url(self): return reverse("del_task", kwargs={"task_id": self.pk})` views.py def delete_task(requset, task_id): obj = get_object_or_404(Task, pk=task_id) obj.deletete() return render(request, 'task/del_task.html', {"obj ": obj})` or class TaskDelete(DeleteView): model = Task template_name = 'task/del_task.html' success_url = reverse_lazy('home') pk_url_kwarg = 'task_id'` index.html Delete del_task.html {% extends 'base.html' %} <h1>The Task was successfully deleted</h1> -
Django - validate a field exists in list of objects
I'm using DRF serializers. I want to create a field that is a list of objects, while one of the fields in the object is choiceField and is required. I got it working partially, but seems like when this field doesn't exist in the request body, the serializer is_valid() is fine and the object is updated without that field. (But when trying to send a value that is not in the choices, the updating fails. Part of the code: model: class GeneralModel(models.Model): id=models.CharField(max_length=200) my_list_of_objects=JSONField(default=list) GeneralModel serializer: class GeneralModelSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() my_list_of_objects = MyListOfObjectsSerializer(required=False) list_of_objects serializer: class MyListOfObjectsSerializer(serializers.ListField): child = SingleObjectSerializer() single object serializer: MY_TYPES = ( ('1', 'ONE'), ('2', 'TWO'), ('3', 'THREE'), ) class SingleObjectSerializer(serializers.Serializer): id = serializers.CharField(max_length=100) my_type = serializers.ChoiceField(choices=MY_TYPES) As mentioned, it basically works and validates the choices field for example, but it allows updating with no 'my_type' field in the internal object. I've tried also adding this to the GeneralModelSerializer: def validate_my_list_of_objects(self, value): serializer = MyListOfObjectsSerializer(data=value) serializer.is_valid(raise_exception=True) return value But I'm getting an error saying that MyListOfObjectsSerializer doesn't know 'data' -
Add manually field to form already linked in django
For this order app, i have field product linked to Product, but in my case, sometimes i have specified product which not exist on product table, can i add them manually on this order ? class Product(models.Model): name = models.CharField(max_length=64) price = models.FloatField() class Order(models.Model): date = models.DateField(default=timezone.now) number = models.CharField(max_length=64, unique=True) client = models.ForeignKey(Supplier,on_delete=models.CASCADE) class OrderItem(models.Model): order = models.ForeignKey('Order', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) class OrderForm(ModelForm): class Meta: model = Order fields = "__all__" class OrderItemForm(ModelForm): class Meta: model = OrderItem fields = "__all__" -
Append querystring to view render function Django
I got querystring in my view: def my_view(request): query_string = request.GET Then I do some staff in this view. Finally I want to append querystring to URL of view when page rendered completely: return render(request, 'my_template.html', context=context) # Want to add querystring here! In brief I want to append querystring to view render function or something like that. How can I do that? -
Django app served via gunicorn is unable to find custom template tags
I get the classic TemplateSyntaxError at / <custom_template_tag_module> is not a registered tag library when serving my app via the command gunicorn <app_name>.wsgi:application. The application works fine when I serve it using python manage.py runserver. I can import the template tag file in the command prompt (python manage.py shell). The error is ocuring in django/template/defaulttags.py in the find_library routine (at line 1021 for Django version 3.0.10). So it looks like the custom_tag_module isn't being registered. A little piece of extra evidence is that none of my custom template tag modules appear in the list given in the exception. I'm completely lost. Why would registration of a custom tag module be effected by how the website is served? Happy to post code as many code segments as needed to get an answer. I'm just not sure what pieces of code would even be relevant. -
i did same way above djangogirls tutorial but it doesn’t work
<div> <h1><a href="/">Django Girls Blog</a></h1> </div> {% for post in posts %} <div> <p>published: {{ post.published_date }}</p> <h1><a href="">{{ post.title }}</a></h1> <p>{{ post.text|linebreaksbr }}</p> </div> {% endfor %} i was doing this part. after this code i check “blog/templates/blog/post_list.html“ but it dosen’t bring posts. just empty. what did i wrong things. please help. -
How to post list in drf post request via postman
I have a client model that can have multiple numbers like a person can have multiple phone numbers. I want to create a client in my database plus add all of its phone numbers at the same time. just like when a person submits his data in a form. Right now I testing my API in postman but could submit data when number field is added in serializer, GET request is working but I am struggling with post models.py class Client(models.Model): name = models.CharField(max_length=32) departure = models.DateTimeField(default=None, blank=True) arrival = models.DateTimeField(default=None, blank=True) price = models.IntegerField(validators=[MinValueValidator(0)]) def __str__(self): return self.name class Number(models.Model): number = models.IntegerField() client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, related_name='number') serializers.py class NumberSerializer(serializers.ModelSerializer): class Meta: model = Number fields = ('id', 'number') class ClientSerializer(serializers.ModelSerializer): number = NumberSerializer(many=True) class Meta: model = Client fields = ('id', 'name', 'departure', 'arrival', 'price','number') views.py class ClientViewSet(viewsets.ModelViewSet): queryset = Client.objects.all() serializer_class = ClientSerializer authentication_classes = (TokenAuthentication, ) permission_classes = (IsAuthenticated,) This is how I am making a post request via postman and getting error -
Submit Django Form with Foreign Key
I am trying to send a form which would add a new "item"/row in my table Listing using Django. I am sure the issue lays in the fact that I am using a ForeignKey and keep on receiving the following error : ValueError: Cannot assign "'2'": "Listing.category" must be a "Category" instance. Note that the value 2 above is just one of 7 options i have. My "Category" Table defined in Models.py is currently filled as followed: (id) : (category) 7 : Book 6 : Technology 5 : Beauty 4 : Clothing 3 : Health 2 : Sports 1 : Grocery Models.py : class Category(models.Model): category = models.CharField(max_length=16) def __str__(self): return f"{self.id} : {self.category}" class Listing(models.Model): owner = models.CharField(max_length=64) title = models.CharField(max_length=64) description = models.CharField(max_length=256) startingBid = models.IntegerField() link = models.CharField(max_length=1024,blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category_id") time = models.DateTimeField(auto_now_add=True) def __str__(self): return f'"{self.title}" added by {self.owner}' Views.py class Create(forms.Form): CHOICES = ( (1, 'Grocery'), (2, 'Sports'), (3, 'Health'), (4, 'Clothing'), (5, 'Beauty'), (6, 'Technology'), (7, 'Book'), ) owner = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Your Username'})) title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What is your item?'})) description = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Max 256 characters'})) link = forms.URLField(required=False) startingBid = forms.IntegerField() category = forms.ChoiceField(choices=CHOICES) @login_required def create_listing(request): if request.method == … -
ValueError at /accounts/signup/ not enough values to unpack (expected 2, got 1)
I have seen a lot of these questions around here, yet I can't seem to solve my own. In development mode, registering to the site works fine. Just in development mode I get this error when trying to register as a new user: ValueError at /accounts/signup/ not enough values to unpack (expected 2, got 1) I turned debug on to see where this might be coming from but it seems they all refer to files in the site-packages. This is the debug: Debug In other words, I really have no clue where to look right now.. -
Django URL pattern is not working with unicode word/part
I used unicode sting inside my Django app's URL pattern. Everything works fine in local host When i upload and browse for the links it says it didn't matched any of the entire app's urls and throws error. Please help. -
Selenium Django Channels error:ERROR: setUpClass
I'm learnig DJango channels.It says to install Chrome and Chrome driver to work with Silenium. This is test case code and everyething from site: from channels.testing import ChannelsLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.wait import WebDriverWait class ChatTests(ChannelsLiveServerTestCase): serve_static = True # emulate StaticLiveServerTestCase @classmethod def setUpClass(cls): super().setUpClass() try: # NOTE: Requires "chromedriver" binary to be installed in $PATH cls.driver = webdriver.Chrome() except: super().tearDownClass() raise @classmethod def tearDownClass(cls): cls.driver.quit() super().tearDownClass() def test_when_chat_message_posted_then_seen_by_everyone_in_same_room(self): try: self._enter_chat_room('room_1') self._open_new_window() self._enter_chat_room('room_1') self._switch_to_window(0) self._post_message('hello') WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 1 from window 1') self._switch_to_window(1) WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 2 from window 1') finally: self._close_all_new_windows() def test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room(self): try: self._enter_chat_room('room_1') self._open_new_window() self._enter_chat_room('room_2') self._switch_to_window(0) self._post_message('hello') WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 1 from window 1') self._switch_to_window(1) self._post_message('world') WebDriverWait(self.driver, 2).until(lambda _: 'world' in self._chat_log_value, 'Message was not received by window 2 from window 2') self.assertTrue('hello' not in self._chat_log_value, 'Message was improperly received by window 2 from window 1') finally: self._close_all_new_windows() # === Utility === def _enter_chat_room(self, room_name): self.driver.get(self.live_server_url + '/chat/') ActionChains(self.driver).send_keys(room_name + '\n').perform() WebDriverWait(self.driver, 2).until(lambda _: room_name in self.driver.current_url) def _open_new_window(self): self.driver.execute_script('window.open("about:blank", "_blank");') self.driver.switch_to.window(self.driver.window_handles[-1]) def … -
Not receiving slack private channel list
i have below scope granted for my slack application. incoming-webhook,channels:read,chat:write,chat:write.public&user_scope=identify,groups:read&granular_bot_scope=1 now when i use below python code for get private channel list it is not return private channel list. channel_list = self.client.conversations_list(types="private_channel",exclude_archived=1) i don't know the reason, even i tried same with https://api.slack.com/methods/conversations.list/test this link, in this i am also not receiving private channel list. am i missing any scope permission ?