Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Can I check if logged in user profile information is updated in django models
I am working on a project in Django where I have a Profile Model with a Foreign Key field (OneToOne Relationship with User Model) called applicant and a status field which is set to 'Update' at default. Other fields like surname and othernames are also included in the Profile Model. class Profile(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=30, null=True) status = models.CharField(max_length=30, default='Update', null=True) def save(self, *args, **kwargs): self.profilestatus = 'Updated' super().save(*args, **kwargs) def __str__(self): return f'{self.applicant.username}-Profile' I want the system to check every logged in user if their profile information are not Updated, they should be redirected to the Profile Update page to update their profile first else they should be redirected to view their updated profile. def index(request): user = request.user.is_authenticated if request.user.is_authenticated and Profile.objects.get(applicant==user, status== 'Update'): return redirect('user-profile-update') else: return redirect('user-profile') context = { 'check_profile_update':check_profile_update, } return render(request, 'dashboard/index.html', context) I have ModelForm with a save method with automatically updates the satus field in Profile Model to Updated any time a user updates his or her profile information. Someone should kindly help me on the best way of solving this issue. Thanks -
solucion a este error , [Errno 2] No such file or directory en python
enter image description here enter image description here.png si existe todo esta dentro del entorno -
Django-storages uploads to S3 causing Django to hang
How can I prevent blocking when uploading to S3 using django-storages? My webserver currently gets about 100TPS and I have 17 workers (8 core cpu). After a bit of investigation I believe it's user content being uploaded that causes my webserver to hang. Is there a way to use django-storages + S3 properly (that prevents the event loop from being blocked)? Or am I barking up the wrong tree? Or– do I simply need to continue scaling worker resources? -
Django Project database MongoDB deploy in Azure settings
I've completed the deployment of the Django project on Azure Web App. However, I am getting errors in DATABASES in settings.py In settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'db-name', 'CLIENT': { 'host': 'mongodb+srv://<username>:<password>@<atlas cluster>/<myFirstDatabase>?retryWrites=true&w=majority' } } } However, Azure is unable to establish a connection with MongoDB. Is there anybody who knows the proper approach for a Django project to connect to MongoDB in the Azure web application? I need some help. Anyone who can assist me would be much appreciated; I need assistance with this difficulty. -
how to connect or acquire a connection to a blob storage via outbound proxy
curl -v -X GET 'https://outboundproxy.xx.net:8443/<Container_name>/<SAS>Token' -H 'Host: Azurestorage.blob.core.windows.net' -H "Rest of the curl headers" We have a outbound proxy inplace and all of the external connection has to go via an 'https://outboundproxy.xx.net:8443'. Hence, In the above curl command i have used host header to pass the actual storage account base url. Now, I want to replicate it using the python Azure blob SDK module but I am not sure how to structure the account url parameter. Any pointer or hint will be helpful -
Understanding slow Django performance
My webserver is scaling and I'm using Sentry Performance to try and better understand where things are slow. One thing that I don't quite understand is where the slowness might be coming from when the total reported query times are dramatically different than the time it takes to get a response. For example, one of my endpoints is taking 40s to finally get a response to the user. You'll see the total response time took an incredible 44,000ms even though all the work was done in about 1s (which is still slow, but not 44s slow). -
set_password() function not working - DJANGO REST FRAMEWORK
Creating a new user works fine until I try to set the password of the new user. Every other data gets to the auth_user table except the password. What could be the cause and what's the solution? Link to github -
Error installation pip install mysqlclient [duplicate]
Bonjour après plusieurs recherche toutes la journée, je me permet de vous dérangez. Un problème d'installation de mysqlclient sur un projet django sur un S.E Ubuntu 20.04. J'ai tenté des solutions comme : pip install mysqlclient error Rien à faire sa marche pas. Mon dernier recours, je me tourne vers vous. Merci. Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [44 lines of output] mysql_config --version ['10.3.34'] mysql_config --libs ['-L/usr/lib/x86_64-linux-gnu/', '-lmariadb'] mysql_config --cflags ['-I/usr/include/mariadb', '-I/usr/include/mariadb/mysql'] ext_options: library_dirs: ['/usr/lib/x86_64-linux-gnu/'] libraries: ['mariadb'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/include/mariadb', '/usr/include/mariadb/mysql'] extra_objects: [] define_macros: [('version_info', "(2,1,0,'final',0)"), ('__version__', '2.1.0')] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-39 creating build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-cpython-39/MySQLdb creating build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-cpython-39 creating build/temp.linux-x86_64-cpython-39/MySQLdb x86_64-linux-gnu-gcc … -
Django Test User Login With Factory And setUpClass
I am trying to test a user login with setUpClass, but the credentials of the saved user do not get accepted (403) during authentification although it works if I register the user manually (but I wanted to omit that for all functions so I do not have to do that, that's why I looked up setUpclass()) Am I missing something? test_register() works just fine. class AuthenticationTest(APITestCase): @classmethod def setUpClass(cls): super(AuthenticationTest, cls).setUpClass() cls.user_object = UserFactory.build() cls.user_saved = UserFactory.create() cls.client = APIClient() cls.base_url_login = reverse("api:login-list") cls.base_url_register = reverse("api:register-list") cls.base_url_logout = reverse("api:logout-list") cls.base_url_check_session = reverse("api:check-session-list") cls.faker_obj = Faker() def test_register(self): # Prepare data signup_dict = { 'username': self.user_object.username, 'password': 'test_Pass', 'email': self.user_object.email, } # Make request response = self.client.post( self.base_url_register, signup_dict ) # Check status response self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_data = response.json() self.assertEqual(response_data["success"], True) self.assertEqual(User.objects.count(), 2) # Check database new_user = User.objects.get(username=self.user_object.username) self.assertEqual( new_user.email, self.user_object.email, ) def test_login(self): # Prepare Data login_dict = { 'password': self.user_saved.password, 'email': self.user_saved.email, } # Make request response = self.client.post(self.base_url_login, login_dict) # Check status response self.assertEqual(response.status_code, status.HTTP_200_OK) response_data = response.json() self.assertEqual(response_data["success"], True) ... class UserFactory(django.DjangoModelFactory): class Meta: model = User username = Faker("user_name") email = Faker("email") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if … -
Django Signals not creating profile after user registration
I want the profile to be created once the user registration is complete but I am having to create a profile separate for the existing user. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from main.models import Membership # Create your models here. class Profile(models.Model): membership = models.OneToOneField( Membership, on_delete=models.CASCADE, related_name="membership", default="null") user = models.OneToOneField( User, on_delete=models.CASCADE, related_name="profile") couple_with = models.OneToOneField( User, on_delete=models.CASCADE, related_name="couple_with", blank=True, null=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) maiden_name = models.CharField(max_length=2, blank="") street_address = models.CharField(max_length=50) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default="Select") date_of_birth = models.DateField( blank=True, null=True) address2 = models.CharField(max_length=10) city = models.CharField(max_length=20) state = models.CharField(max_length=20) zip = models.CharField(max_length=5) country_name = models.CharField(max_length=30) graduate_year = models.CharField(max_length=4) def __str__(self): return(self.first_name + " " + self.last_name) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): user = instance print(user) if created: profile = Profile.objects.create(user=user) profile.save() This is what my views.py looks like. I don't know where am I slipping. It is able to create the user once registered but the profile is never created and Admin has to create the profile manually. def register_account(request): # check if the user is already logged in if request.user.is_authenticated: return redirect("main:home") … -
Show notifications to users at certain times in Django
By creating a model on Django, I want to create notifications for my users on the hours and days I want. And I want to create these notifications from my admin panel.I want to set the start and end dates from the admin panel and send these notifications to the users within the specified time.And once the user sees it, I don't want it to see it again.An example notification model: class NotificationModel(models.Model): title = models.CharField(max_length=100) description = models.TextField() start_date = models.DateTimeField() end_date = models.DateTimeField() How can I do that? How I use it will be healthier? -
Django Reverse Lookups of Foreign Keys is not working
Info I am using abstract models in django every thing is working fine instead of queryset i am try to make query for Domain which is related to the clients model. But i don't understand why Reverse Lookups of Foreign Keys is not working? TenantMixin && DomainMixin class TenantMixin(models.Model): schema_name = models.CharField(max_length=63, unique=True, db_index=True) class Meta: abstract = True class DomainMixin(models.Model): domain = models.CharField(max_length=253, unique=True, db_index=True) tenant = models.ForeignKey(settings.TENANT_MODEL, db_index=True, related_name='domains', on_delete=models.CASCADE) class Meta: abstract = True Client class Client(TenantMixin): name = models.CharField(max_length=100) class Domain(DomainMixin): pass QuerySet tenant = Client.objects.all() for t in tenant: for i in t.domain_set.all(): print(i) -
Running a django application on both the host machine and docker container at the same time
I have created a simple django application that has one endpoint /health/live and it returns a success message upon receiving a get request. I run the application locally with python manage.py runserver on port 8000 I also have a docker-compose and Dockerfile as below: FROM python ENV PYTHONUNBUFFERED 1 RUN mkdir /inventory WORKDIR /inventory COPY . /inventory WORKDIR /inventory RUN pip install -r requirements.txt and version: '3' networks: kong-net: name: kong-net driver: bridge ipam: config: - subnet: 172.1.1.0/24 services: inventory: container_name: inventory build: context: . dockerfile: Dockerfile restart: unless-stopped networks: kong-net: ipv4_address: 172.1.1.11 ports: - "8000:8000" environment: DEBUG: 'true' command: python manage.py runserver 0.0.0.0:8000 I then run docker-compose up (I don't detach it to be able to see the logs) They both work. I send a get request to http://127.0.0.1:8000/health/live: based on the logs I see, the request goes through the service running directly on the system and not on the docker container If I stop the service running directly without docker, and send the request, the request goes through the one deployed on docker is there a reason this is happening? why the first one takes priority? And shouldn't I see an error when trying to run the docker … -
How to hide some fields if user not logged in Django?
I want to hide some fileds from not logged users. For example I have model account with fields: name, surname, address, tel, and I want to hide address and tel fields if user is not logged in. I found some examples, but it hide whole model, not just a part I need. -
django template language - if statement issues
i am kind of new to django and i ran into a problem i couldnt find a solution to. In a template i render data from a custom context processor. There i use a for loop over all the queried items and a if statement, that checks that the data belongs to the person that is currently logged in: {% for item in all_soli_accs %} {% if item.owner == request.user.get_username %} <a href="{% url 'url-soli-acc' item.soli_acc %} "> {{ item.soli_acc }} </a> {% endif %} {% endfor %} Weirdly, the if statement doesnt return "true", when it is supposed to. The rendering doesnt output anything. In order to debug it, i tried to render {{item.owner}} and {{request.user.get_username}} and check if there are errors. But rendered as a variable, they return the same output, which lets me assume that it is all fine. I am confused. Does anyone has a solution to that? Do you need further information? best regards -
How can I make an attribute associate automatically with User? django
I'm making a simple website using django. I've added a 'Comment' model to make a comment section on a blog post. I'd like to print out each of the 'date_added', 'text', and 'owner' attributes in html. class User_Comment(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.text I have problems with the 'owner' attribute. owner = models.ForeignKey(User, on_delete=models.CASCADE) if I try to make migrations with it, Django asks me to provide a default value. It is impossible to change a nullable field 'owner' on user_comment to non-nullable without providing a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Ignore for now. Existing rows that contain NULL values will have to be handled manually, for example with a RunPython or RunSQL operation. 3) Quit and manually define a default value in models.py. If I add 'blank=True', 'null=True' parameters to the onwer attribute, the attribute works but it doesn't automatically associate with the owner when adding a comment. So I have to go to … -
How can i show data from js to html in django:TemplateSyntaxError at /payment Could not parse the remainder: '[$index]' from 'cardNumber[$index]'
I am creating a card payment page where it has a card and text box when I type on textbox it should show on the card.but I am using {{n < 10 ? '0' + n : n}} ,{{$index + minCardYear}} in HTML to get the number on card with animation. <div class="card-form__col"> <div class="card-form__group"> <label for="cardMonth" class="card-input__label">Expiration Date</label> <select class="card-input__input -select" id="cardMonth" v-model="cardMonth" v-on:focus="focusInput" v-on:blur="blurInput" data-ref="cardDate"> <option value="" disabled selected>Month</option> <option v-bind:value="n < 10 ? '0' + n : n" v-for="n in 12" v-bind:disabled="n < minCardMonth" v-bind:key="n"> {{n < 10 ? '0' + n : n}} </option> </select> <select class="card-input__input -select" id="cardYear" v-model="cardYear" v-on:focus="focusInput" v-on:blur="blurInput" data-ref="cardDate"> <option value="" disabled selected>Year</option> <option v-bind:value="$index + minCardYear" v-for="(n, $index) in 12" v-bind:key="n"> {{$index + minCardYear}} </option> </select> </div> </div> Django is giving me the error of: TemplateSyntaxError at /payment Could not parse the remainder: '[$index]' from 'cardNumber[$index]' How can I solve it so that Django ignores those portions and js should read that. -
Django display search bar values as multiple choice check boxes and then subbmit them to the database through a form
I have a form that gathers additional inforrmation about an user and one of its fields is a ManyToMany relationship (it stores data about ski resorts) and i want the following : to make for the ManyToMany field, from the form, a search bar. to display all the searched items as check boxes then check ( if wanted) and submit them How should i approach this ? I did the following views.py class CreateInfoView(CreateView): model = AdditionalInfoModel form_class = AdditionallnfoModelForm template_name = "user_ski_experience/additional_info.html" def get_form_kwargs(self): variable_to_send = super(CreateInfoView, self).get_form_kwargs() variable_to_send.update({'pk': None}) variable_to_send.update({'pk_user': self.request.user.id}) return variable_to_send def get_success_url(self): return reverse('login') class SearchResultsView(ListView): model = AdditionalInfoModel template_name = 'user_ski_experience/search_results.html' def get_queryset(self): q = self.request.GET.get('q', '') selected_resorts = Resorts.objects.filter(name__icontains = q) return selected_resorts forms.py class AdditionallnfoModelForm(forms.ModelForm): class Meta: model = AdditionalInfoModel fields = '__all__' widgets = {'user': forms.HiddenInput(), 'resort_choice': forms.SelectMultiple()} def __init__(self, pk, *args, **kwargs): pk_user = kwargs.pop('pk_user', None) super(AdditionallnfoModelForm, self).__init__(*args, **kwargs) self.pk = pk self.fields['user'].disabled = True self.fields['user'].initial = User.objects.last() for el in self.fields: self.fields[el].label = False def clean(self): return self.cleaned_data additional_info.html <body> <form method = "post"> {% csrf_token %} <h1> Let's get started with some questions ! </h1> <h2> This will help us get to know your ski experience </h2> <p> … -
'tuple' object has no attribute 'is_preview'
i am woking on a project where users can create a videos and check if the particular can be previewed before they purchase or not, everything was working fine up till now i got this 'tuple' object has no attribute 'is_preview' i can't really tell where this error is coming from. This is where the traceback is pointing too traceback Traceback (most recent call last): File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Destiny\Desktop\DexxaEd\dnextedprj\course\views.py", line 122, in course_details if(video.is_preview is False): AttributeError: 'tuple' object has no attribute 'is_preview' [01/May/2022 20:08:43] "GET /course/et-ea-velit-ad-veritatis-explicabo HTTP/1.1" 500 73905 views.py line 122 if serial_number is None: serial_number = 1 # if Video.objects.all().exists video = Video.objects.get_or_create(serial_number=serial_number, course=course) video_count = Video.objects.get(serial_number=serial_number, course=course) if(video.is_preview is False): if request.user.is_authenticated is False: return redirect("course:sign-in") else: user = request.user try: user_course = UserCourse.objects.get(user=user, course=course) except: return redirect("course:check-out", slug=course.slug) form.py CourseVideosFormset = inlineformset_factory(Course, Video, fields=('title','serial_number', 'video_id', 'is_preview')) -
Javascript scrolling for navigation bar not showing up when scrolling back up [django]
I am new to programming and having an issue with my navigation bar. I have a fully functional nav bar and when I scroll down it hides as expected but does not pop back up when I scroll back up. This is the function I used for the scrolling: var scrolled; var lastscroll = 0; var delta = 5; var navHeight = $('header').outerHeight(); $(window).scroll(function(event){ scrolled = true; }); setInterval(function() { if (scrolled) { hasScrolled(); scrolled = false; } }, 250); function hasScrolled() { var scrolltop = $(this).scrollTop(); if(Math.abs(lastscroll - scrolltop) <= delta) return; if (scrolltop > lastscroll && scrolltop > navHeight){ $('header').removeClass('nav-down').addClass('nav-up'); } else { if(scrolltop + $(window).height() < $(document).height()) { $('header').removeClass('nav-up').addClass('nav-down'); } } lastScrollTop = scrolltop; } Does anyone know what I am missing? -
I cannot access Django Oscar url
I deployed oscar /django application: Whenever I try to access my site on port 8000, I get the below error page : In my urls.py, I have the following: from django.apps import apps from django.urls import include, path from django.contrib import admin urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), # The Django admin is not officially supported; expect breakage. # Nonetheless, it's often useful for debugging. path('admin/', admin.site.urls), path('', include(apps.get_app_config('oscar').urls[0])), ] I have no active firewalls configured and I cannot access the app URL example.com:8000. In settings.py, I have the following configured: Django settings for frobshop project. Generated by 'django-admin startproject' using Django 3.2.13. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from oscar.defaults import * from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-z@up7l!&f*qh1%u21p*_ltv+m2^8+_9o-th+zpdih5!3ydlipd' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', … -
How to insert ManyToMany field in django
I want to insert a ManyToMany fields in my db using django.I select some customers using checkboxes. This is my models.py : class Campaign(models.Model): title = models.CharField(max_length=255) channel = models.CharField(max_length=255) start_date = models.DateField() end_date = models.DateField() target_prospect = models.ManyToManyField(ProspectClient,related_name='campaigns_prospect') target_partner = models.ManyToManyField(PartnerClient,related_name='campaigns_partners') I try the code below in my views.py but didn't work : def campaigns_page(request): if request.user.is_authenticated: if request.user.profile == 'D' or request.user.profile == 'E' or request.user.is_superuser: campaigns = Campaign.objects.all() prospects = ProspectClient.objects.all() partners = PartnerClient.objects.exclude(id__in=PartnerClient.objects.values('id')).all() context = { 'campaigns':campaigns, 'prospects':prospects, 'partners':partners } if request.method == 'POST': title = request.POST['title'] channel = request.POST['channel'] start_date = request.POST['start_date'] end_date = request.POST['end_date'] descriptions = request.POST['goals'].split(",") targets = request.POST['targets'] campaign = Campaign.objects.create(title=title,channel=channel,start_date=start_date,end_date=end_date) for description in descriptions: goal = Goal.objects.create(description=description) goal.campaign.add(campaign) for target in targets: prospects.campaign.add(campaign) partners.campaign.add(campaign) return render(request,'CampaignManagement/campaigns_page.html',context) return render(request, 'Login/logout.html') How I can solve this ? -
PostgreSQL tweaks for faster huge DB cleanup
I have a Python-Django script that takes our production database (150GB) and removes a ton of stuff from it, basically leaving only last 2 weeks of data for development purposes and produces just 6GB database at the end. Currently this script takes about 36 hours to finish with the given computational cloud resources (rather small and cheap ones). I think that there should be some postgresql-based tweaks like disabling auto-vacuum or disabling the indexes rebuilding to speed this up. Are there any? -
Object has no attribute get in serializer
I created a serializer and an API endpoint so I can retrieve some data from a Django DB in my React app but getting this error message: AttributeError: 'ProgrammingChallengesView' object has no attribute 'get' Here is my models.py: #creating programming challenges class ProgrammingChallenges(models.Model): challenge_id = models.AutoField(primary_key=True) challenge_name = models.CharField(max_length=200) challenge_description = models.TextField() challenge_expectations = models.TextField() my serializer: from accounts.models import ProgrammingChallenges ... class ProgrammingChallengesView(serializers.ModelSerializer): class Meta: model = ProgrammingChallenges fields = '__all__' and my urls.py: path('api/programming_challenges/', ProgrammingChallengesView, name='programming_challenges'), -
Django serializer does not recognize relation attribute
what im trying to do I'm creating a django API and currently i'm trying to request(GET) all the farmers(model) from my database, but every time I try to do so I ended up receiving a response saying that a property from my model isnt declared even though it's clearly declared. I've been struggling with this for a couple of days, your wisdom and knowledge on this situation is greatly appreciated. Error: Exception Type: AttributeError Exception Value: 'Farmer' object has no attribute 'property' models.py: class Farmer(AbstractUser): active = models.BooleanField(default=True) age = models.PositiveSmallIntegerField(blank=True, default=18) cpf = models.CharField(max_length=11, unique=True, default='') phone = models.CharField(blank=True, max_length=11, unique=True, default='') sex = models.CharField(blank=True, max_length=11, unique=False, default='') class Meta: ordering = ['id'] verbose_name = 'farmer' verbose_name_plural = 'farmers' def __str__(self): return self.username @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) class Property(models.Model): name = models.CharField(blank=False, max_length=255) size = models.DecimalField(blank=False, max_digits=100, decimal_places=1) phone = models.CharField(blank=False, max_length=11, unique=True) longitude = models.DecimalField(blank=False,decimal_places=16,max_digits=1000) latitude = models.DecimalField(blank=False,decimal_places=16,max_digits=1000) farmer = models.ForeignKey( Farmer, related_name='property_farmer', on_delete=models.DO_NOTHING ) class Meta: ordering = ['id'] verbose_name = 'property' verbose_name_plural = 'properties' unique_together = ['id', 'farmer'] def __str__(self): return f'the {self.name} property is owned by {self.farmer.username}' serializers.py: class FarmerSerializer(serializers.ModelSerializer): property = serializers.HyperlinkedRelatedField( many=True, view_name='property-detail', read_only=True ) class Meta: …