Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve ValueError Assign problem in Django?
I created a system with Django. In this system, user uploads an excel table and I creating a new customer from that excel. But in this excel I have 2 important columns. They are entity and parent. I want to when a user uploads this excel table but If there is an entity or parent that is not registered in my database, I want to create it and then save it. I user get_or_createe for that but I am getting an error: ValueError at /customers/upload Cannot assign "(<ParentCompany: TESTP>, False)": "Customer.parent" must be a "ParentCompany" instance. How can I solve it? views.py def customer_excel_upload(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) company = userP[0].company if request.method == 'POST': form = CustomerExcelForm(request.POST, request.FILES) if form.is_valid(): new_excel = form.save() new_excel = new_excel.excel df = pd.read_excel('C:/fray/otc/' + new_excel.name, index_col=0, engine='openpyxl') for index, row in df.iterrows(): if row is not None: new_customer = Customer() new_customer.customer_name = index country = Country.objects.get(country_name=row['Country']) new_customer.address = row['Address'] new_customer.customer_number = row['Customer Number'] new_customer.phone_number = row['Phone Number'] new_customer.email_address = row['Email Adress'] new_customer.credit_limit = row['Credit Limit'] new_customer.currency_choice = row['Currency choice'] new_customer.risk_rating = row['Risk rating'] parent = ParentCompany.objects.get_or_create(parent=row['Parent Company'], company=request.user.company) entity = Entities.objects.get_or_create(entities=row['Entity'], company=request.user.company) new_customer.parent = parent new_customer.entity = entity new_customer.country = country … -
In Api URL how to Increment Page NUmber in Django
i amnot getting in Django Pease help me .. In my Api request i have particular page number i amnot able to understand how to increment that page number by dynamically please help in this #URL base_url = 'https://api.kayzen.io/v1/reports/336960/report_results?end_date={}&page=1&per_page=25&sort_direction=desc&start_date={}'.format( today,today) In this URL page is their that number should increment not other number. -
NoReverseMatch at/Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/(?P<product_slug>[^/]+)/$']
Hello I am a student currently learning Django. The following error occurs in the project I'm making. We are implementing a function related to product registration, but we can't do anything because of an error. Actually, I don't know much about slug or Django. What should I do to solve it? Great developers, please help me. I have attached the files for our project. Help would be appreciated. I don't know where and how to designate the slug. I've applied all the results from the search, but I'm only looking at the same screen. I would really appreciate it if you could help me. error content : NoReverseMatch at / Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['(?P[0-9]+)/(?P<product_slug>[^/]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['(?P[0-9]+)/(?P<product_slug>[^/]+)/$'] Exception Location: D:\anaconda3\envs\vnv_zn\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: D:\anaconda3\envs\vnv_zn\python.exe Python Version: 3.7.6 Python Path: ['C:\zeronine_project (1)', 'D:\anaconda3\envs\vnv_zn\python37.zip', 'D:\anaconda3\envs\vnv_zn\DLLs', 'D:\anaconda3\envs\vnv_zn\lib', 'D:\anaconda3\envs\vnv_zn', 'D:\anaconda3\envs\vnv_zn\lib\site-packages'] Server time: Tue, 25 May 2021 12:19:01 +0900 model.py from django.db import models from django.contrib.auth.models import AbstractUser from django.urls import reverse # member class Member(AbstractUser): username = models.CharField(primary_key=True, … -
Is there a package like django-sphinxdoc for django3.X or how to make it work with django3.X
I need to make docs and i was in need to use django-sphinxdoc and i got this error when i make migrates Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/hassanyoussef/.cache/pypoetry/virtualenvs/djangotrainingcart-TmT73HM3-py3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() ... File "/home/hassanyoussef/.cache/pypoetry/virtualenvs/djangotrainingcart-TmT73HM3-py3.8/lib/python3.8/site-packages/sphinxdoc/decorators.py", line 7, in <module> from django.utils.decorators import available_attrs ImportError: cannot import name 'available_attrs' from 'django.utils.decorators' (/home/hassanyoussef/.cache/pypoetry/virtualenvs/djangotrainingcart-TmT73HM3-py3.8/lib/python3.8/site-packages/django/utils/decorators.py) anyone know how to solve this or similar package? -
How to load django template tags in static javascript file
I've provided such a function which has to add a new row to the form after pressing a button: const addNewRow = () => { const numberOfRows = document.querySelectorAll('.order-form-row').length const orderForm = document.querySelector('.order-form') orderForm.innerHTML += ` <div class="row order-form-row"> <div class="col-md-3"> <select required id="order-form-material" class="form-control"> <option value="" selected disabled>{% trans 'Select an option' %}</option> </select> <label class="form-label" for="order-form-material">{% trans 'Material' %}</label> </div> </div> ` } but it renders this way: -
how to track the position of the user in django
i am planning to build a site, which requires to track the location of the user and a specific address and show the distance between both points , kind of like uber Please any suggestions how i can deal with this issue,i have not started to code yet so.... waiting for your precious guidance. thanks -
Celery worker does not write logs when detached
I have a Django application and I use celery & rabbitmq to execute async tasks. I have configured celery to write logs to file, and when I execute celery -A project_name -b <broker_url> worker -l INFO everything works fine and the logs are printed both in console and into the file. However, when I execute the aforementioned command with -D option, i.e. detach the worker, the file is no longer appended with logs. My logging configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'null': { 'level': LOGGING_LEVEL, 'class': 'logging.NullHandler', }, 'logfile': { 'level': LOGGING_LEVEL, 'class': 'logging.handlers.RotatingFileHandler', 'filename': log_file_path, 'maxBytes': 5000000, 'backupCount': 2, 'formatter': 'standard', }, 'console': { 'level': LOGGING_LEVEL, 'class': 'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, 'level': "WARNING", }, 'django.db.backends': { 'handlers': ['console'], 'level': "INFO", 'propagate': False, }, 'celery': { 'handlers': ['console', 'logfile'], 'level': LOGGING_LEVEL, }, }} The celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.signals import setup_logging os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_service.settings') app = Celery('my_service') app.config_from_object('django.conf:settings', namespace='CELERY') @setup_logging.connect def config_loggers(*args, **kwags): from logging.config import dictConfig from board_ownership_service import settings dictConfig(settings.LOGGING) # Load task … -
Django Form is Not saving to Database
I have searched the site for a solution, many related questions, but no direct response given. I have 3 apps on my projects, and 2 worked pretty well, except for this app, which is not writing to the database. Yes, the other 2 apps write to the postgres database, and I can view the table, but this return empty rows, and I don't see any problem. I hope someone can help me, see below my Model, Form and View.py. MY View.py from django.shortcuts import render, redirect from .forms import EngForm def EngineerList(request): return render(request, "Engineers/elist.html") def EngineerForm(request): if request.method == "GET": form = EngForm() return render(request, "Engineers/eform.html", {'form':form}) else: form = EngForm(request.POST) if form.is_valid(): form.save() return redirect('/engineer/') #pointing to urls.py paths My Forms.py from django import forms from .models import Engineers class EngForm(forms.ModelForm): class Meta: model = Engineers fields = '__all__' labels = { 'workarea' : 'Zone', 'face' : 'Picture', } def __init__(self, *args, **kwargs): super(EngForm, self).__init__(*args, **kwargs) self.fields['position'].empty_label='Select' self.fields['workarea'].empty_label='Select' self.fields['face'].required = False My Model.py from django.db import models class Engineers(models.Model): position = ( ('NOC', 'NOC'), ('Supervisor', 'Supervisor'), ('Site Manager','Site Manager'), ('Site Engineer', 'Site Engineer'), ) region = ( ('SS','South-South'),('SW','SW'),('SE','SE'), ('NE','NE'),('NW','NW'),('NC','NC'), ) firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) email = … -
Django foreign model from third party API
On our project we have CartItem, where users can store both Package - foreign model, and Ticket Group id - in relation to the entity that should be fetched from third party service API: class CartItem(models.Model): id = models.AutoField(_('id'), primary_key=True) cart = models.ForeignKey(Cart) package = models.ForeignKey(Package, null=True) quantity = models.IntegerField(_('quantity')) ticket_group_id = models.IntegerField(_('ticket_group_id'), null=True) What is the most convenient way to fetch ticket group information, and is there any way to do it on the model level? -
Python Django: Is it possible to convert comma separated values in a column and retrieve each value as query set rows
My data set in the table is like this, lets call table name as plans_tracker (1st screen shot) I am trying to retrieve query set like (2nd screen shot). can some one please help me on this, I could not modify the table structure. I am trying to do this in Django templates -
S3 files can only be opened in read-only mode
I have an image field in django model. before i save the image from the form, i want to resize and crop image and then only to save in s3 bucket. when i was using django-storages, it worked fine. moving to django-s3-storage, gives me the error of S3 files can only be opened in read-only mode. this is the code snippet of my resizing and editing in django form: def save(self): photo = super(ProfileUpdateForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(photo.image) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) fh = default_storage.open(photo.image.name, 'wb') resized_image.save(fh, 'png') fh.close() return photo also, if i remove the mode arg of open (fh = default_storage.open(photo.image.name) ), it does not edit and crop the image and just upload the original. also, i tries: to open a PIL image format, but no luck: fh = default_storage.open(resized_image, 'wb') resized_image.save(fh, 'png') fh.close() finally; i tried to make my s3 bucket publicly accessible and give all permissions. also did not works. I realized that it gotta be django-s3-storages. i would be supper and more then happy to be advised and or any help as i am stacked at … -
How to flatten serialized data with only 1 field in Django Rest Framework
I have the following serializer: class SomeSerializer(serializers.ModelSerializer): some_user = UserSerializer() class Meta: model = UserFollowing fields = ("some_user",) And the model UserFollowing associated to it: class UserFollowing(models.Model): some_user = models.ForeignKey(User, on_delete=models.CASCADE) The serializer returns something like this: [ { "some_user": { "username": "jane", "profile_picture": "/media/picture.jpg" } }, ... ] For consistency and simplicity, I would like to return: [ { "username": "jane", "profile_picture": "/media/picture.jpg" }, ... ] How can I achieve this? -
Getting list from Many to One Relationship Django
I have two models like these: class User(models.Model): id = models.AutoField(primary_key=True) username= model.CharField(max_length=25) class Book(models.Model): id = models.AutoField(primary_key=True) book_name = models.CharField(max_length=25) created_by = models.ForeingKey(User, on_delete=models.CASCADE) Then, I have a rest api with json for getting all books. def get_book_list(request): queryset = Book.objects.all() return JsonResponse({ 'result_list' : list(queryset.values()) }) Now, this api returns json like this: { "result_list" : [ { "id" : 1, "book_name" : "A-Book", "created_by_id" : 1}, { "id" : 2, "book_name" : "B-Book", "created_by_id" : 1}, { "id" : 3, "book_name" : "C-Book", "created_by_id" : 1} ] } I have user that id is 1, username is "Test". But, api does not return foreign key user object. Why? Is it possible to getting list like this ? : { "result_list" : [ { "id" : 1, "book_name" : "A-Book", "created_by" : { "id" : 1, "username" : "Test"} }, { "id" : 2, "book_name" : "B-Book", "created_by" : { "id" : 1, "username" : "Test"} }, { "id" : 3, "book_name" : "C-Book", "created_by" : { "id" : 1, "username" : "Test"} } ] } Any suggestions? Thank you -
Django - Indentation Error - (Submitting form with an Image field) [duplicate]
I'm trying to get my head around forms in Django at the moment (Still at the early stages of learning) although, I have managed to successfully submit post content data through my form, but I'm struggling with getting an image to upload. class CreateNewPost(LoginRequiredMixin, CreateView): model = Post fields = ['content', 'image'] template_name = 'post/post_new.html' success_url = '/' @login_required def post_image(self, form): form=upload() if request.method == 'POST': form = upload(request.POST, request.FILES) return render(request, 'post/post_new.html', {'form': form}) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data['tag_line'] = 'Create a new post' return data The error in which I receive is: IndentationError at /posts/ unindent does not match any outer indentation level (views.py, line 149) Thanks, Jay -
How do I specify the hostname of the callback uri when using python-social-auth?
I'm using python-social-auth inside Django, so social-auth-app-django to be exact. The application is only an API for a single page application that acts as the frontend. The server that serves the frontend proxies requests to the backend, to avoid any issues with CORS, third party cookies, etc. This means you visit example.com, the SPA loads and makes requests to example.com/api which gets proxied to api.example.com/api. example.com is a NodeJS simple server, and api.example.com is the Django application. The URLs for the backend look something like this: urlpatterns = [ path("admin/", admin.site.urls), path("social-auth/", include("social_django.urls", namespace="social")), path("api/", include(router.urls)), path("api-auth/", include("rest_framework.urls")), path("", views.home, name="home"), ] api and social-auth are proxied. The front end has a link to start the authentication process to /social-auth/login/facebook/. That works, gets redirected to Facebook, but then when Facebook redirects back instead of landing on example.com/social-auth/... it lands on api.example.com/social-auth which fails with the error: "Session value state missing." How can I specify the redirect_uri sent to Facebook to be example.com instead of the default api.example.com? I'm aware that one possible solution is to skip proxying and deal with CORS/cookies/tokens, but I'm trying to get it working with proxying in this Stack Overflow question. -
Displaying tasks under specific project in django
HI I am currently trying to develop a project management system. I am stuck at showing tasks related to a particular project when I view project details model.py looks like this class Project(models.Model): name = models.CharField(max_length=50) start_date = models.DateField(default=date.today) due_date = models.DateField(default=date.today) progress = models.CharField(max_length=20, choices=progress) status = models.CharField(max_length=20, choices=status) priority = models.CharField(max_length=20, choices=priority) def __str__(self): return self.name def total_projects(self): return Project.objects.all().count() def get_absolute_url(self): return reverse('projects:project_list') class Task(models.Model): title = models.CharField(max_length=50) project = models.ForeignKey(Project, related_name="tasks", on_delete=models.CASCADE) priority = models.CharField(max_length=20, choices=priority) status = models.CharField(max_length=20, choices=status) assigned = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return '%s - %s' % (self.project.name, self.title) def get_absolute_url(self): return reverse('projects:add_task') views.py looks like this class ProjectListView(ListView): model = Project template_name = 'projects/project_list.html' class ProjectDetailView(DeleteView): model = Project template_name = 'projects/project_detail.html' def get_context_data(self, *args, **kwargs): projects = Project.objects.order_by('id') context = super(ProjectDetailView, self).get_context_data(*args, **kwargs) context["projects"] = projects return context I have tried searching the net, nothing is clear -
Stripe -> issue when configuring a customer portal through code
I am not able to update plan from the stripe customer portal(Manage billing portal) after configuring the portal through code. update_to = [settings.MONTHLY_FS_PRICE_ID, price_id] #list of price_id portal_config = stripe.billing_portal.Configuration.create( features={ "customer_update": { "allowed_updates": ["email"], "enabled": True, }, "invoice_history": {"enabled": True}, "payment_method_update": {"enabled": True}, "subscription_cancel": { "enabled": cancel_enabled, "mode": "immediately" }, "subscription_update": { "default_allowed_updates":["price", "promotion_code"], "enabled": True, "products": [ { "product": product_id, "prices": update_to } ], "proration_behavior": "always_invoice" } }, business_profile={ "privacy_policy_url": privacy_policy_url, "terms_of_service_url": terms_url, }, ) session = stripe.billing_portal.Session.create( customer=request.workspace.subscription.stripeCustomerId, configuration=portal_config, return_url='http://'+settings.CURRENT_SITE_URL+'/w/dashboard' ) return redirect(session.url) The error in the billing portal during updating to a different plan-> { "error": { "message": "This subscription cannot be updated to the specified pricing structure.", "type": "invalid_request_error" } } Updating plan works when using the default customer portal configured through no-code(i.e from the dashboard settings) but I want to configure through code for more customisation -
i try to run my code but keep getting the "NoReverse match at/" error
When i run the code, i keep getting this error. NoReverseMatch at / Reverse for 'panel-index' not found. 'panel-index' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'panel-index' not found. 'panel-index' is not a valid view function or pattern name. Exception Location: C:\Users\Daniel Litumbe\Desktop\Camtel\Camvir\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\Daniel Litumbe\Desktop\Camtel\Camvir\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\Daniel Litumbe\Desktop\Camtel\Camvir\inventory', 'c:\users\daniel ' 'litumbe\appdata\local\programs\python\python38-32\python38.zip', 'c:\users\daniel ' 'litumbe\appdata\local\programs\python\python38-32\DLLs', 'c:\users\daniel ' 'litumbe\appdata\local\programs\python\python38-32\lib', 'c:\users\daniel litumbe\appdata\local\programs\python\python38-32', 'C:\Users\Daniel Litumbe\Desktop\Camtel\Camvir', 'C:\Users\Daniel Litumbe\Desktop\Camtel\Camvir\lib\site-packages'] Server time: Tue, 25 May 2021 08:21:09 +0000 Error during template rendering In template C:\Users\Daniel Litumbe\Desktop\Camtel\Camvir\inventory\templates\partials\nav.html, error at line 4 Reverse for 'panel-index' not found. 'panel-index' is not a valid view function or pattern name. 1 <!--Navbar--> 2 <nav class="navbar navbar-expand-lg navbar-info bg-info"> 3 <div class="container"> 4 <a class="navbar-brand text-white" href="{% url 'panel-index' %}">Camtel Inventory</a> 5 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> 6 <span class="navbar-toggler-icon"></span> 7 </button> 8 9 <div class="collapse navbar-collapse" id="navbarSupportedContent"> 10 <ul class="navbar-nav mr-auto"> 11 <li class="nav-item active"> 12 <a class="nav-link text-white" href="{% url 'panel-index' %}">Home <span class="sr-only">(current)</span></a> 13 </li> 14 <li class="nav-item"> **Below are the views and urls of the code** **urls.py** … -
I am trying to set up django signals to let someone get noticed after creating a blog
but this code does not work... keep error message like 'TypeError at /blog/create/ Here are the codes I put at blog/signals.py @receiver(signals.post_save, sender=Post) def send_mail(sender, instance, created, **kwargs): print('signal send') subject = "Thank you" message = Post.objects.get(??) send_mail(subject, 'message', '', ['info@*****.com.au'], fail_silently=False, ) ?? is the problem... I put pk=pk, pk=id, I don't know what parameter I need to put here... -
Django : bulk upload with confirmation
Yet another question about the style and the good practices. The code, that I will show, works and do the functionality. But I'd like to know is it ok as solution or may be it's just too ugly? As the question is a little bit obscure, I will give some points at the end. So, the use case. I have a site with the items. There is a functionality to add the item by user. Now I'd like a functionality to add several items via a csv-file. How should it works? User go to special upload page. User choose a csv-file, click upload. Then he is redirected to the page that show the content of csv-file (as a table). If it's ok for user, he clicks "yes" (button with "confirm_items_upload" value) and the items from file are added to database (if they are ok). I saw already examples for bulk upload for django, and they seem pretty clear. But I don't find an example with an intermediary "verify-confirm" page. So how I did it : in views.py : view for upload csv-file page def upload_item_csv_file(request): if request.method == 'POST': form = UploadItemCsvFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file_name = handle_uploaded_item_csv_file(request.FILES['item_csv_file']) request.session['uploaded_file'] = … -
Adding a certain number of hours to the date and time
I have a string in the following format 2021-05-06 17:30 How do I convert this to a date and time and add a certain number of hours to a given row? For example 4 I also need to add a certain number of days to the line 2021-05-06 -
Allow related field in post request in DRF
I have created model with many to many relationship and I have join table when I keep additional variable for it: class BorderStatus(models.Model): STATUS_CHOICES = [("OP", "OPEN"), ("SEMI", "CAUTION"), ("CLOSED", "CLOSED")] origin_country = models.ForeignKey(OriginCountry, on_delete=models.CASCADE, default="0") destination = models.ForeignKey(Country, on_delete=models.CASCADE, default="0") status = models.CharField(max_length=6, choices=STATUS_CHOICES, default="CLOSED") extra = 1 class Meta: unique_together = [("destination", "origin_country")] verbose_name_plural = "Border Statuses" def __str__(self): return ( f"{self.origin_country.origin_country.name} -> {self.destination.name}" f" ({self.status})" ) Other models: # Create your models here. class Country(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name='Country') class Meta: verbose_name_plural = "Countries" def __str__(self): return self.name class OriginCountry(models.Model): origin_country = models.ForeignKey( Country, related_name="origins", on_delete=models.CASCADE ) destinations = models.ManyToManyField( Country, related_name="destinations", through="BorderStatus" ) class Meta: verbose_name_plural = "Origin Countries" def __str__(self): return self.origin_country.name Here is my serializer for the endpoint: class BorderStatusEditorSerializer(serializers.ModelSerializer): """Create serializer for editing single connection based on origin and destination name- to change status""" origin_country = serializers.StringRelatedField(read_only=True) destination = serializers.StringRelatedField(read_only=True) class Meta: model = BorderStatus fields = ('origin_country', 'destination', 'status') And my endpoint: class BorderStatusViewSet(viewsets.ModelViewSet): queryset = BorderStatus.objects.all() serializer_class = BorderStatusEditorSerializer filter_backends = (DjangoFilterBackend,) filter_fields=('origin_country','destination') The problem Im having is that I cant create any new combination for the BorderStatus model in this serializer via post request. If I remove the lines: … -
DJango - How To pass the full model object as new field in serializer
I want to pass the full Artist model object to the Serializer so I created a new Field serializers.SerializerMethodField and passed Artist object inside it. but I get the error. getattr(): attribute name must be string class ArtistSerializer(serializers.ModelSerializer): similar_artists = serializers.SerializerMethodField(Artist.objects.all()) class Meta: model = Artist fields = ('id', 'artist_name', 'albums', 'similar_artists') I guess I'm doing it totally wrong. so is there any way to pass all values or all Artists in single object with serializer with a manual field. I want to achieve something like this in serializer. { "id": 1, "albums": [ { "id": 1, "album_name": "Fearless (Taylor's Version)" }, { "id": 7, "album_name": "Reputation" }, { "id": 8, "album_name": "1989" } ], "artist_name": "Taylor Swift", "similar_artists": [ { Artist Object } ] }, -
Django order by nested foreignkey
models.py: class Address(models.Model): text = models.TextField(max_length=2060, null=True, blank=True, default=None, unique=True) class Tag(models.Model): text = models.CharField(max_length=255, null=True, blank=True, default=None, unique=True) class AddressTagJoin(models.Model): address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True, blank=True, related_name='address_tag_join') tag = models.ForeignKey(Tag, on_delete=models.CASCADE, null=True, blank=True, related_name='address_tag_join') In above, Address and Tag objects are only used as AddressTagJoin's foreignkey target. What I want to do is two kind of queryset.. When I got address "https://www.google.com", I want to get Tag queryset ordered by most used for Address (text = "www.google.com") Tag.objects.order_by(count_of_AddressTagJoin_and_It's_address_foreignkey_is_for_"www.google.com") In reverse, I got tag "google", I want to get Address queryset ordered by most how many used for Tag (text="google") Address.objects.order_by(count_of_AddressTagJoin_and_It's_tag_foreignkey_is_for_"google") How can I do that? -
How to send message to user in a Django Thread?
I have a long time execution function that I run in a Thread to avoid blocking the user during the process. But I have a problem when I want to notify the user at the end of this function to tell him that it's done (and tell him if it was a success or an error). I tried to use django.contrib.messages but unsuccessful. Here is my code simplified : from threading import Thread from django.contrib import messages def my_view(request): thread =Thread(target=run_creation, args=[request], daemon=True) thread.start() return render(request, 'main/home.html') def run_creation(request): print("sleep start") time.sleep(20) print("sleep end") messages.add_message(request, messages.INFO, 'Hello word') The problem is that I can't see the message in my template. Here is my template : {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} Thanks a lot for your help