Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i display foreignkey data in a different html template?. Btw im new to django, so it's a bit confusing for me
my views.py def schedule_work(request): form = schedule_form() if request.method == 'POST': form = schedule_form(request.POST) if form.is_valid(): form.save() return redirect('view_schedulework') return render(request, 'schedule_work.html', {'form': form}) def view_schedulework(request): data = schedule.objects.all() return render(request, 'view_schedulework.html', {'data': data}) def update_schedulework(request, id): data = schedule.objects.get(id=id) form = schedule_form(instance=data) if request.method == 'POST': form = schedule_form(request.POST or None, instance=data or None) if form.is_valid(): form.save() return redirect('view_schedulework') return render(request, 'edit_schedulework.html', {'form': form}) def delete_schedulework(request, id): schedule.objects.get(id=id).delete() return redirect('view_schedulework') def available_schedules(request): data = appointment.objects.all() return render(request, 'available_schedules.html', {'data': data}) my models.py class customuser(AbstractUser): is_worker = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) address = models.TextField(null=True) experience = models.CharField(max_length=25, null=True) photo = models.ImageField(upload_to='profile', null=True) class schedule(models.Model): date_available = models.DateField() start_time = models.TimeField(null=True) end_time = models.TimeField(null=True) class appointment(models.Model): Customuser = models.ForeignKey(customuser, on_delete=models.CASCADE, null=True) Schedule = models.ForeignKey(schedule, on_delete=models.CASCADE, null=True) status = models.IntegerField(default=0) my html template for available_schedules <div class="card"> <div class="card-body"> <table class="table table-bordered"> <thead> <tr> <th>Sl No.</th> <th>name</th> <th>Available Date</th> <th>Starting Time</th> <th>Ending Time</th> <th>Schedule an appointment</th> </tr> </thead> <tbody> {% for appointment in data %} <tr> <td>{{ forloop.counter }}</td> <td>{{ appointment.Customuser.username }}</td> <td>{{ appointment.Schedule.date_available }}</td> <td>{{ appointment.Schedule.start_time }}</td> <td>{{ appointment.Schedule.end_time }}</td> <td><button class="btn btn-primary" type="submit">Book appointment</button></td> </tr> {% endfor %} </tbody> </table> </div> </div> {% endblock %} im trying to display the … -
Django MiddlewareMixin replacement
We have this Middleware class and test in Django 3.2, How do we update the code for Django 4.2.1 as we get required parameter get_response missing Middleware class lass CountryMiddleware(MiddlewareMixin): def process_request(self, request): country_code = helpers.get_country_from_querystring(request) if country_code: request.COUNTRY_CODE = country_code def process_response(self, request, response): """ Shares config with the language cookie as they serve a similar purpose """ if hasattr(request, 'COUNTRY_CODE'): response.set_cookie( key=constants.COUNTRY_COOKIE_NAME, value=request.COUNTRY_CODE, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_PATH, domain=settings.LANGUAGE_COOKIE_DOMAIN, secure=settings.COUNTRY_COOKIE_SECURE, httponly=True, ) return response Test @pytest.mark.parametrize('country_code,country_name', choices.COUNTRY_CHOICES) def test_country_middleware_sets_country_cookie( client, rf, country_code, country_name ): settings.COUNTRY_COOKIE_SECURE = True request = rf.get('/', {'country': country_code}) response = HttpResponse() request.session = client.session instance = middleware.CountryMiddleware() instance.process_request(request) instance.pprocess_template_response(request, response) cookie = response.cookies['country'] assert cookie.value == country_code -
Mocking attribute of a file in python fails
I am trying to mock a function call inside file here is the file dummy.py from core.connection_util import create_graphql_client config = settings.ABCD gql = create_graphql_client(config) print("debug", gql) # this print statemet is not coming either. def get_instance(): return gql unit test file test_dummy.py def test_get_instance(): with patch('dummy.adapter.create_graphql_client') as mocked_create_graphql_client: \# Configure the mock's behavior mocked_gql = 'Mocked GraphQL Client' mocked_create_graphql_client.return_value = mocked_gql # Call the function under test instance = get_instance() # Assertions assert instance == mocked_gql mocked_create_graphql_client.assert_called_once_with(settings.ABCD) I tried with mocker fixture too still no luck. Any help would be appriciated thanks. I am running things in pycharm community edition and I tried running the test via terminal as well no luck. -
How to format Django templates without having formatting white-space in the output?
I need to generate some txt files and Jinja2 used for Django templates causes the template code to look really messy, because I cannot use line-breaks without having them in the generated result. The {% spaceless %} tags would probably make things only messier as it will be hard to insert the wanted space. An example: [{% if foo.condition %}x{% else %} {% endif %}] List of requirements fulfilled: {{ foo.requirements_fullfilled }} of {{ foo.num_requirements }} {% for requirement in foo.requirement %} - {{ requirement.number }}{% if requirement.name %}: {{ solution.exercise.name }}{% endif %}{% endfor %}{% endif %} Note the linebreak before - which makes the list add a linebreak before each bullet point and the missing linebreaks for all other tags, as they would be visible in the output. Using spaceless would allow for formatting, but also remove the linebreak before the bullet points. Without spaceless the line looks quite messy. I also tried to use {# #} with a linebreak inside the comment as workaround, but multi-line comments need to use the {% comment %} template tag, which itself has a quite verbose name and would result in, for example: [{% if foo.condition %}{% comment %} {% endcomment … -
How to run async GraphQL schema.execute() inside Celery shared_task?
I'm using Strawberry with Django for GraphQL and I created a shared_task() which should execute this query on the Schema but I get this error: GraphQLError("'coroutine' object has no attribute 'items'") query_total = """ query MyQuery($filters: Filter!) { something(filters: $filters) { items { id } total } } """ @shared_task() def my_function(filters, request): context = CustomContext(request) loop = asyncio.get_event_loop() total_result = loop.run_until_complete(schema.execute(query_total, variable_values={"filters": filters}, context_value=context)) I call the function like this: my_function.delay(...) I tried already with async-await, async_to_sync with a wrapper function. -
Cannot assign "2022": "Profile.year_of_passing" must be a "Batch" instance
This is my model.py file from asyncio import constants import profile from django.contrib.auth.models import User from django.db import models from django.utils import timezone import datetime, os from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from model_utils import FieldTracker from time import strftime from applications.adminportal.mail_helper import send_verification_email class Constants: SEX_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other') ) ROLE_CHOICES = ( ('S','Student'), ('A','Alumni'), ) PROG_CHOICES = ( ('B.Tech', 'B.Tech'), ('B.Des', 'B.Des'), ('M.Des', 'M.Des'), ('M.Tech', 'M.Tech'), ('PhD', 'PhD') ) BRANCH = ( ('CSE', 'Computer Science and Engineering'), ('ECE', 'Electronics and Communication Engineering'), ('ME', 'Mechanical Engineering'), ('SM', 'Smart Manufacturing'), ('NS', 'Natural Sciences'), ('MT', 'Mechatronics'), ('DS', 'Design'), ('NA', 'Not Applicable') ) WORKING_STATUS = ( ('Is Working', 'Is Working'), ('Is Pursuing Higher Studies', 'Is Pursuing Higher Studies'), ('Is Self Employed', 'Is Self Employed') ) EMPLOYMENT_TYPE = ( ('ft', 'Full-time'), ('pt', 'Part-time'), ('se', 'Self-employed'), ('fr', 'Freelance'), ('in', 'Internship'), ('tr', 'Trainee'), ) `your text` YEAR_OF_ADDMISSION = tuple((n, str(n)) for n in range(2005, datetime.datetime.now().year)) ADMISSION_YEAR = tuple((n, str(n)) for n in range(1990, datetime.datetime.now().year + 1)) PASSING_YEAR = tuple((n, str(n)) for n in range(2005, datetime.datetime.now().year)) class Batch(models.Model): year_of_passing = models.IntegerField(primary_key=True) def __str__(self): return self.year_of_passing def upload_photo(instance, filename): name, extension = os.path.splitext(filename) return 'Profile_Pictures/' + str(instance.roll_no) + ".jpg" … -
Creating dynamic models in Appconfig.ready
I am working on a Django project for which I need to create dynamic models that are based on explicit/static models (i.e. classes in models.py). Right now I am using the class_prepared signal, but the models are not fully processed by Django yet at that time, which leads to reduced functionality. Is it possible to create dynamic models in the Appconfig.ready function? Code in the ready function will only be run after everything is properly initialized. If you create a dynamic model in that function, will it still be processed properly by Django or not? I've tried creating a model in the ready function, and it seems to work. I can access the _meta object and functions like _meta.get_fields() without errors. (Which is not possible before the ready function) I'm just scared that some internal Django stuff might work different because the model was created after Django is supposed to be done iniatializing. -
My {{ item.img.url }} doesnt work, doesnt even display url
So basicaly I am making an information panel and sometimes there needs to be a photo attached. I can assure you I searched the whole internet for the solution and yet after two hours I am here and need help. Please restore my sanity. My index.html - I am posting only the part where theres the {{ item.img.url }} <ul class="list-ohlasky"> {% for item in ohlasky %} <li class="polozka-ohlasky"> {{ item.den }}<br> {{item.text}}</li> {% if item.img %} <img src="{{ item.img.url }}" alt="PLS WORK"> {% else %} {% endif %} {% endfor %} </ul> My views.py from django.shortcuts import render from .models import Ohlasky from .models import Liturgicketexty from django.http import HttpResponse from django.template import loader # Create your views here. now = datetime.datetime.now() def index(request): order = Ohlasky.objects.all().order_by('den').values() order1 = Liturgicketexty.objects.all().order_by('id').values() template = loader.get_template('blog/index.html') context = { 'ohlasky': order, 'liturgicketexty': order1, } return HttpResponse(template.render(context, request)) Here is models.py from django.db import models # Create your models here. class Ohlasky(models.Model): den = models.DateField(blank=False) nazev = models.CharField(max_length=25, blank=False) text = models.TextField(blank=False) img = models.ImageField(upload_to='media', default=None, blank=True, null=True) def __str__(self): return self.nazev + ' | ' + str(self.den) Here is urls.py from django.contrib import admin from django.urls import path, include from django.conf import … -
How to merge two PDF files?
I'm trying to merge two PDF's but got this error. File "/code/aca_django/certificates/utils.py", line 10, in <module> from pypdf import PdfMerger File "/usr/local/lib/python3.10/site-packages/pypdf/__init__.py", line 10, in <module> from ._encryption import PasswordType File "/usr/local/lib/python3.10/site-packages/pypdf/_encryption.py", line 68, in <module> from Crypto.Cipher import AES, ARC4 # type: ignore[import] File "/usr/local/lib/python3.10/site-packages/Crypto/Cipher/ARC4.py", line 119, in <module> key_size = xrange(1,256+1) NameError: name 'xrange' is not defined. Did you mean: 'range'? I have tried with PyPDF2 3.0.1 and pypdf 3.8.1 like those imports. from PyPDF2 import PdfMerger or from pypdf import PdfMerger But got the same error. Any idea ? Thanks. -
CBV CreateView influences rendering of UpdateView
I've a model Anlieferung for which there are two forms and a CreateView and an UpdateView. CreateView and UpdateView use either one of the forms, depending on the user. The problem is that whenever the CreateView is called, all following GET requests to the UpdateView render a wrong information, i.e. the value rendered in field Spedition is not the same value as in the database. The value rendered in field Spedition is the value of the lastly created Anlieferung.spedition and not the value of the called record. Restarting the server solves, either by touching the wsgi.py script or by restarting apache itself, but this cannot be the solution. The configuration setup used is apache with mod_wsgi and this problem only occurs in the production environment. models.py: class Anlieferung(models.Model): spedition = models.ForeignKey(Spedition, blank=False, null=False, on_delete=models.CASCADE) ankunftszeit = models.TimeField(null=False, blank=False, ) fahrzeug = models.ForeignKey(Fahrzeug, on_delete=models.CASCADE, blank=True, null=True) anhaenger = models.ForeignKey(Fahrzeug, related_name='anhaenger', on_delete=models.CASCADE, blank=True, null=True) anzahlStellplaetze = models.IntegerField(null=False, blank=False, verbose_name="Anzahl Stellplätze") standort = models.ForeignKey(Standort, null=True, blank=True, on_delete=models.CASCADE) lieferant = models.CharField(max_length=100, blank=True, null=True, verbose_name="Lieferant / Kundenname") SpeditionsAuftrag = models.CharField(max_length=100, blank=True, null=True, verbose_name="Speditions Auftragsnummer") KundenAuftrag = models.CharField(max_length=100, blank=True, null=True, verbose_name = "Produzenten- oder Kundenauftragsnummer, " "Ordernummer oder Bestellnummer") leergut = models.ForeignKey(Leergut, null=True, blank=True, on_delete=models.CASCADE) leergut_anzahl … -
pgAdmin/postgresql is reordering my django model, prioritising character values over integer values
It's not a huge issue that the columns have been re-ordered, but I would like to understand why pgAdmin / PostgreSQL has prioritised the ordered of fields which have a character value over an integer value? See image of my django model below, and then an image of how it's structured in pgAdmin. Is there a reason why it would re-order the model? I was expecting the database to translate as per the order of the model -
Log files is busy by another proccess with open
I have script which get information from log file and create model with log info from that file when user log in or log out on our site But when i'm restarting pc i got an error that my log file is busy by another process How can i fix that? script.py def writing_logs(request, action): logger.info('{} {} {} {}'.format( request.user.email, get_client_ip(request), get_client_type_device(request), action)) with open('loggers/log_user_activity/user_activity.log', 'r', encoding='utf8') as filelog: for i_line in filelog.readlines(): if i_line.startswith('INFO') and len(i_line.split()) == 9: line_list = i_line.split() if line_list[3] != 'Watching': if not Log.objects.filter(log_date=line_list[1]): Log.objects.create(log_category=line_list[0], log_date=line_list[1]) -
How can i send form by type into input using htmx?
I have a search input and sort select. I wrapped it into form. How can i send form by typing into search input (hx-trigger="keyup changed delay:150ms") or selecting another item in select (hx-trigger="changed"). I need to send data from both of this elements. Here is my code: <form hx-get="{% url 'search-spec' %}" hx-target="#search-results" hx-trigger="keyup delay:150ms changed"> <div class="search w-100 mt-4 d-flex justify-content-center"> <div class="input-group rounded w-75 shadow-4-soft"> <span class="input-group-text me-2" id="search-addon"> <i class="fas fa-search"></i> </span> <input type="search" class="form-control rounded" placeholder="Начните набирать..." name="q" id="q"/> </div> </div> <div class="search w-100 mt-2 d-flex justify-content-center"> <span class="input-group-text me-2" id="search-addon"> <i class="fas fa-sort"></i> </span> <select name="sort" id="sort" value="0" class="form-select w-50"> <optgroup label="По дате публикации"> <option value="0">Последние публикации</option> <option value="1" selected>Первые публикации</option> </optgroup> <optgroup label="По обозначению"> <option value="2">Обозначение 0-9</option> <option value="3">Обозначение 9-0</option> </optgroup> <optgroup label="По наименованию"> <option value="4">Наименование А-Я</option> <option value="5">Наименование Я-А</option> </optgroup> </select> </div> </form> -
Django Custom User model field display User List
UserProfile is Custom User Model having columns avatar, bio and display fields. I want to Profile avatar in the User List I have added avatar_tag function to be called by the users list #models.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) def get_upload_avatar_to(self, filename): return f"images/avatar/{self.user.id}/{filename}" avatar = models.ImageField(upload_to=get_upload_avatar_to, null=True, blank=True) def avatar_tag(self): if self.avatar.url is not None: return mark_safe('<img src="{}" height="50"/>'.format(self.avatar.url)) else: return "" avatar_tag.short_description = 'Image' avatar_tag.allow_tags = True full_name = '' bio = models.TextField(default="", blank=True) display = models.CharField(default=full_name,max_length=512,blank=True) admin.py code is below class UserProfileInline(admin.StackedInline): model = UserProfile fk_name = 'user' can_delete = False verbose_name = "User profile" verbose_name_plural = 'Profiles' classes = ('text-capitalize','collapse open') extra = 1 list_display = ('avatar_tag') fieldsets = ( ("Profile", {'fields': ('avatar','bio', 'display',)}),) class UserProfileAdmin(UserAdmin): inlines = (UserProfileInline,) -
I am trying to fetch data with the Django ORM with filter and exclude both at the same time, but it returns the same data with and without exclude
I am trying to fetch the data from a model with a filter and exclude at the same time. Here is the query sharing = UserSharingPermissions.objects.filter( user_id = extra.user_id, is_deleted = False, archived = False ).exclude(pk = extra.current_company.pk) I am trying to exclude the current company from the results but this query includes the current company. I also tried with the Q, but this also gives me the same result. UserSharingPermissions.objects.filter(Q(user_id = extra.user_id, is_deleted = False, archived = False) & ~Q(pk = extra.current_company.pk)) I am not sure if am I missing something in a query or something else. Thanks. -
"msal" IdentityContextData for Django
I am working with MSAL for the django project that i am developing with. I Looked at the methods under class IdentityContextData(object) in context.py. I See that there is a variable self._id_token_claims = {} under the clear method. I have data coming in that variable. I saw a flask app that returns this variable as id_token_claims. Could someone add a property for id_token_claims similar to username or token_cache ` @property def username(self) -> str: return self._username ` ` @username.setter def username(self, value: str) -> None: self._username = value self.has_changed = True ` The above is the code snipet from class IdentityContextData(object) inside context.py. I need to get user email that is returned in _id_token_claims. But when i check the request in django, under request.identity_context_data, i can access request.identity_context_data._id_token_claims but i get the accessing protected property warning. I see data like prefered_username and email in this _id_token_claims but i also get a warning for the same. would appreciate someone adding the method to access this property directly like username or token_cache -
Making Both Value to be Condition for django_filters in DRF and Showing Customized Error if the condition is empty
I am trying to use Filter in Django Restful Framework using django_filters. I would like to use two fields so the condition must be met for both fields. This means the user must enter ref_code and expecting_time. But now, if the user enters ref_code the query still works. Lastly, if the query is empty I need a customized Message. filters.py import django_filters from myappointment.models import * class AppointmentFilter(django_filters.FilterSet): class Meta: model = AppointmentData fields =['ref_code', 'expecting_time'] api.py @api_view(['GET']) def AllAppointmentData(request): queryset = AppointmentData.objects.all() filterset = AppointmentFilter(request.GET, queryset=queryset) if filterset.is_valid(): queryset = filterset.qs if queryset is not None: serializer = AppointmentDataSerializer(queryset, many=True) return Response(serializer.data) else: return Response([], {'success': "The Query is empty"}, status=status.HTTP_200_BAD_REQUEST ) enter image description here -
Django KeyError at forms.py
I'm learning django and I'm playing around with forms and registering users. When I submit the registration form with the username, email, password, and confirm password fields filled, I get an error that states: KeyError at director/register/ "confirm_password" However, when I look at the POST data in the error message I clearly see the data I'm trying to access. see screenshot here csrfmiddlewaretoken: blahblahblabh username: dasdasd email: dasd@dsada.com password: test123! confirm_password: test123! Below are the forms.py, portion of the views.py, register.html files. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ("email", "password") class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ("email", "password") class RegisterUser(forms.Form): username = forms.CharField(max_length=64, required=True) email = forms.EmailField() password = forms.CharField(max_length=128, widget=forms.PasswordInput(), required=True) confirm_password = forms.CharField(max_length=128, widget=forms.PasswordInput(), required=True) def clean_username(self): username = self.cleaned_data["username"] if CustomUser.objects.filter(username=username).exists(): raise forms.ValidationError("Email already exists") return username def clean_email(self): email = self.cleaned_data['email'] if CustomUser.objects.filter(email=email).exists(): raise forms.ValidationError("Email already exists") return email def clean_password(self): password = self.cleaned_data['password'] confirm_password = self.cleaned_data['confirm_password'] if password != confirm_password: raise forms.ValidationError("Passwords do not match") return password``` views.py (register_view) def register_view (request): if request.method == "POST": form = RegisterUser(request.POST) if form.is_valid(): new_user = form.save() login(request, … -
Why is my Django, React+Vite environment not supporting my google calendar API?
I have successfully replicated the Google Calendar API in a React+Vite environment but when introducing Django it doesn't function at all. Are there any specific reasons why? If so, I would love an explanation why. const CLIENT_ID = myid; const API_KEY = mykey; const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'; const SCOPES = "https://www.googleapis.com/auth/calendar"; const accessToken = localStorage.getItem('access_token'); console.log(accessToken) const expiresIn = localStorage.getItem('expires_in'); console.log(expiresIn) let gapiInited = false, gisInited = false, tokenClient; useEffect(() => { gapiLoaded() gisLoaded() }, []) function gapiLoaded() { gapi.load('client', initializeGapiClient); } async function initializeGapiClient() { await gapi.client.init({ apiKey: API_KEY, discoveryDocs: [DISCOVERY_DOC], }); gapiInited = true; console.log("GAPI #1 INITIATED") if (accessToken && expiresIn) { gapi.client.setToken({ access_token: accessToken, expires_in: expiresIn, }); listUpcomingEvents(); } } function gisLoaded() { tokenClient = google.accounts.oauth2.initTokenClient({ client_id: CLIENT_ID, scope: SCOPES, callback: '', // Defined Later }); console.log("Success") gisInited = true; } //Enables user interaction after all libraries are loaded. // I believe the error happens here, it never console.logs GAPI 2 function handleAuthClick() { console.log("GAPI 1") tokenClient.callback = async (resp) => { console.log("GAPI 2") if (resp.error) { throw (resp); } console.log("GAPI 3") // await listUpcomingEvents(); console.log("GAPI 4") const { access_token, expires_in } = gapi.client.getToken(); localStorage.setItem('access_token', access_token); localStorage.setItem('expires_in', expires_in) console.log("GAPI 5") window.location.reload() }; if (!(accessToken && expiresIn)) { … -
Method not found when calling LIstRequest in grpc from client
I have written a function, to get the list, while connecting the server it show as error method not found. Error shown below. grpc._channel._MultiThreadedRendezvous: <_MultiThreadedRendezvous of RPC that terminated with: status = StatusCode.UNIMPLEMENTED details = "Method not found!" debug_error_string = "UNKNOWN:Error received from peer {created_time:"2023-05-17T02:07:09.472090526+00:00", grpc_status:12, grpc_message:"Method not found!"}" views.py @csrf_exempt def add_question(request): if request.method == "POST": data = json.loads(request.body) survey_response_data = { 'id' : 'success' } response = {"errorCode": "", "message": "success", "data": survey_response_data} return JsonResponse(data=response, status=status.HTTP_200_OK) if request.method == 'GET': try: client_stub = create_new_survey_question_client() survey_question = client_stub.List(survey_question_pb2.SurveyQuestionListRequest()) serializer = SurveyQuestionBffSerializer(survey_question, many=True) language_data = [msg for msg in serializer.data] return JsonResponse(data=language_data, status=status.HTTP_200_OK, safe=False) except Exception as E: data = {"message": f"Exception: {E}"} return JsonResponse(data=data, status=status.HTTP_400_BAD_REQUEST, safe=False) .proto file syntax = "proto3"; package survey_question; import "google/protobuf/empty.proto"; service SurveyQuestionController { rpc List(SurveyQuestionListRequest) returns (stream SurveyQuestion) {} rpc Create(SurveyQuestion) returns (SurveyQuestion) {} rpc Retrieve(SurveyQuestionRetrieveRequest) returns (SurveyQuestion) {} rpc Update(SurveyQuestion) returns (SurveyQuestion) {} rpc Destroy(SurveyQuestion) returns (google.protobuf.Empty) {} } message SurveyQuestion { int32 id = 1; string survey = 2; int32 question_no = 3; int32 question_type = 4; int32 order = 5; int32 is_required = 6; } message SurveyQuestionListRequest { } message SurveyQuestionRetrieveRequest { int32 id = 1; } I tried to create … -
django nested prefetch_related for loop in template giving multiple results
I am trying to get three objects in the same template. So i userd prefetch_related. It does work but in the last loop for the nested prefetch_related it obviously loops all again. Does any one knows how to do it correctly? If i only uses one prefetch_related it works perfectly: vendors = Vendor.objects.filter(id__in = vendors_ids).prefetch_related( Prefetch( 'productvendors', queryset = Product.objects.select_related('vendor') ) ) ) From the first query I get the VENDORS and from the second query I get the products and this works fine. {% for vendor in vendors %} {{ vendor.vendor_name }} {% for product in vendor.productvendors.all %} {{ product.product_name }} {% endfor %} {% endfor %} Result: VENDOR A HotDog VENDOR B Coffee Bread Now I need to add some data from CART model (quantity and total value). So I decided to add a nested related_prefetch adding the CART: vendors = Vendor.objects.filter(id__in = vendors_ids).prefetch_related( Prefetch( 'productvendors', queryset = Product.objects.all().prefetch_related( Prefetch( 'cartproducts', queryset = Cart.objects.all() ) ) ) ) And I got this (obviously): {% for vendor in vendors %} {{ vendor.vendor_name }} {% for product in vendor.productvendors.all %} {% for cart in product.cartproducts.all %} {{ product.product_name }} {{ cart.quantity }} {{ cart.total_price }} {% endfor %} {% endfor … -
Django: How to reference a context variable created in one class-based view from another class-based view
In the simplified example below, how do I reference the context variable "Elephant" (created in the class Lion) from inside the class Leopard? I have researched and tried a number of ways, including the last line below which results in a KeyError for "Elephant". views.py class Lion(ListView): def get_context_data(self, **kwargs): context super().get_context_data() context[“Elephant”] = Rhinoceros context["Giraffe"] = Eagle return context class Leopard(ListView): Buffalo = Lion.get_context_data(context[“Elephant”]) -
Django not recognizing react routes
This is my first django project. I set up react routes and Django, but I when I call a react route, django throws this error: So, I made this changes to project manage and now there is no error, but it does not show react component urlpatterns = [ #path('', views.index) re_path(r".*", views.index) ] How can I make this work? manage project urls.py: from django.urls import path,re_path from . import views urlpatterns = [ path('', views.index) # re_path(r".*", views.index) ] project urls.py: from rest_framework import routers from .api import MercadoriaViewSet, EntradaViewSet, SaidaViewSet router = routers.DefaultRouter() router.register('api/mercadoria', MercadoriaViewSet, 'mercadoria') router.register('api/entrada', EntradaViewSet, 'entrada') router.register('api/saida', SaidaViewSet, 'saida') urlpatterns = router.urls frontend project url.py from django.urls import path,re_path from . import views urlpatterns = [ path('', views.index) # re_path(r".*", views.index) ] frontend views: from django.shortcuts import render # Create your views here. # Aponta para os templates def index(request): return render(request, 'frontend/index.html') -
ValueError: Related model u'app.model' cannot be resolved when adding admin and custom user in existing app
I have an existing app that has as lot of migrations and no users table. I am looking to add django admin and a custom user. I am hitting Related model u'myapp.model' cannot be resolved when I run manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, myapp, sessions Running migrations: Applying myapp.0001_initial... OK Applying contenttypes.0001_initial... OK Applying admin.0001_initial...Traceback (most recent call last): <redacted> ValueError: Related model 'myapp.user' cannot be resolved Why is this happening and how do I fix this? -
ValueError : The given username must be set
``i am trying to do a register form in python django ,if we click on submit without providing username then this error shows( when username field have null value).i want to check if username is none or not before submit. register.py Registration Form <b>Username</b> <br> <b>Password</b> <br> <label><b>Confirm Password</b></label> <input type="password" name="password1" placeholder="Confirm Your Password"><br> <div class="col-md-12" style="text-align:center;padding-top:25px;"> <button type="submit">Submit</button> views.py def register(request): if request.method=='POST': username = request.POST['username'] password = request.POST['password'] cpassword = request.POST['password1'] if password == cpassword: if User.objects.filter(username=username).exists(): messages.info(request, "Username already exist") return redirect('register') else: user=User.objects.create_user(username=username,password=password) user.save(); return redirect('login') else: messages.info(request,"password not matching") return redirect('register') return redirect('/') return render(request,"")`