Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ? -
ModuleNotFoundError: No module named 'google' in GCP app
I have a Django app that I am trying to deploy to GCP. The app works perfectly fine when I run it locally, and it deploys with no issue to GCP (via gcloud app deploy). When I open the webpage, I get this error "502 Bad Gateway 502 nginx" due to "ModuleNotFoundError: No module named 'google'". I haven't been able to find how to properly import google into my GCP app. More details below, any help is appreciated. Here is the parsed stack trace (via GCP debugger): ModuleNotFoundError: No module named 'google' at <module> (/srv/socha_web/settings.py:14) at _call_with_frames_removed (<frozen importlib._bootstrap>:219) at exec_module (<frozen importlib._bootstrap_external>:728) at _load_unlocked (<frozen importlib._bootstrap>:677) at _find_and_load_unlocked (<frozen importlib._bootstrap>:967) at _find_and_load (<frozen importlib._bootstrap>:983) at _gcd_import (<frozen importlib._bootstrap>:1006) at import_module (/opt/python3.7/lib/python3.7/importlib/__init__.py:127) at __init__ (/env/lib/python3.7/site-packages/django/conf/__init__.py:142) at _setup (/env/lib/python3.7/site-packages/django/conf/__init__.py:63) at __getattr__ (/env/lib/python3.7/site-packages/django/conf/__init__.py:76) at setup (/env/lib/python3.7/site-packages/django/__init__.py:19) at _call_with_frames_removed (<frozen importlib._bootstrap>:219) at exec_module (<frozen importlib._bootstrap_external>:728) at _load_unlocked (<frozen importlib._bootstrap>:677) at _find_and_load_unlocked (<frozen importlib._bootstrap>:967) at _find_and_load (<frozen importlib._bootstrap>:983) at _gcd_import (<frozen importlib._bootstrap>:1006) at import_module (/opt/python3.7/lib/python3.7/importlib/__init__.py:127) at import_app (/env/lib/python3.7/site-packages/gunicorn/util.py:358) at load_wsgiapp (/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py:39) at load (/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py:49) at wsgi (/env/lib/python3.7/site-packages/gunicorn/app/base.py:67) at load_wsgi (/env/lib/python3.7/site-packages/gunicorn/workers/base.py:144) at init_process (/env/lib/python3.7/site-packages/gunicorn/workers/base.py:119) at spawn_worker (/env/lib/python3.7/site-packages/gunicorn/arbiter.py:583) And here is my settings.py file (I wiped any secret keys): import os from google.oauth2 import service_account # … -
How to upload a big size folder to GCS using angular 9?
I have to upload a huge size of the folder(approx 150GB ) to GCS. I am using Angular 9 as front-end and Django for the backend. Please tell me the best approach for this. The approach in my mind is: Take a token from the back-end and upload the file one by one(using GCS API). Upload all the files one-by-one in the Django server than upload it to GCS. Zip the folder and upload it to Django and then extract and upload it to GCS(but I have no idea,how to upload a big zip file using angular). Please suggest to me what can I do and how? -
Onchange missing AJAX validation with django
I've been trying to validate the title field using AJAX.(If the title exist in the table display the error "Title already exists"). I looked at many examples, but some are old and do not work, while others I do not understand.Below is the code, please help with the implementation. Here is my code:- forms.py class postForm(forms.ModelForm): class Meta: model = Post fields = ( 'title', 'description' ) widgets = { 'title': forms.TextInput(attrs={'id': 'title', 'required': True,}), 'description': forms.TextInput(attrs={'id': 'description', 'required': True}) } views.py def validate_title(request): title = request.GET.get('title', None) data = { 'is_taken': Post.objects.filter(title=title).exists() } return JsonResponse(data) class postClass(CreateView): template_name = 'create_post.html' form_class = postForm def create_post(self, request): posts = Post.objects.all() response_data = {} form = postForm() if request.POST.get('action') == 'post': title = request.POST.get('title') description = request.POST.get('description') response_data['title'] = title response_data['description'] = description Post.objects.create( title=title, description=description, ) return JsonResponse(response_data) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('create/', postClass.as_view(), name='create'), path('validate_title', views.validate_title, name='validate_title'), ] create_post.html <body> <form method="POST" id="post-form"> {% csrf_token %} <div class="row" style="margin-left: 400px;margin-top: 50px"> {{ form }} <button type="submit" style="margin-left: 20px" class="btn btn-primary">Submit</button> </div> </form> <div> {% for i in posts %} <label>{{ i.title }}</label> {% endfor %} </div> <script type='text/javascript'> $(document).ready(function () { $(document).on('submit', '#post-form', function (e) { e.preventDefault(); … -
Is it possible to access database from command prompt in Django?
I'm searching for the way to access database from command prompt without using Django admin. Thanks in advance. -
What are the diffences between django-dash and django-plotly-dash?
I am building a web app using Django. It will display network graphs and others data visualization and I am investigating Dash on that purpose. I found these two similar packages: django-dash and django-plotly-dash and I am wandering what would be the best solution. Is anyone knows the core differences between the two packages and has some experience with it? Thanks -
how to active show more button and show 3 item per page in django
i'm trying to show 3 items per page and if user press on show more button it will load more 3 items views.py : def home_page(request): pcgamesforhome = PCgames.objects.all() context = {'pcgamesforhome' : pcgamesforhome} return render(request,'html_file/enterface.html',context=context) html page : <div class="container"> <div class='row'> {% for home_page in pcgamesforhome %} <div class='col-xs-12 col-sm-6 col-md-4 website-thumb'> <a href="{{ home_page.page_url }}"> <img src="{{ home_page.get_image }}" class='image_control_for_home_page_pc_games' alt=''> </a> <h3 class="font_control_for_home_page_pc_games_name"><a href="{{ home_page.page_url }}" style="color:black">{{ home_page.name }}</a></h3> </div> {% endfor %} </div> <div class="text-center mt-4"> <a role="presentation" type="button" class="btn btn-secondary btn-lg loadMore" style="width:40%">Show More</a> </div> <script> $(".row").slice(0, 3).show(); //showing 3 div $(".loadMore").on("click",function(){ $(".row:hidden").slice(0, 3).show(); //showing 3 hidden div on click if($(".row:hidden").length ==0) { $(".loadMore").fadeOut(); //this will hide //button when length is 0 } }) </script> so what is the wrong in my code , ( my html page now show all items in model not 3 in once ) -
How to use the django-admin-search with search_FieldNameHere ? I am unable to use the same
The django-admin-search plugin version 0.3.5 has beem installed with django 3.0.5 on linux. How exactly to use the search_field query, I fail to understand. I am not great working with OOPS yet. What I tried: def search_mfrom(request, field_value, param_values): """ intercept query filter for description field """ query = Q() #print(request, field_value, param_values, 'llllllllllllll') query = Q(mfrom='sowmiya@abc.com') print(query, 'qqqqqqqqqqqq') return query The print(query, 'qqqqqqqqqqq') never executes. Am I passing in something wrong? The form field is mfrom. Secondly, wish to send in login specific records in queryset which this tool is overriding. How to do that? I am able to override the queryset based on login domain part of the request.user, but since this tool is also overriding the queryset object of the modeladmin, I don't know how to go about. The code snippet for the same: def get_queryset(self, request): domain_list = [] temp = [] qs = super(LogSearchFormAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: domain_list = Domain.objects.filter( customer__in=Customer.objects.filter( email=request.user.username)).values_list( 'name', flat=True) #print(list(domain_list)) dom_names = list(domain_list) #print(dom_names) qs = MailLogs.objects.none() if dom_names: for d in dom_names: qs = MailLogs.objects.filter( Q(mfrom__icontains=d)|Q(mto__icontains=d)) # qs |= MailLogs.objects.filter(mfrom__icontains=d) # qs |= MailLogs.objects.filter(mto__icontains=d) print(qs.query) #print(qs) return qs -
how can both foreign key shows the same values?
I am trying to connect two tables so i made a model with foreign key as follows- class Queryform(models.Model): querynumber=models.IntegerField(primary_key=True) name=models.ForeignKey("app.Person",on_delete=models.CASCADE,related_name="query_name",) address=models.ForeignKey("app.Person",on_delete=models.CASCADE,related_name="query_address",null=True) my Views.py def queryform(request): return render(request,'app/queryform.html',{'form':queryformform()}) But as i am using this form address is also giving name options in my form . name is correctly giving name options. how can i handle this thing ? -
Auto populating model fields in the django adminTabularinline with a foreign key relationship from another app model
Am writing a django app that can also store and manage business stock and such related stuff.Buh am a little bit stuck somewhere where i expect it to auto-populate some fields from the related stock app model into the daily sales app admin Tabularinline. I want it to autofill the rest of the fields from the related provided item name in the stock model on the fly after it has been input by the user in the daily sales. My stock model is as follows: class stock (models.Model): Item_Name = models.CharField(max_length=12) Quantity = models.PositiveIntegerField() Cost_price = models.PositiveIntegerField() Selling_price = models.PositiveIntegerField() date_added = models.DateTimeField(name='date added',auto_now_add=False) overall_price = models.PositiveIntegerField(null=True , blank=True) And then the daily sales model for tabularinline is : class product_entry (models.Model): Day = models.ForeignKey(daily_sales,on_delete=models.CASCADE) product = models.ForeignKey(stock, on_delete=models.CASCADE) Quantity = models.PositiveIntegerField() Selling_price = models.PositiveIntegerField() Total_price = models.PositiveIntegerField() For the daily sales admin : class product_entry_admin (admin.TabularInline): model = product_entry extra = 3 autocomplete_fields = ('product',) -
No matching distribution found for django==3.1.1 (from -r requirements.txt (line 23))
i am using ubuntu using terminal i am trying to install python and django i have installed python successfully but when i do pip3 install -r requirements.txt its showing this error :- WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip. Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue. To avoid this problem you can invoke Python with '-m pip' instead of running pip directly. DEPRECATION: Python 3.5 reached the end of its life on September 13th, 2020. Please upgrade your Python as Python 3.5 is no longer maintained. pip 21.0 will drop support for Python 3.5 in January 2021. pip 21.0 will remove support for this functionality. Defaulting to user installation because normal site-packages is not writeable Ignoring python-magic-bin: markers 'sys_platform == "win32"' don't match your environment Collecting adyen==3.0.0 Using cached Adyen-3.0.0.tar.gz (13 kB) Collecting amqp==2.6.1 Using cached amqp-2.6.1-py2.py3-none-any.whl (48 kB) Collecting aniso8601==7.0.0 Using cached aniso8601-7.0.0-py2.py3-none-any.whl (42 kB) Collecting asgiref==3.2.10 Using cached asgiref-3.2.10-py3-none-any.whl (19 kB) Collecting babel==2.8.0 Using cached Babel-2.8.0-py2.py3-none-any.whl (8.6 MB) Collecting beautifulsoup4==4.7.1 Using cached beautifulsoup4-4.7.1-py3-none-any.whl (94 kB) Collecting billiard==3.6.3.0 Using cached billiard-3.6.3.0-py3-none-any.whl (89 kB) Collecting boto3==1.14.52 Using cached boto3-1.14.52-py2.py3-none-any.whl (129 kB) Collecting botocore==1.17.52 Using cached … -
How to always let heroku run a command on deployment for a django project?
I was working on a django project. The Procfile is the place that heroku always looks on before deployment. Currently it is configured this way and it works all fine. web: python manage.py collectstatic --no-input; gunicorn project_folder.wsgi --log-file - --log-level debug This means it runs collectstatic command every time I make any changes in my project and deploy it on server. Can the same thing apply to run a background task? This background task needs to run automatically after my project is deployed. python manage.py process_tasks is what I type in my command to trigger this background_task in django on my local server. So, would something like this below be invoked the same way as python manage.py collectstatic serves(that is collecting all static files in my static folder)? web: python manage.py collectstatic --no-input; python manage.py process_tasks; gunicorn project_folder.wsgi --log-file - --log-level debug -
Redirect set of included URL patterns in django
For my Django app, I've always had my Dashboard pages prefixed with /site/dashboard/ urlpatterns = [ path('site/dashboard/', include('dashboard.urls')), ] I'd like to simplify the URLs and change it so the pages are just /dashboard/ urlpatterns = [ path('dashboard/', include('dashboard.urls')), ] I'm familiar with doing a RedirectView in URLs to redirect to a different single url/view. How would I do this with an entire set of views, so all the old /site/dashboard/ URLs in dashboard.urls were marked with a 301 redirect to the new URLs? -
How do i add in manytomany relationship in django
class Watchlist(models.Model): item = models.ManyToManyField(Product, related_name="item") watcher = models.ForeignKey(User, on_delete=models.CASCADE, related_name="watcher") def __str__(self): return f"watcher: {self.watcher}, {self.item.all()}"