Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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... -
how to filter objects to get the sum of the repeated values in Django?
models.py name = models.ForeignKey(CustomUser) date = models.DateTimeField() orders = models.IntegerField(default=0) this is the model which counts daily orders of a user. the order which is made in the same day will just increase the orders count by one. So how to make a query or serializer which gives the result of users with their total orders of all time eg: [{name:albert, orders:35}, {name:Vncent, orders:35}, {name:john, orders:35}, {name:dion, orders:35}, {name:aoidi, orders:35},] -
django count ids in every subgroup
I have models of subjects, topics and questions structured as following: class Subject(models.Model): subject = models.CharField(max_length=200, unique=True) class Topic(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) topic = models.CharField(max_length=200, blank=False) class Question(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, topic = ChainedForeignKey( "Topic", chained_field="subject", chained_model_field="subject", show_all=False, auto_choose=True, ) Now I want to create a query that will count ids for each subject, topic. viz: ╔═════════╤═══════╤═══════╗ ║ subject │ topic │ count ║ ╠═════════╪═══════╪═══════╣ ║ 1 │ 1 │ 10 ║ ╟─────────┼───────┼───────╢ ║ 1 │ 2 │ 11 ║ ╟─────────┼───────┼───────╢ ║ 2 │ 3 │ 5 ║ ╟─────────┼───────┼───────╢ ║ 2 │ 4 │ 4 ║ ╚═════════╧═══════╧═══════╝ So far tried the following: numberq=Question.objects.all().values('subject','topic').annotate(TotalQuestions=Count('topic')) numberq=Question.objects.all().values('subject','topic','id').order_by('subject','topic') numberq=df.groupby(['subject','topic'])['id'].count()#.size() Unfortunately nothing yielding expected results. Can someone please guide? As a bonus 🙃 I also want to replace the subject_id and topic_id by the respective name fields. -
Django Avatar Library ValueError
Django has added an Avatar Library to make it easy to install User Avatars: https://django-avatar.readthedocs.io/en/stable/. However I'm lost on: 3: Add the avatar urls to the end of your root urlconf. Your urlconf will look something like: urlpatterns = [ # ... path('avatar/', include('avatar.urls')), ] I want to add the ability for the user to change an avatar on the "profile".html page. path("profile/<str:username>", views.profile, name="profile"), How can I do this? 4: Somewhere in your template navigation scheme, link to the change avatar page: <a href="{% url 'avatar_change' %}">Change your avatar</a> When I add step 4 to the profile page, I get a ValueError: not enough values to unpack (expected 2, got 1). I have not specified a User Avatar yet, but the ReadMe documentation doesn't specify how to set a default avatar image. Thanks so much. I am expecting users to be able to add/change their avatar images. -
Why is my Django web page refusing to load? (View pulling from large mySQL table)
I am currently trying to load a web page which is a table of contracts data that is pulled from a mySQL database. There are a large amount of contracts (210,000+) in the contracts table and it will continue to grow by the thousands daily. As you will see, I have already added pagination, and I have changed the model call to only request columns from the table that are needed to display the information on the webpage. I cannot get the view to load, and I think that it is due to to large size of the contracts table that I am pulling information from. In a separate view, I calculate a similarity array (similarity_arr) and save it as a JSON object in another table in the database, which it is then paired with the user's id as a foreign key. The similarity array is an array which matches the length of the amount of contracts in the contracts table. These contracts are pulled and ordered by the dates they were posted to maintain order which is used to pair the similarity scores to the proper contract in the following view function. The similarity score is just a float … -
How to upload files from django admin panel?
iam using django 3.0.7 and i want to upload files from admin panel but when i try to upload file it still loading and at least it show error 500 request time out , i deploy my website in namecheap so how to fix it settings.py : # media dir MEDIA_URL= '/media/' MEDIA_ROOT = os.path.join('/home/traixmua/public_html/media') urls.py : urlpatterns = [ path('', views.home, name='home'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) handler404 = 'blog_app.views.handler404' models.py : class Trainer(models.Model): document = models.FileField(upload_to='documents/') admin.py : from django.contrib import admin from blog_app.models import Trainer # Register your models here. class TrainerAdmin(admin.ModelAdmin): search_fields = ('name', 'name') admin.site.register(Trainer,TrainerAdmin) what is the problem here i can't find any problem note : when i try to upload files using SQLite it's work good but with mysql i have this problem , i can choose the file but it won't to upload -
Integrity error with Django models (NOT NULL constraint failed)
can someone please help with the below error? IntegrityError at /configuration/solarwinds/ NOT NULL constraint failed: pages_cityname.name Request Method: GET Request URL: http://127.0.0.1:8000/configuration/solarwinds/ Django Version: 3.2.5 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: pages_cityname.name Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /usr/local/opt/python/bin/python3.7 Here is my models.py: class Region(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = 'Region' class Cityname(models.Model): region = models.ForeignKey(Region, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name class Meta: verbose_name_plural = 'Cityname' class SolarwindsTool(models.Model): region = models.ForeignKey(Region, on_delete=models.SET_NULL, blank=True, null=True,verbose_name='Region') city = models.ForeignKey(Cityname, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='City') class Meta: db_table = 'solarwindstool' def __str__(self): return self.name -
AttributeError at / 'str' object has no attribute 'decode'
i am facing a problem , that is my django website show an error when i put debug True , and the problem is 'str' object has no attribute 'decode' and i don't know why this happened also the error say i have error in line 25 : def home(request): trainerpostforhome = Trainer.objects.all() app = trainerpostforhome page = request.GET.get('page', 1) page 2 etc paginator = Paginator(app, 10) try: single_home_post = paginator.page(page) # line 25 the error here except PageNotAnInteger: single_home_post = paginator.page(1) except EmptyPage: single_home_post = paginator.page(paginator.num_pages) return render(request,'website_primary_html_pages/home.html', { 'single_home_post': single_home_post }) the full error is : Environment: Request Method: GET Request URL: https://trainermods.net/ Django Version: 2.2.5 Python Version: 3.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog_app', 'ckeditor'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/traixmua/django/blog_app/views.py" in home 25. single_home_post = paginator.page(page) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/paginator.py" in page 70. number = self.validate_number(number) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/paginator.py" in validate_number 48. if number > self.num_pages: File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/utils/functional.py" in __get__ 80. res = instance.__dict__[self.name] = self.func(instance) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/paginator.py" in num_pages 97. if self.count … -
DRF serializer validation depends on format of request?
I tried to google this one up and still cannot find an answer. Maybe I am missing sth basic... While testing a PUT and POST requests with pytest I have noticed that when I provide data with a missing serializer field it is ok - as long as I don't specify the format of the request. The code is simply: class MySerializer(CustomModelSerializer): a = ... b = .... c = serializers.BooleanField(source='some_c') def test(): ... data = {'a': something, 'b': something_else} # 'c' is missing, c should be boolean resp = client.post(reverse('articles-list'), data=data, format='json') ... and I get HTTP 400, {'c': [ErrorDetail(string='This field is required.', code='required')]} when I omit the format part though, the test passes... -
Django redirect not clearing after clearing, disabling cache, etc
I have a maintenance mode on my site which I typically turn on while I make changes. It checks if an IP address is in a list of verified IPs, and if it is not, it redirects to a maintenance page. When I finished working on my site I turned maintenance mode back off. Unfortunately, the home page (and, weirdly, only the home page) still appears to redirect to the maintenance page! To fix this problem, I first tried to disable the cache in my browser. Still redirecting. Then I cleared my cache and all of my cookies. Then, to my astonishment, I saw that it was still redirecting in different browsers. What the heck? Then I decided what the heck, and commented out the maintenance mode code from my middleware. Exact same behavior. Then I tried setting up another redirect that would take you from the maintenance page back to the home page, in hopes it would resolve my issue. Turns out this was a bad idea, because now home redirects to maintenance and maintenance redirects to home, so I get a too many redirects error. I tried to just take that part of the code back out, but … -
Why abort() in celery is setting all fields to null?
I have Django application where I am using celery to run asynchronous tasks. The task goes through list of websites and get some data. Inside this task I am using raise Exception inside while loop. Below is my APIView I am using to stop celery task in React. Revoke() does not work at all and this is the only working way to stop my task. class StopTaskResult(APIView): def get(self, request, task_id): AbortableAsyncResult(task_id).abort() return Response({"msg": "Task has been succesfully stopped"}) The problem I am facing is that when the task status is set to ABORTED all fields except task_id are set to null. Once they reach to Exception they are changed to FAILURE and all values are restored. How to change this behaviour? The most important is to keep periodic_task_name and worker fields (even if task status is equal to ABORTED)?