Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PostgreSQL returns Copy 0 for a csv file
I have a test database with 2 lines that consists of 7 fields integrated with django. Apart from that, I have another test database with an obvious error in it (random delimiters). The query is the following: COPY public.website_manager_tasks FROM 'C:\upwego_test\csvs\tasks.csv' DELIMITER '|' CSV HEADER; The database is the following: No extra spaces, strings have quotation marks, the delimiter is set properly, data types match, the name of the file doesn't match any columns. In the second database, the delimiters are set improperly: ; | | | | | However, the data from this database copies perfectly. I don't understand the postgre's problem here. I have tried changing the resetting the delimiters in the first database so that they matched the pattern in the second database, and it didn't help. I also tried to copy the text from the first database to the second database and everything worked perfectly. I have no idea why it happens so. I'd be glad if anyone could explain this glitch and am ready to provide additional details. -
Django Функция сравнения содержимого http-адреса с именем папки
need help. There are named folders - post-1, post-2, post-3. Images are in folders. There are posts. You need to write a function that will compare the current http address post with the name of the folder and display its contents (all pictures) in the post. If the http address contains post-1 (http looks like this: http://category/post-1 ), then it displays the contents of the folder - post-1 on the page Need a function and a way to display it in the post template. I don't understand how to do it. Please help solve this problem -
Django form, "Value in valid, select not available"
I'm compelety new with python, after watched a vedio on youtube over the weekend I tried to create a Employee Management app with Django. In the video, all feilds are CharFields, after finish it as it was showed in the video, I tried to change some fields to dropdown list. Then it shows error "Value not valid, select not available" in one of the modified field when try to save the form input data. The Error message is that Branch_Name choices are invalid, and select is unavailable. Please check the code below and help me fix it. Many thanks. #in models.py: #in models.py from django.db import models class Bankinfo(models.Model): Bank_Name=models.CharField(max_length=100) Branch_Name=models.CharField(max_length=100) Branch_Sort_Code=models.CharField(max_length=50) def __str__(self): return f'Bankinfo: {self.Bank_Name}{self.Branch_Name}{self.Branch_Sort_Code}' class Employee(models.Model): def get_branch_choices(self): bank = Bankinfo.Bank_Name branches = Bankinfo.objects.filter(Bank_Name=bank).values_list('Branch_Name', 'Branch_Name').distinct() return branches def get_sort_code_choices(self): bank = Bankinfo.Bank_Name branch = Bankinfo.Branch_Name sort_codes = Bankinfo.objects.filter(Bank_Name=bank, Branch_Name=branch).values_list('Branch_Sort_Code', 'Branch_Sort_Code').distinct() return sort_codes def update_branch_choices(self): self.BRANCH_CHOICES = self.get_branch_choices() self.SORT_CODE_CHOICES = self.get_sort_code_choices() self.save() selected_bank = self.Bank_Name selected_branch = self.Branch_Name sort_codes = Bankinfo.objects.filter(Bank_Name=selected_bank, Branch_Name=selected_branch).values_list('Branch_Sort_Code', 'Branch_Sort_Code').all() self.SORT_CODE_CHOICES = sort_codes self.save() bank = Bankinfo.objects.all() BANK_CHOICES = [] bank_names = set() # Use a set to keep track of unique bank names for bk in bank: if isinstance(bk, Bankinfo) and bk.Bank_Name not in … -
change an imbricated list to a flat list in django, python
I want a flat list for my categories list in output, but this code doesn't do that. It still shows the categories in imbricated list. Can someone help me? This is the code: @api_view(['GET']) def AllCategoriesList(request): categories = Categories.objects.filter(parent=None).prefetch_related( Prefetch('children', queryset=Categories.objects.all(), to_attr='subcategories') ) def flatten_list(lst): flat_lst = [] for item in lst: if isinstance(item, list): flat_lst.extend(flatten_list(item)) else: flat_lst.append(item) return flat_lst category_list = [] for category in categories: category_list.append(category) category_list.extend(category.children.all()) flattened_list = flatten_list(category_list) serializer = CategorieSerializer(flattened_list, many=True) return Response(serializer.data) I tried to change my code to use the flatten_list function, but it doesn't work. This is the output: { "id": 1, "image_couverture": null, "children": [{ "id": 2, "image_couverture": null, "children": [], "nom_categorie": "nouveau categorie", "descriptions": "categorie fille", "slug": "nouveau-categorie", "created_at": "2023-03-04T08:08:35.667959Z", "updated_at": null, "parent": 1 } ], "nom_categorie": "Test categorie", "descriptions": "test categorie", "slug": "test-categorie", "created_at": "2023-03-04T06:43:42.628255Z", "updated_at": null, "parent": null }, { "id": 2, "image_couverture": null, "children": [], "nom_categorie": "nouveau categorie", "descriptions": "categorie fille", "slug": "nouveau-categorie", "created_at": "2023-03-04T08:08:35.667959Z", "updated_at": null, "parent": 1 }, { "id": 3, "image_couverture": null, "children": [ { "id": 4, "image_couverture": null, "children": [], "nom_categorie": "Boissons", "descriptions": "Test description", "slug": "boissons", "created_at": "2023-03-06T10:13:39.229660Z", "updated_at": null, "parent": 3 } ], "nom_categorie": "Alimentation & vins", "descriptions": "Test Description", "slug": … -
Minimal Reproducible Example for a django+celery project that can be deployed to google cloud Appengine, using redis on Memorystore
I have been stumped on this for quite a while, to the point where I just need this much help: I have a django + celery project that works fine locally, and I need to have it served on google cloud AppEngine. Having just Django deployed is working, but I cannot for the life of me figure out how to integrate celery. The issues that I need to solve are: get both django and celery to be served as single service have celery use the redis Memorystore instance as broker Having some kind of starting point that 100% works is what I would like to see, in order to study it and adapt it to my needs. It seems that every person that has asked this question didn't receive an satisfactory answer, just "use this other thing" "check the docs (404 link)" etc. I hope someone can point me to the right direction! -
FileNotFoundError at /ml/application/non-citizen-applicant/attest/ [Errno 2] No such file or directory: '/tmp/tmp5p0gvmpz.upload.jpg'
My Django app is a form that collects images and texts fields. It worked perfectly on the local server but when I deployed it on render, it gives the error 'FileNotFoundError at /ml/application/non-citizen-applicant/attest/ [Errno 2] No such file or directory: '/tmp/tmp5p0gvmpz.upload.jpg'' How do I resolve this? Here is my save function for the images def save(self, commit=True): instance = super().save(commit=False) if commit: instance.save() image1 = self.cleaned_data.get('image1') image2 = self.cleaned_data.get('image2') image3 = self.cleaned_data.get('image3') fs = FileSystemStorage() if image1: filename = fs.save(image1.name, image1) instance.image1 = filename if image2: filename = fs.save(image2.name, image2) instance.image2 = filename if image3: filename = fs.save(image3.name, image3) instance.image3 = filename if commit: instance.save() return instance I used postgres for database when deploying on render.com and db.sqlite for local server (https://i.stack.imgur.com/eW4bV.jpg) -
Django sends web requests messages to my logging file
I want to cancel Django to show me those web server requests, it getting to my uwsgi.log file of my application and i can't find where to set it off. enter image description here I tried looking at the documentation of django but couldn't find -
Django I'm trying to comment on posts, but I'm not getting it right
I'm trying to comment on posts, but I'm not getting it right. I have a comment model associated with a post model. We need a separate function for presenting comments on post pages. I tried different options, but nothing works. I wrote functions, but I don’t understand how to display them in a template. Help write a function and how to display a form for adding and displaying comments. class season(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug def get_absolute_url(self): return reverse('seasonpost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class episode(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... cat = models.ForeignKey('season', on_delete=models.PROTECT, null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('episodepost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(episode,on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField(blank=False) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) FORMS.PY from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'body') Views from .forms import * from .models import * ... def ContentSeason(request, seasonpost_slug): seasonpages = get_list_or_404(season, slug=seasonpost_slug) seasonpages=season.objects.filter(slug=seasonpost_slug) return render(request, 'content/season.html',{ 'season':seasonpages, }) def ContentEpisode(request, seasonpost_slug, episodepost_slug): episodepost = episode.objects.filter(slug=episodepost_slug, … -
Getting A Django Template Syntax Error. How do I solve this?
I tried to extend the base.html file in index.html. But I keep getting the following error: Invalid block tag on line 2: 'endblock'. Did you forget to register or load this tag? base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>{% block title %}{% endblock %}</title> <!-- {% block css_files %} {% endblock %} --> </head> <body> {% block content %}{% endblock %} </body> </html> index.html {% extends 'base.html' %} {% block title %} My Blog {% endblock %} {% block content %} Hello {% endblock %} I've made sure there are no gaps between any of the curly braces and %. Where could be the issue? -
Django unit test - TEST Mirror default database
I am trying to set up some testing on my Django application. I have used a database mirror for the test database. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'example1', 'USER': 'root', 'PASSWORD': 'password', 'HOST':'localhost', 'PORT':'3306', 'TEST': { 'MIRROR': 'default', } }, } I added new data to the mirror database when executing test cases. How to view Mirror database and its tables and data from MySQL Workbench? If I want to destroy Test mirror database, how to do that? -
Check if django permission works via shell
User has only change_post permission. I want to check in practice via shell if it works. It hasn't add_post permision. Creating an instance of a Post class with an user attribut it doesn't raise an error. How the user can try to 'add post' via shell? user.get_user_permissions() # {'blog.change_post'} user.has_perm('blog.add_post') # False post = Post(title='New Post', body='...', author=user, status=Post.Status.PUBLISHED) user.blog_posts.first() # <Post: Test Post> -
Creating a super use with docker-compose
Am new to docker and am trying to create a super user using this command: docker-compose -f docker-compose-deploy.yml run --rm app sh -c "python manage.py createsuperuser" I keep getting Error response from daemon: No such container: 3316a457be585979396635f940978c6942eaf969da69f7f86fc4dba6375fd923 However, when I ran docker ps, There are no containers listed. How do I avoid this error? -
There is error when trying to make order in django
When I try to order something, I keep getting this error: Here is my views.py if not request.user.is_authenticated: session = request.session cart = session.get(settings.CART_SESSION_ID) del session['cart'] else: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) order_product, created = OrderProduct.objects.get_or_create( order=order, ) order.save() messages.success(request, 'Заказ успешно оформлен. Проверьте свою электронную почту!!!') return redirect('product_list') Please can anyone help me to fix it. -
How to query the latest of a datetime field with a reverse foreign key in django
class CandidateUser(models.Model): first_name = models.CharField(verbose_name="First Name", max_length=256) class WorkRecord(models.Model): candidate = models.ForeignKey(to=CandidateUser, on_delete=models.CASCADE) job_title = models.CharField(max_length=256) finishes_at = models.DateField() this way i have two models. take the largest of the user's workrecords from the finishes_at dates (AND) and the job_title of those records must be equal to "foo" Here is what I want to do: finishes_at = MAX # I want to take the last of the user's work records (WorkRecord) and return it if the job_title field of that record is equal to "foo" job_title = "foo" # job_title field must be equal to "foo" I need to solve this problem by saying Candidate User.objects.filter()... like here CandidateUser.objects.filter(workrecord__job_title="foo").annotate(max_finish_date=Max('workrecord__finishes_at')).filter(workrecord__finishes_at=F('max_finish_date')) CandidateUser.objects.filter(workrecord__job_title="foo")\ .annotate(max_finish_date=Max('workrecord__finishes_at')) \ .filter(workrecord__finishes_at=F('max_finish_date'),) -
ImproperlyConfigured at /oauth/authorize/ This application does not support signed tokens
I'm using django oauth toolkit. When my client react-oidc app makes request to the authority djangoapp_domain/oauth/authorize (In my case localhost:8000/oauth/authorize), I get the error: ImproperlyConfigured at /oauth/authorize/ This application does not support signed tokens I'm expecting to get an JWT access token containing the set claims. I've tested the django app with Postman and when a request is made to the above given URL, everything works fine and I get the required result. Can someone guide me in the right direction? -
Dynamically updating a description class parameter and generating the new value in swagger documentation in a django-drf project
I will try to provide a minimal example since the real code in question is under protection - please feel free to ask for any corrections from my part. I have something like the following: class StatusCustomFilter: param_name = 'status' accepted_choices = ['DRAFT', 'ISSUED', 'PARTIAL', 'UNPAID', 'OVERDUE', 'PAID', 'VOID'] initial = {'draft': False, 'is_void': False} description = 'Optional choices to filter.' query_free_choices = True def get_choices(self): return accepted_choices # with some transformations, so I need to return them from a method class MyViewSet(SomeInheritance): serializer_class = Serializer filter_classes = ( StatusCustomFilter, ) # ... plus viewset logic # and via some inheritance the following code class GClassMixin(View): def get_filter_fields_display(self, filter_holder): filters = [] organization = self.organization filter_classes = list(getattr(filter_holder, 'filter_classes', [])) for filterClass in filter_classes: choices = [] if filterClass.query_free_choices: f = filterClass({}, organization=organization) description = force_text(f.description) choices = self.flatten_choices(f.get_choices()) description += ' The available choices are: %s' % (','.join( [c['value'] for c in choices])) filter_value = filterClass.param_name # status filters.append({ 'name': filterClass.param_name, 'verbose': utfupper(u'%s' % filterClass.title), 'value': filter_value, 'choices': choices, }) return filters which return a set of filter options for the UI connected with the MyViewSet class. I am trying to update the description parameter dynamically when the parameter … -
How to delete images from list of images in django and react?
I am trying to build image upload and I have to show it on frontend. I have button which select images and show the image to user. There is option of deleting the images and if deleted, images should be deleted from the tables. models.py class CampaignPopup(models.Model): campaign = models.ForeignKey(Campaign,on_delete=models.CASCADE,db_column='campaign') image = models.ImageField(upload_to='images/',default=None) display_pos = models.CharField(max_length=50,default=None,null=False) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) @property def image_url(self): if self.image and hasattr(self.image,'url'): return self.image_url else: return '' class Meta: db_table = "campaign_popup" This is how I am showing the image in one of my components { props.addImages.map((d, index) => { return ( <li key={index}> <img src={d.image_url} className="imageList" /> <span onClick={props.handleRemoveImages(index)}> <i className="fa fa-close"></i> </span> </li> ); }); } handleSubmit const handleSubmit = (e) => { e.preventDefault(); let formData = new FormData(); formData.append("campaign", JSON.stringify(campaign_data)); formData.append("popup", JSON.stringify(addImages)); for (let i = 0; i < addImages.length; i++) { formData.append("images" + i, addImages[i].image); } const response = async () => { await axiosApiInstance({ method: "post", url: "/chatapi/campaign/" + id, data: formData, }) .then((res) => { console.log(res); }) .catch((e) => { console.log(e); }); }; response(); }; I receive list of objects from addImages and this is how I save the image for index, popupData in enumerate(popup_data): print(popupData) if … -
Site specific idea with Django
I am looking for specific ideas to implement in Django, I have checked all kinds of ideas on the internet but they were not interesting, I would be happy if you have a nice and interesting idea, tell me. I try in the internet -
Exception Type: RelatedObjectDoesNotExist at / Exception Value: User has no customer
When I create a new product in Django admininstration , it created and saved but when I prompt to home page it throws error "Exception Type: RelatedObjectDoesNotExist at / Exception Value: User has no customer." how to solve it? I have no idea to solve it. HELP ME -
How to properly send messages outside of telegram message handlers?
I have an Aiogram bot written in Python integrated with Django REST (db, POST requests). Inside my views I have POST request handler which is getting messages from another API. I need to make my bot send this messages to telegram users, but the problem is that I probably need to make it outside of bot handlers themselves and they should be asynchronous, but I'm new to async programming. My POST handlers and aiogram bot are in different django apps. I just need to properly send messages using Aiogram or Asyncio outside of aiogram handlers. Some code snippets: This is POST handler: from bot_app.app import dp, bot import asyncio @api_view(['POST', 'GET']) def snippet_list(request, format=None): if request.POST['event'] == 'ONMESSAGEADD': # here I tried different solutions to send messages from request.POST to telegram users through bot, but got errors async def send_message(message): await bot.send_message(some_telegram_id, message) # 1 try send_fut = asyncio.run_coroutine_threadsafe(send_message(request.POST['data[MESSAGES][0][message][text]']), bot.loop) # 2 try, it works sometimes, but I'm getting "Timeout context manager should be used inside a task" asyncio.run(send_message('hi')) This is Aiogram bot: import asyncio from aiogram import Bot, Dispatcher from aiogram.contrib.fsm_storage.memory import MemoryStorage from . bot_settings import API_KEY # Here I used loop = asyncio.BaseEventLoop, but unsure how to … -
I changed the listview using forms in Django admin. But the slide bar doesn't work
try it for the first time Even if it's gibberish, please take good care of me. I'm trying to design a page using Django admin. I'm trying to use a form to input two numbers and pass them. This form is the one that pops up right away when you press the slide bar. For example, if you create an app called 'port' and register it in admin, it appears on the slide bar, right? And if you press 'port', it goes to the list page. I'm trying to go to the form I created without going to the list page. So now I'll show you my code. ports/forms.py class MediaForm(forms.Form): Media_port1 = forms.IntegerField(min_value=10000, max_value=19999) Media_port2 = forms.IntegerField(min_value=10000, max_value=19999) class MessageForm(forms.Form): Message_port1 = forms.IntegerField(min_value=20000, max_value=29999) Message_port2 = forms.IntegerField(min_value=20000, max_value=29999) ports/views.py def media_port_setting(request): form1 = MediaForm() form2 = MessageForm() return render(request, 'admin/ports/server_port_setting.html', {'form1': form1, 'form2': form2}) ports/admin.py @admin.register(Mediauseport) class MediaAndMessageUsePortAdmin(admin.ModelAdmin): def changelist_view(self, request, extra_context=None): url = reverse('ports:setting', current_app=self.admin_site.name) return redirect(url) templates/ports/server_port_setting.html {% extends "admin/base_site.html" %} {% block content %} <div> <h2>Media server port setting</h2> <form method="post"> {% csrf_token %} {{ form1.as_p }} <button type="submit">save</button> </form> </div> <div> <h2>Message server port setting</h2> <form method="post"> {% csrf_token %} {{ form2.as_p }} <button type="submit">save</button> … -
DJANGO 4.1 manage.py invalid syntax when trying to run collectstatic
Project Folder Structure -Project --app1 --app2 --static static folder has all static files for all apps. Settings.py STATIC_URL = 'static/' STATIC_ROOT = "/var/www/191.96.1.180/static" STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/)' ERROR: File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax pip list: pip list 1 pip list 2 So. My problem is when running python manage.py collectstatic on the developement server on my local machine it works. it saves all static files on the path from settings.py when i try to run python manage.py collectstatic on developement on my linux server i get this error. It is not due to python version or django version i have checked. -
Django : Query for date range when date is stored as string
For some reasons I'm required to store date as string 2023-03-03 and I have a requirement to filter this data using date range. Given starting date (say 2023-03-01) and end date (2023-03-04) I have to find all the rows between the given dates. Currently I'm using this query Sample.objects.filter(date__range=["2011-01-01", "2011-01-31"]) which is giving results. I'm not able to understand how it is working. I'm looking to see if this approach I'm following is right of if there's better approach to query this data. -
don't know why it's not redirecting properly.. how to do redirect on payments.html page with context value?
from django.shortcuts import render, redirect, HttpResponse from carts.models import CartItem from .forms import OrderForm import datetime from .models import Order Create your views here. def payments(request): return render(request, 'orders/payments.html') def place_order(request, total=0, quantity=0,): current_user = request.user cart_items = CartItem.objects.filter(user=current_user) cart_count = cart_items.count() delivery_charge = 40 grand_total = 0 tax = 0 for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) quantity += cart_item.quantity tax = (2 * total)/100 grand_total = total + tax + delivery_charge if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.address_line_2 = form.cleaned_data['address_line_2'] data.country = form.cleaned_data['country'] data.state = form.cleaned_data['state'] data.city = form.cleaned_data['city'] data.pincode = form.cleaned_data['pincode'] data.order_note = form.cleaned_data['order_note'] data.order_total = grand_total data.tax = tax data.delivery_charge = delivery_charge data.ip = request.META.get('REMOTE_ADDR') yr = int(datetime.date.today().strftime('%Y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr,mt,dt) current_date = d.strftime("%Y%m%d") # 20230214 order_number = current_date + str(data.id) data.order_number = order_number data.save() order = Order.objects.get(user=current_user, is_ordered=False, order_number=order_number) context = { 'order': order, 'cart_items': cart_items, 'total': total, 'tax': tax, 'delivery_charge': delivery_charge, 'grand_total': grand_total, } return render(request, 'orders/payments.html', context) else: return redirect('checkout') {% extends 'base.html' %} {% load static %} {% block body … -
Django: Use objects from one django model to filter objects from another django objects
I'm doing my studying project. I have 2 models: class RoutePoint(geo_models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, null=False, blank=False, related_name='routepoints') point = geo_models.PointField() datetime = models.DateTimeField() class Travel(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.DO_NOTHING, null=False, blank=False, related_name='travels') begin = models.DateTimeField() end = models.DateTimeField() First one contains geopoints for vehicle and date and time for vehicle getting there. Second one countains the begining and the ending of the rides for vehicles. I'm having some curl request with two fields - start_date and end_date, let's call it some kind request for report. So, at first I need to get something like this: SELECT vehicle_id, begin, end FROM park_travel WHERE begin > "2022-12-30" AND end < "2023-01-06" I'll call it result. And after that i need to get something like: SELECT vehicle_id, point, datetime FROM park_routepoint WHERE vehicle_id = result.vehicle_id AND datetime > result.begin AND datetime < result.end And I have to do it without raw sql... Can you give me some advice? Thank you. P.S. Frankly speaking, I even couldn't get to working raw sql yet...