Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filefield in django Model, hide the link to file and clear box in template
I have a model Test with a filefield: class Test(models.Model): file = models.FileField(upload_to='file', blank=True, null=True) In the template i render it via the form: class TestForm(forms.ModelForm): class Meta: model = Test fields = '__All__' In the template i do: <td class="tg-0lax">{{ test.file }}</td> In the template its working fine, i gat the file upload possibility But this also shows the clickable link to the file in the template. I dont want that. So i want to render it buy without the link to the file (only the upload possibility) Is this possible -
Django Serializer How to loop over dictionary value and return in serializer
I have following dictionary inside list self.passengers = [{'first_name':'Harry','last_name':'kane'},{'first_name':'cristiano','last_name':'aviero'} I Have set my serializer as following class PassengerSerializer(serializers.Serializer): first_name = serializers.CharField() last_name = serializers.CharField() class TicketDetailSerializer(serializers.Serializer): passenger = PassengerDetailSerializer(many=True) I have set my code as following to extract passenger data 'passenger': [{ 'lastname': [passenger['lastname'] for passenger in self.passengers], 'firstname': [passenger['firstname'] for passenger in self.passengers] }], But I am only getting firstname ->'harry' and lastname-> kane what shall I do next to get all dictionary of first name and last name is self.passengers? -
Django dropdown list not saving value
I have a dropdown list box on my django form that shows a correct list of options but the problem I am facing is that the form is not saving the selected value. When I press a submit button, I receive the following error message 'This field is required'. Below is the code that I currently using. I simply can't figure out what I am doing wrong. Models.py ASSET_TYPE = ( ('0','0'), ('1','1'), ('2','2'), ('3','3'), ('4','4') ) asset = models.CharField(max_length=200,choices=ASSET_TYPE) forms.py class ApplicationForm(forms.ModelForm): class Meta: model = Enquiry fields = ['asset'] asset = forms.ChoiceField(choices=ASSET_TYPE, required=True) HTML <div class="container asset-type"> <div class="row justify-content-center"> <div class="col-lg-4"> <div class="form-group"> <div class="styled-select"> <select id="asset" name="asset_type_form"> {% for field in form.asset %} <option value="{{ field.id_for_label }}">{{ field.choice_label }}</option> {% endfor %} </select> </div> </div> </div> </div> </div> Can anyone please help? Thanks. -
Not sure why im getting a (CSRF token missing or incorrect.) error in django
HTML: {% extends 'generic.html' %} {% load static %} {% block title %} <title>Projects - Login</title> {% endblock %} {% block content %} <form action='#', method='post'> {% csrf_token %} <label for="username">Username</label> <input type="text" name="username" id="username"> <label for="password">Password</label> <input type="password" name="password" id="password"> <input type='submit' value='Login!'> </form> {% endblock %} views.py: def login(request): return render(request, 'login.html') urls.py: urlpatterns = [ path('login/', views.login, name='login') ] I have tried putting a @csrf_protect decorator on the login function. however I still get the same error. -
Django redirect not working in authentication
I am trying to authenticate a registered user . redirect is not working in my case. after clicking the login button it keep on showing the login page again. i want the user to go to home page upon the successful login. Here are my files. views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.contrib import messages from django.contrib.auth import authenticate, login, logout def loginUser(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: # at backend authenticated the credentials login(request, user) return redirect('home') return render(request, 'login_a.html') urls.py from django.contrib import admin from django.urls import path from home import views urlpatterns = [ path("", views.index, name='home'), path("login", views.loginUser, name='login'), path("logout", views.logoutUser, name='logout'), #path("register", views.register, name='register'), path("register_new_a", views.register_new_a, name='register_new_a'), path("register_new_b", views.register_new_b, name='register_new_b'), path("about", views.about, name='about'), ] Any help would be appreciated. -
Error loading shared library when trying to deploy django using nginx and docker
I have been following a tutorial to deploy a django project to docker. Both docker files work independently but when I run the docker-compose-deploy.yml I get the following error: app_1 | app_1 | 128 static files copied to '/vol/web/static', 3 unmodified. app_1 | Error loading shared library libxml2.so.2: No such file or directory (needed by /usr/local/bin/uwsgi) app_1 | Error relocating /usr/local/bin/uwsgi: xmlDocSetRootElement: symbol not found app_1 | Error relocating /usr/local/bin/uwsgi: xmlCheckVersion: symbol not found app_1 | Error relocating /usr/local/bin/uwsgi: xmlNewTextChild: symbol not found app_1 | Error relocating /usr/local/bin/uwsgi: xmlNewChild: symbol not found app_1 | Error relocating /usr/local/bin/uwsgi: xmlNewDoc: symbol not found app_1 | Error relocating /usr/local/bin/uwsgi: xmlReadMemory: symbol not found app_1 | Error relocating /usr/local/bin/uwsgi: xmlNewNode: symbol not found app_1 | Error relocating /usr/local/bin/uwsgi: xmlDocDumpFormatMemory: symbol not found app_1 | Error relocating /usr/local/bin/uwsgi: xmlCleanupParser: symbol not found app_1 | Error relocating /usr/local/bin/uwsgi: xmlFreeDoc: symbol not found app_1 | Error relocating /usr/local/bin/uwsgi: xmlDocGetRootElement: symbol not found app_1 | Error relocating /usr/local/bin/uwsgi: xmlGetProp: symbol not found app_1 | Error relocating /usr/local/bin/uwsgi: xmlFree: symbol not found proxy_1 | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration proxy_1 | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ proxy_1 | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh app_1 … -
How to fix missing 1 required positional argument 'request' error?
TypeError at /risk/riskset get_context_data() missing 1 required positional argument: 'request'. See code here: models.py class RiskSet(models.Model): name = models.CharField('Risk set', max_length=500, blank=True, default = '') owner = models.ForeignKey(User, verbose_name = 'owner', on_delete=models.PROTECT, null=True) risk = models.ForeignKey(Risk, verbose_name = 'risk', on_delete=models.PROTECT, null = True) parent_risk_set = models.ForeignKey('self', related_name="child_risk_set", on_delete=models.PROTECT, blank=True, null=True) def __str__(self): return "{}".format(self.name) forms.py class RiskSetForm(forms.ModelForm): RiskID1 = forms.ModelMultipleChoiceField(queryset=Risk.objects.all(), required=True, widget=forms.SelectMultiple(attrs={'class': 'select2'}), label = 'Risk id') def __init__(self, *args, **kwargs): super(RiskSetForm, self).__init__(*args, **kwargs) print(self) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class Meta: model = RiskSet fields = ['name', 'owner', 'risk', 'parent_risk_set'] views.py class RiskSet(FormView, SingleTableMixin): template_name = "risk/RiskSet.html" model = RiskSet form_class = RiskSetForm def get_context_data(self, request): form = RiskSetForm(request.POST or None) if form.is_valid(): form.save() # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['page'] = 'risk' return context Now I get the error: TypeError at /risk/riskset get_context_data() missing 1 required positional argument: 'request' Please help! -
How does Django handle the logins of different users on a deployed website?
Several questions (I started learning Django last week and don't know what to search in the docs). How does Django handle different user logins? To elaborate, I am the only user that can perform a login and logout procedure when I locally run the server on my machine. I am already logged in as 'farid' (my superuser username). Imagine I deploy this website with full authentication functionality, will other new users be logged in as 'farid'? Or will Django somehow identify them as not being me and have them register? How does this procedure work (is it IP based)? Lastly, can I get the links to some good resources on this matter? -
best way to deploy django app for faster loading
I have created a Django app. it uses a bit more images and one page includes videos as well. the storage is on S3 AWS bucket on US East (N. Virginia) us-east-1. Database is also in Asia Pacific (Mumbai)ap-south-1, AWS RDS PostgreSQL. the app itself is hosted on Heroku. I had also upgraded Heroku plan to professional so to get the best performance. when access the landing page, its fast enough. but after the login and each pages on dashboard, it takes so much time to refresh or load. it takes almost 4 to 10 sec. I also tried hosting on AWS, EC2. but same story. as I am new to deployments and optimizations, I would be so glade in any advise to overcome this. -
Requested setting DEBUG, but settings are not configured. django.core.exceptions.ImproperlyConfigured
I am trying to deploy django application onto linux server. When running django-admin runserver via terminal in CPanel receiving the following error: django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried to export an environment variable: export DJANGO_SETTINGS_MODULE=mysite.settings. After that I got ModuleNotFoundError: No module named 'mysite' Also, i tried import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", __file__) import django django.setup() on the top of my settings.py file. It still does not work. My wsgi.py file at the moment: from sbiweb.wsgi import application -
Getting the first tuple in a list of tuples in python, django
I have a list of tuples called job_details in this format [(job, company, salary)] I have sorted them with the highest salary like this: job_details.sort(key=lambda a: a[2], reverse=True) Next, I want to have only the first result so that I can give a link "Show more" In my view how do I display that detail? Like a list with a single record. Should I use the for loop? Thank you -
POST /post/29/ HTTP/1.1" 405 0
I made comments in a post on my blog on django, when I enter data in the "Name" field and the "Body" field, then I press "Submit" this error appears POST /post/29/ HTTP/1.1" 405 0 models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType class Post(models.Model): published = None title = models.CharField(max_length=200) author = models.ForeignKey('auth.User', on_delete=models.CASCADE, ) body = models.TextField() header_image = models.ImageField(blank=True, null=True, upload_to="images/") def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255, default="Some String") body = models.TextField(max_length=255, null=True, blank=True) #date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) forms.py from django.forms import ModelForm from .models import Comment class CommentForm(ModelForm): class Meta: model = Comment fields = ['name', 'body'] views.py from django.shortcuts import render, redirect from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .forms import CommentForm from .models import Post class BlogListView(ListView): model = Post template_name = 'home.html' context_object_name = 'posts' paginate_by = 2 queryset = Post.objects.all() #paginate_by = 2 #model = Contact class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' class BlogCreateView(CreateView): model = Post template_name = 'post_new.html' fields … -
Form field in django should not be none
I have this form in django. class userRequest(forms.Form): lat_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_Origin"}),required=False,initial=181) lon_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_Origin"}),required=False,initial=181) lat_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_Dest"}),required=False,initial=181) lon_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_Dest"}),required=False,initial=181) origin_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={"class":"data_aux data","id":"origin_address"})) destination_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={"class":"data_aux data","id":"destination_address"})) When I print form.cleaned_data: {'lat_Origin': None, 'lon_Origin': None, 'lat_Dest': None, 'lon_Dest': None, 'origin_address': 'Calle San Amaro, 1A, 09001 Burgos, España', 'destination_address': "Calle de O'Donnell, Madrid, España", 'date': datetime.date(2021, 6, 12), 'maxPrice': None, 'OrderType': 'NONE', 'OrderBy': 'PRICE'} I don't know why lat_Origin, lon_Origin, lat_Dest, lon_Dest are none. I am using JS google maps api. I want to save coordinates values into lat_Origin, lon_Origin, lat_Dest, lon_Dest. I obtain latitude and longitude data correctly using google maps geocoder (I have printed them with console.log) but I don`t know why they are finally none. document.getElementById('lat_Origin').value = lat; document.getElementById('lon_Origin').value = lng; document.getElementById('lat_Dest').value = lat; document.getElementById('lon_Dest').value = lng; -
AttributeError: 'AnonymousUser' object has no attribute '_meta' error using a custom registration form
Good Day! I'm trying to make the user of my website register and login with only the email, but I'm getting this error: AttributeError: 'AnonymousUser' object has no attribute '_meta' Even if I've this error the account is saved in the database, but I can't login (I've the same error for both registration and login). This is my code: views.py def register_view(request, *args, **kwargs): user =request.user if user.is_authenticated: return HttpResponse(f"You are already authenticated as {user.email}.") context = {} if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email').lower() raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account, backend= 'django.contrib.auth.backends.AllowAllUsersModelBackend') destination = get_redirect_if_exists(request) if destination: return redirect(destination) return redirect("home") else: context['registration_form'] = form return render(request, 'registration/register.html', context) def logout_view(request): logout(request) return redirect("home") def login_view(request, *args, **kwargs): context = {} user = request.user if user.is_authenticated: return redirect("home") if request.POST: form = AccountAuthenticationForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user =authenticate(email=email, password=password) if user: login(request, user, backend= 'django.contrib.auth.backends.AllowAllUsersModelBackend') destination = get_redirect_if_exists(request) if destination: return redirect(destination) return redirect("home") else: context['login_form'] = form return render(request, "registration/login.html", context) def get_redirect_if_exist(request): redirect = None if request.GET: if request.GET.get("next"): redirect = str(request.GET.get("next")) return redirect Also this is not the first error I'm getting, … -
Django query certain attribute via foreign key
I want to query certain data from a foreign key class. Is there a way to make it directly in the query? I want to do the following query: plant_list = Plant.objects.filter(plant_product = ikey).values('plant_number', 'plant_name', 'plant_city', 'plant_country', 'plant_product') My Result is: {'plant_number': '0001', 'plant_name': 'HoP1', 'plant_city': 3, 'plant_country': 1, 'plant_product': 1} Now, for example at plant_city. I don´t want to have the ID I want to have the attribute city_name of the model City, which is the Foreign Key. Is there a elegant way? That would be a very graet help! Here are my Models: class City(models.Model): city_name = models.CharField(max_length=100, unique=True) class Meta: ordering = ['city_name'] # changes view in admin area verbose_name_plural = ('Cities') def __str__(self): return self.city_name class Country(models.Model): country_name = models.CharField(max_length=100, unique=True) class Meta: ordering = ['country_name'] verbose_name_plural = 'Countries' def __str__(self): return self.country_name class Plant(models.Model): plant_number = models.CharField(max_length=10, unique=True) plant_name = models.CharField(max_length=10, unique=True) plant_city = models.ForeignKey(City, on_delete=models.CASCADE) plant_country = models.ForeignKey(Country, on_delete=models.CASCADE) plant_product = models.ManyToManyField(TPZProductCluster1) updated_at = models.DateField(auto_now=True) class Meta: ordering = ['plant_number'] def plant_produces(self): return ', '.join([p.pc1_product for p in self.plant_product.all()]) def __str__(self): return self.plant_name + " (" + str(self.plant_number) +")" Thank you in advance!!! -
DRF ModelViewSet is possible to create custom @action with same url and different methods
I have custom function with @action decorator for routing with two methods GET and DELETE. Everything works ok if code is in same function and I can run different operations with simple if: @action(methods=['GET', 'DELETE'], detail=False, url_path='current', url_name='profile-current', permission_classes=[IsAuthenticated]) def get_current_profile(self, request: Request, **kwargs) -> Response: if self.request.method == 'DELETE': ... However I would like to separate the code into two functions still with same route, but different method. If I separate code into two functions and same url-path and different methods, one of the methods returns method not available error. Am I missing something here or is not possible to create methods in the way I thought it should work. -
AttributeError: 'ListSerializer' object has no attribute 'initial_data'
Everyone, hi, i have issue but i'm lost, because i'm new in the project. Please give some advice, how to solve it. I'm have 2 endpoints: path( "v1/balance/client/<int:pk>/", ClientsAuditAPIView.as_view(), name="audit-headers-client-detail", ), path( "v1/balance/client/header/bulk-update/", ClientsAuditBulkUpdateView.as_view(), name="audit-headers-client-bulk-update", ) and two serializers: class BalanceClientSerializer(serializers.Serializer): FIELDS_IN_ORDER = ['distribId', 'level', 'percentage', 'part', 'comment'] distribId = serializers.IntegerField(allow_null=False, required=True, min_value=0) level = serializers.IntegerField(allow_null=False, required=True, min_value=0) percentage = serializers.IntegerField(allow_null=True, required=False, min_value=0) part = serializers.IntegerField(allow_null=True, required=False, min_value=0) comment = serializers.CharField(allow_null=True, required=False) @staticmethod def clean_number_fields(instance): for row in instance.initial_data: for field in ('percentage', 'part'): if row.get(field) == '': row.pop(field) @classmethod def many_init(cls, *args, **kwargs): instance = super().many_init(*args, **kwargs) print('instance', instance) cls.clean_number_fields(instance) return instance @staticmethod def wrap_in_dict(rows: Iterable) -> List[dict]: """Wraps iterable of rows in list of dictionaries. Order of values in rows matter!""" fields = BalanceClientSerializer.FIELDS_IN_ORDER return [{field: row[idx] for idx, field in enumerate(fields)} for row in rows] class BalanceClientBulkUpdateSerializer(serializers.Serializer): head_ids = serializers.ListField(child=serializers.IntegerField()) rows = BalanceClientSerializer(many=True) When i run the test i got AttributeError: 'ListSerializer' object has no attribute 'initial_data' It's come from rows = BalanceClientSerializer(many=True) Before validating i need to clean my data by function clean_number_fields In my view's: data = request.data['_content'] if '_content' in request.data else request.data serializer = BalanceClientBulkUpdateSerializer(data=data) ``` -
Swiper slide background
help. I do not know how to set the image to the background via thumbnail? I need to insert the background via thumbnail. How can i do it? <section class="slider"> <div class="swiper-container"> <div class="swiper-wrapper"> {% for new in news %} {% load thumbnail %} **<div class="swiper-slide" data-background="{% static 'images/slide01.jpg' %}"> ** <div class="slide-inner"> {% thumbnail new.image_1 "1280x720" crop="center" upscale=True as im %} <figure><img src="{ im.url} " alt="Image"></figure> {% endthumbnail %} <h2>{{ new.text|truncatechars:120 }}</h2> <div class="link"> <a href="{ blog_single new.id} ">SEE CASE STUDY</a> </div> <!-- end link --> </div> <!-- end slide-inner --> </div> <!-- end swiper-slide --> {% endfor %} <!-- end swiper-slide --> </div> -
Dynamic home page based on visitor's city django
I'm working on a web app where one can consult a rating of some specific companies. My goal is to develop a dynamic home page that shows top-3 companies in a visitor's city. We use Django 3.2, python 3.7, SQlite. I'm lost on what solution to use: Geodjango with Geoip2 (which seems to be too complicated for such a trivial task) or HTML5 geolocation API (which seems to be easier, but I don´t understand at the moment how to implement it in django). Any advice? -
how to pass custom attribute value from "select option" form to view in django
i have an html form inclouds select input , and the option have extra attribute value called "testvalue" , and want to pass the "testvalue" to my views, and here is my example as the following : <select class="form-control select2" name="q_post_id" > <option disabled selected >Select Post</option> {% for post in all_posts %} <option value="{{post.item.id}}" testvalue = "my test value" > {{post.item.message}}</option> {% endfor %} </select> normally in my view function i use : q_post_id = request.POST.get("q_post_id") but this will give me a default value "{{post.item.id}}", so how can i get the extra attribute in view ? thanks. -
Django admin.py How to show a foreign key field of a model
In models.py I have two models created class Tutor(models.Model): ... class Case(models.Model): tutor_applied = models.ManyToManyField( Tutor, related_name="case_set", default=None, blank=True, ) In admin.py, I am trying something like class TutorAdmin(admin.ModelAdmin): fieldsets = [ ( None, { "fields": [ "case_set", ] }, ) ] which does not work, showing this error Unknown field(s) (case_set) specified for Tutor. Check fields/fieldsets/exclude attributes of class TutorAdmin. I have tried also tried: class TutorAdmin(admin.ModelAdmin): def case_set(self): u = self.case_set if u is not None: return u.case_set fieldsets = [ ( None, { "fields": [ case_set, ] }, ) ] which shows this error sequence item 0: expected str instance, function found How can I work around this to show the 'case_set' field? I expect to see something like this in the 'Tutor' admin form, but instead with case_set -
Testing Django view
I'm trying to test the following view def generate_exercise_edl(request, ex_pk, unit_pk, *args, **kwargs): ex_instance = Exercises.objects.get(id=ex_pk) unit_instance = Units.objects.get(id=unit_pk) unit_edl = UnitEdl.objects.filter(unit=unit_instance) locations = Locations.objects.all() unit_edl = list(unit_edl) print(request) print(request.POST) print(request.user) if request.method == "POST": for item in unit_edl: ExerciseEdl.objects.update_or_create(unit=unit_instance, exercise=ex_instance, equipment=item.equipment, quantity=item.quantity, location=Locations.objects.get(location="Okinawa")) print(request) return redirect('exercise-equipment', ex_pk=ex_pk, unit_pk=unit_pk) else: messages.error( request, f'Failed to add/update the {unit_instance.unit_name} edl for {ex_instance.exercise}.') context = { 'ex_instance': ex_instance, 'unit_instance': unit_instance, 'unit_edl': unit_edl, 'locations': locations, } return render(request, 'exercise/exercise_edl.html', context) This is my test code def test_generate_edl(self): unit_edl = UnitEdl.objects.filter(unit=unit.pk) for edl in unit_edl: ExerciseEdl.objects.update_or_create( unit=unit, exercise=ex, equipment=edl.equipment, quantity=edl.quantity, location=loc ) response = self.client.post( f'/exercise/{ex.pk}/edl/{unit.pk}/convert/') ex_edl = ExerciseEdl.objects.all().count() self.assertEquals(ex_edl, 2) self.assertEqual(response.status_code, 302) This is the URL for the view path('exercise/<int:ex_pk>/edl/<int:unit_pk>/convert', views.generate_exercise_edl, name='generate-edl'), And the part of the template that calls my function <form action="{% url 'generate-edl' ex_pk=ex_instance.id unit_pk=unit_instance.id %}" method="post"> {% csrf_token %} <input class="btn btn-primary btn-sm mt-2" type="submit" value="Generate EDL"> </form> My test returns 404, not 302, but the function on the site works, and redirects you. f'/exercise/{ex.pk}/edl/{unit.pk}/convert/' isn't mapped to any template, it's just the url for the function. In the past my tests have returned a status code of 404 when I wrote the post data incorrectly. print(request.POST) returns: <QueryDict: {'csrfmiddlewaretoken': … -
Celery, Where does celery retrieve list of tasks schedule?
I have a django app and it runs tasks fine. I want to define some more celery tasks which are not run (by our web server). These tasks are purely analytics related and I want to run these tasks in dev servers. So I created another Celery app that has these analytics-related tasks defined only. I want to run celery worker --app=analytics to run these newly-defined periodic tasks, but don't want to run all the tasks I defined previously(for our web service) When I run celery worker --app=analytics, it keeps finding the tasks which were previously registered for the web service. So I removed all the imports I could find to remove the celery tasks (mainly proj/proj/__init__.py file where it imports celery) However it keeps finding the old tasks only.. (not the full list but partial list of previously defined tasks..) ? Where does celery get the list of registered tasks? How can I make sure to tell my new celery to include only newly-defined tasks (in a separate file)? I tried to change BROKER_URL and CELERY_RESULT_BACKEND hoping maybe something is stored there, but it didn't fix the issue -
Why Page not found (404) while accessing child record in Onetomany relation in Django?
I am working on a small Django project and created OneToMany Relation between two models(say Products and Sub_Products). And my project contains two urls first to get all the data in products table and other link is to get related products associated with particular product. I am passing product-id from template to view as follows:- <a href='sub/{{ x.id }}'><img src="{{x.pic.url}}" alt="" class="card-img-top" height="200px"></a> url.py :- urlpatterns = [ path('admin/', admin.site.urls), path('home/', home_page_view, name='homepage'), path('sub/<int:id>/', product_sub, name='relatedproducts'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) view Functions:- def product_sub(request, id): var = Products.objects.get(id=id) querysets = Sub_Products.objects.filter(products=var) context = { "object_list": querysets } print(context) return render(request, "subproducts.html", context) Now when ever i am clicking on the image-link to get related project i am getting Page not found (404). But if i am using Shell to access the Sub_Products, i am getting desired output. Please help to let me know what i am going wrong. Hope to here from you soon. Thanks in advance. -
Django queryset grouping and filtering
I'm writing a query for a hotel availability search. my models look like this: hotel => room (FK hotel) => rateplan (FK room) => price(each price is a separate date with availability number) (FK rateplan) I'm trying to find all hotels that have at least one room with occupancy equal or greater than 1 AND at least one rateplan where ALL availability within certain daterange is no less than 0. My models: class Hotel(models.Model): name = models.CharField(max_length=100) city = models.CharField(max_length=100) class Room(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name='rooms') name = models.CharField(max_length=100) occ_adult = models.IntegerField() class Rateplan(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='rateplans') name = models.CharField(max_length=30) class Price(models.Model): date = models.DateField(null=True) availability = models.SmallIntegerField() rateplan = models.ForeignKey(Rateplan, on_delete=models.CASCADE, related_name='prices') price_1 = models.DecimalField(max_digits=8, decimal_places=2) my query so far: h = Hotel.objects.filter(city='Warsaw', rooms__rateplans__availability__availability__gt=0, rooms__occupancy__gte=1, rooms__rateplans__availability__date__range=['2021-6-7', '2021-6-7']).distinct() also I have tried grouping rateplans using 'values' and annotating results but this returns dict rather than queryset: c1 = Hotel.objects.values('rooms__rateplans').filter(rooms__rateplans__prices__availability__gt=0) Any thoughts on this?