Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF ManyToMany field seralize
I have the following model class Contact(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='contacts') friends = models.ManyToManyField('self', blank=True) def __str__(self): return self.user.username When the user log-in, the client make a HTTP request to the following view to get user friends. class ContactAPIView(generics.RetrieveAPIView): queryset = Contact.objects.all() serializer_class = ContactSerializer lookup_field = 'user__username' The data returned: THE QUESTION IS: How can I serializer the 'friends' field in a way that I can get the id, user.id and user.username. -
By Convention, when creating an application in django is it more common to access the backend directly or use API's to make the CRUD?
I'm a beginner and now that I've done all the views and html, I'm in a connection phase with the backend, I would like to know what is most used, to do it correctly. PS: this will have a large number of users -
Inline CSS not following @media min-width and max-width properties
I am creating a pricing page in my Django app which has 3 columns. If the screen size is more than 768 pixels, I want it to show all 3 columns side-by-side. But if it's less 768 pixels, I want there to only be 1 column with the different pricing options on top of each other. For some reason, the @media properties are not being followed. It doesn't matter what the screen size is, the page is always showing 3 columns. The below screenshot should only have 1 column (like most mobile-friendly pages) Current page: Js Fiddle - LINK The strange thing is that in this JS Fiddle, it does seem to be following the @media screen and (max-width) properties. Code: <html> <head> <style> @import url(https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css); @import url(https://fonts.googleapis.com/css?family=Raleway:400,500,800); @import url(https://fonts.googleapis.com/css?family=Montserrat:800); /* MOBILE CUSTOMIZATIONS */ @media screen and (max-width: 767px) { .snip1214 .plan { width: 90%; margin: 0 auto; background-color: blue; } } @media screen and (min-width: 768px) { .snip1214 .plan { margin: 0; width: 25%; position: relative; float: left; background-color: #ffffff; border: 1px solid rgba(0, 0, 0, 0.1); } } html { height: 100%; } body { background-color: #212121; display: flex; justify-content: center; align-items: center; flex-flow: wrap; margin: 0; height: … -
Django filter statement error- invalid literal for int() with base 10:
I have 2 tables. I wanted to filter records from the second table based on filtered value from the first table. There is something wrong in my second filter statement. If anyone can help me to sort it out? report_table_data=report_table.objects.filter(cn_number=Master_table_data.cn_number)) My codes are as below. Models.py class Master_table(models.Model): sl_no = models.AutoField(primary_key=True) cn_number = models.CharField(max_length=10, null=False) class report_table( models.Model ): cn_number = models.ForeignKey(Master_table, on_delete=models.CASCADE) remarks = models.CharField( max_length=20, null=False ) Views.py def any_view(request): Master_table_data=Master_table.objects.get(sl_no=request.GET['key']) report_table_data=report_table.objects.filter(cn_number=Master_table_data.cn_number)) This throws below error. ValueError: invalid literal for int() with base 10: 'USS2000203' -
can't refresh the data in a DIV python Django nor the page after a jquery
Let me start by saying I have 2 variables in an HTML template(messages and users) and I have multiple buttons that when one of them is clicked it calls a jquery code that sends a post request to a Django server and it returns an update to a variable(messages) however, it's not updating the loop, I also tried to return a new HTML page that contains the new variable updated but the jquery is not updating the whole page with the new HTML if I can update the variable alone it would be better and if I can't do that how can I make jquery use the new HTML page the python code i used to return the update to the varialbe messages: if request.method == 'POST': send=Message.objects.filter(from_id=request.POST.get('userId'),to_id=2) rec=Message.objects.filter(from_id=2,to_id=request.POST.get('userId')) messages=sorted(chain(rec, send),key=lambda instance: instance.id,reverse=True) print(messages) return HttpResponse(list(messages)) and the code i used to return new HTML template: m = Message.objects.filter(to_id=2).order_by('-id') users = {} for i in m: if users.get(i.from_id.username) == None: users[i.from_id.username] = User.objects.get(id=i.from_id.id) users = list(users.values()) send=Message.objects.filter(from_id=users[0].id,to_id=2) rec=Message.objects.filter(from_id=2,to_id=users[0].id) messages=sorted(chain(rec, send),key=lambda instance: instance.id,reverse=True) if request.method == 'POST': send=Message.objects.filter(from_id=request.POST.get('userId'),to_id=2) rec=Message.objects.filter(from_id=2,to_id=request.POST.get('userId')) messages=sorted(chain(rec, send),key=lambda instance: instance.id,reverse=True) print(messages) return render(request,'psych.html',{"users":users, "messages":list(messages)}) return render(request,'psych.html',{"users":users, "messages":list(messages)}) the HTML code and jquery code that uses the variable and … -
password reset emails are coming to the host email
I'm making an e-commerce but it sends the password confirmation email to the host. I use django builtin password reset views so I have no idea path('password-reset/', PasswordResetView.as_view( ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( ), name='password_reset_complete'), is there a way to edit the email that is sent to? -
Compare existing Django model's instances for matching fields?
I am working on a fairly difficult django query. The query needs to check against all of the Student model instances, and check if any 2 instances have 2+ matching database fields. I have this so far which works if I throw in a hard-coded search term or the value is grabbed from a form input value. Student.objects.annotate( match_count=Case(When(full_name='hardcodedvalue', then=1), default=0, output_field=IntegerField())).annotate( match_count=F('match_count') + Case(When(phone_number='hardcodedvalue', then=1), default=0, output_field=IntegerField())).annotate( match_count=F('match_count') + Case(When(student_email='hardcodedvalue', then=1), default=0, output_field=IntegerField()) ).filter(match_count__gt=1) This works great when compared to hardcoded value which is really a form input. If any 2 fields come back as a match, then it returns the correct result. Now I am struggling to run the query in a similar way, to query against items already existing in the database. I need to run a check that instead of checking against a form input, it checks all of the Student models fields. For example full name would have to check against... full_name=Student.objects.all().value('full_name') -
Azure pipeline not connecting to database service while running tests
I'm trying to run the tests of a Django application on azure with Azure pipelines. But every time I try to connect to the database I run with an error. The .yml file used for the pipeline is this: resources: containers: - container: pg12 image: postgres:12 env: POSTGRES_USER: beta POSTGRES_PASSWORD: beta POSTGRES_DB: beta ports: - 5432 # needed because the postgres container does not provide a healthcheck options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 variables: - name: DJANGO_SETTINGS_MODULE value: config.settings.production - name: DJANGO_SECRET_KEY value: <redacted> - name: DEBUG value: False - name: DATABASE_URL value: postgres://beta:beta@localhost:5432/beta trigger: - qa pool: vmImage: ubuntu-latest strategy: matrix: Python37: PYTHON_VERSION: '3.7' maxParallel: 3 services: postgres: postgres:12 steps: - script: printenv - task: UsePythonVersion@0 inputs: versionSpec: '$(PYTHON_VERSION)' architecture: 'x64' - script: | sudo apt install -y postgresql-client # sudo psql --host=postgres --username=postgres --command="SELECT 1;" - task: PythonScript@0 displayName: 'Export project path' inputs: scriptSource: 'inline' script: | """Search all subdirectories for `manage.py`.""" from glob import iglob from os import path # Python >= 3.5 manage_py = next(iglob(path.join('**', 'manage.py'), recursive=True), None) if not manage_py: raise SystemExit('Could not find a Django project') project_location = path.dirname(path.abspath(manage_py)) print('Found Django project in', project_location) print('##vso[task.setvariable variable=projectRoot]{}'.format(project_location)) - script: | python -m … -
Django FileNotFoundError: [Errno 2] No such file or directory: 'train_mean.joblib' after deployed in Ubuntu, but working in localhost
im deploying dajngi to ubuntu (apache), running fine on my local, but error when deployed on Ubuntu server. the error: [Fri Oct 01 16:59:25.938641 2021] [wsgi:error] [pid 58417:tid 140031275181824] [remote 140.213.196.122:39872] File "/home/ubuntu/prediction/predict/views.py", line 26, in __init__ [Fri Oct 01 16:59:25.938646 2021] [wsgi:error] [pid 58417:tid 140031275181824] [remote 140.213.196.122:39872] self.values_fill_missing = joblib.load("train_mean.joblib") [Fri Oct 01 16:59:25.938650 2021] [wsgi:error] [pid 58417:tid 140031275181824] [remote 140.213.196.122:39872] File "/home/ubuntu/prediction/venv/lib/python3.8/site-packages/joblib/numpy_pickle.py", line 577, in load [Fri Oct 01 16:59:25.938654 2021] [wsgi:error] [pid 58417:tid 140031275181824] [remote 140.213.196.122:39872] with open(filename, 'rb') as f: [Fri Oct 01 16:59:25.938658 2021] [wsgi:error] [pid 58417:tid 140031275181824] [remote 140.213.196.122:39872] FileNotFoundError: [Errno 2] No such file or directory: 'train_mean.joblib' views.py : from django.shortcuts import render from django.http import JsonResponse import joblib import pandas as pd import numpy as np import os class LogisticRegression: def __init__(self): path_to_artifacts = '' self.values_fill_missing = joblib.load(path_to_artifacts + 'train_mean.joblib') self.scaler = joblib.load(path_to_artifacts + 'min_max_scaler.joblib') self.model = joblib.load(path_to_artifacts + 'log_reg.joblib') The dir structure: -
How to avoid double saving after defining the `Save` method on the Model?
I have defined a Save method in my model for the order fields. Now, when I do some manipulations with the Order field in View and call save() - I save twice - in View save() and Model save(). Because of this, the problem! How to solve this problem? How to make Save work only when creating a model object? And don't work save when I save() in Views -
request.POST data field doesn't get to cleaned_data of form
In views.py I've got a method called signup: def signup(request): context = {} if request.method == 'POST': form = SignUpForm(request.POST) print("request", request.POST) if form.is_valid(): user = form.save(commit=False) login(request, user) return redirect('index') else: context['form'] = form else: # GET request form = SignUpForm() context['form'] = form return render(request, 'registration/signup.html', context) Request print gives me all the fields a user entered: request <QueryDict: {'csrfmiddlewaretoken': ['***'], 'username': ['12312312gdsgdsg'], 'email': ['123123fsdfesgf@gmail.com'], 'password1': ['123fhfhfh'], 'password2': ['989898gdfjgndf']}> When I call form.is_valid() it gets to clean data of my form of forms.py: class SignUpForm(UserCreationForm): username = forms.CharField( label="username", max_length=30, required=True, widget=forms.TextInput( attrs={ 'type': 'text', 'placeholder': 'Username', } ), ) email = forms.EmailField( label="email", max_length=60, required=True, widget=forms.TextInput( attrs={ 'type': 'text', 'placeholder': 'Email', } ), ) password1 = forms.CharField( label="password1", required=True, widget=forms.PasswordInput( attrs={ 'type': 'password', 'placeholder': 'Password', } ), ) password2 = forms.CharField( label="password2", required=True, widget=forms.PasswordInput( attrs={ 'type': 'password', 'placeholder': 'Confirm Password', } ), ) def clean(self): cleaned_data = super(SignUpForm, self).clean() print("cleaned data", cleaned_data) password = cleaned_data["password1"] confirm_password = cleaned_data["password2"] if password != confirm_password: self.add_error('confirm_password', "Password and confirm password do not match") return cleaned_data class Meta: model = ServiceUser fields = ('username', 'email', 'password1', 'password2') The form's cleaned data print returns me the same dictionary as the post, but … -
how to restore database 'postgres' from postgresql
I am using local postgresql and pgadmin 4. I dropped database 'postgres' and now pgadmin won't open. How can I restore 'postgres' or fix this issue? -
Django Rest Framework ordering isnt working
Everything is imported, it might not be working because of get_queryset function, but i am not sure. class ShowStats(ListAPIView): serializer_class = StatsSerializer filter_backends = (DjangoFilterBackend, filters.OrderingFilter) ordering_fields = ('date', 'views', 'clicks', 'cost', 'cpc', 'cpm') ordering = ('views',) def get_queryset(self): return Stats.objects.filter(date__range=[self.kwargs['from'], self.kwargs['to']]) def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) response_list = serializer.data for i in range(len(response_list)): response_list[i]['cpc'] = response_list[i]['cost'] / response_list[i]['clicks'] response_list[i]['cpm'] = response_list[i]['cost'] / response_list[i]['views'] * 1000 return Response(data=response_list) -
Deploy Reactjs inside Django app to heroku
As in the title, I currently have a django project, and have reactjs inside as an app, i follow the tutorial from Tech With Tim https://youtu.be/JD-age0BPVo but he didnt do the deployment step, Most deployment guides show seperate frontend and backend folder, I only found this guide which describe my exact situation (using react,webpack inside django) in option 1 but it isnt so detail https://mattsegal.dev/django-spa-infrastructure.html Can someone help me with deployment, im just a beginner and this is my first project in django, im pretty confused -
Django Add new column and assign values based on another table column values
I have a 3 models: class Status(DjangoEnum): Status1 = "Status1" Status2 = "Status2" Status3 = "Status3" class ABC(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) variable_1 = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) class DEF(models.Model): abc = models.ForeignKey(ABC, on_delete=models.CASCADE) variable_2 = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) class GHI(models.Model): def = models.ForeignKey(DEF, on_delete=models.CASCADE) variable_3 = models.CharField( choices=Status.choices(), default=Status.Status1, max_length=50, ) I want to add a new column "Current_Status"(similar to variable_3 in GHI) in the class ABC. The values that need to be filled in this new column "Current_Status" are based on the values of variable_3 in class GHI. For example, let's assume that Current_Status(in ABC) contains the most frequent value of variable_3(in GHI) among all the records(corresponding to all the DEF records associated with the current ABC record). How can I add this column so that the existing records in the table ABC are filled with values based on variable_3 in class GHI? -
django This backend doesn't support absolute paths
I am getting this error after integration aws S3 bucket. My images are uploading on aws but why I am getting this error?. here is my code for uploading image: if self.profile_pic: img = Image.open(self.profile_pic.path) out_put_size = (200,200) img.thumbnail(out_put_size) img.save(self.profile_pic.path,quality=80,optimize=True) I found few question on stack overflow on this topic where said I need to be use name instead of path but I am not understanding how to use name instead of path? -
Django model formset - data for first nested child form missing in post method
I am using Django 3.2 and crispy-forms 1.11.2 I have a model and form defined like this: /path/to/myapp/models.py class Foo(models.Model): pass class FooChild(models.Model): parent = models.ForeignKey(Foo, on_delete=models.CASCADE) title = models.CharField(max_length=16) /path/to/myapp/forms.py class FooChildForm(ModelForm): class Meta: model = FooChild fields = "__all__" class FooChildFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_method = 'post' self.layout = Layout( 'title', ) self.render_required_fields = True /path/to/myapp/views.py class FooCreateView(CreateView): model = Foo def __init__(self, **kwargs): super().__init__(**kwargs) self.choice_formset = inlineformset_factory(Foo, Child, form=FooChild, extra=9) def get(self, request, *args, **kwargs): form = self.form_class() p = self.model() formset = self.choice_formset(instance=p) helper = ChildFormSetHelper() helper.template = 'bootstrap/table_inline_formset.html' helper.form_tag = False return render(request, 'myapp/create.html', {'form' : form, 'formset': formset, 'helper': helper}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST or None) if form.is_valid(): new_foo = form.save(commit=False) new_foo.creator = request.user new_foo.save() formset = self.choice_formset(request.POST or None, instance=new_foo) formset.save() # <- formset loses first element # request.POST.get('choices-0-title') # 'Choice Two' <- (expected 'Choice One') # request.POST.get('choices-1-title') # 'Choice Three' # request.POST.get('choices-2-title') # 'Choice Four' # request.POST.get('choices-3-title') # 'Choice Five' /path/to/myapp/templates/myapp/create.html {% block content %} <div class="container-lg"> <form id="frm-foo-create" method="post"> {% csrf_token %} <div class="row" style="margin: 30px 0px;"> <div class="col-lg-12"> <h2>Create a New Foo</h2> <br /> {% crispy form %} {{ form|as_crispy_errors }} {% crispy … -
why my dropdown menu not working on some page
I tried to learn django a few day ago and make a simple website use that, but for a reason my dropdown in home page didn't work but in another page it's work properly. Here my html template for that <div class="dropdown-menu"> {% for category in links %} <a class="dropdown-item" href="{{ category.get_url }}">{{category.category_name}}</a> {% endfor %} </div> and here my code for django urls.py urlpatterns = [ path('', views.store, name='store'), path('<slug:category_slug>/', views.store, name='product_by_category'), ] and here my code for links references def menu_links(request): links = Category.objects.all() return dict(links = links) i don't know why in my home page the dropdown button didn't work but in another page it work. i tried to find on my navbar templates and i think there is no problem there but the dropdown still not working and i tried to find on settings.py(to check installation app) but i did it anyone have idea where the problem is? -
How to hide nested object's name in Django Rest Framework serializer?
I have two models: Company and ContactCompany Company model is a base model and ContactCompany has some specific fields. They are connected via a foreign key. There are two serializers CompanySerializer and ContactCompanySerializer. Models: class Company(CoreModel): name = models.CharField( max_length=128, verbose_name=_("Company Name"), unique=True, ) address = models.TextField(null=True, blank=True, verbose_name=_("Address")) sector = models.ForeignKey( "contact.Sector", on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_("Sector"), related_name="companies", ) city = models.ForeignKey( City, on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_("City"), related_name="companies", ) class ContactCompany(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, related_name="contact_companies", null=True, blank=True, ) note = models.TextField(null=True, blank=True, verbose_name=_("Note")) website = models.CharField( null=True, blank=True, max_length=128, verbose_name=_("Website") ) Serializers: class ContactCompanySerializer(serializers.ModelSerializer): company = CompanySerializer() integration_requirements = serializers.ListSerializer( child=serializers.CharField(), required=False, ) statuses = StatusSerializer(many=True, read_only=True) current_status = StatusSerializer(required=False) contact_people = ContactPersonSerializer(many=True, read_only=True) responsible_company = serializers.CharField( source="responsible_company.name", read_only=True ) class Meta: model = ContactCompany fields = ( "id", "company", "website", "responsible_company", "note", "integration_requirements", "current_status", "statuses", "contact_people", ) class CompanySerializer(serializers.Serializer): name = serializers.CharField() is_active = serializers.BooleanField(required=False) city = serializers.CharField(source="city.name", required=False, allow_null=True) country = serializers.CharField( source="city.country.name", required=False, allow_null=True ) sector = serializers.CharField( source="sector.name", required=False, allow_null=True ) Example json response: { "id": 1, "company": { "name": "Company name", "is_active": true, "city": "City", "country": "Country", "sector": "Clothing" }, "website": "test", "note": "Note" } In the json response I want to delete … -
Django 3.2.8 deploy to Heroku fails, gunicorn config.py file is missing
Has anyone run across this issue when trying to deploy Django to Heroku? I am using nothing but a standard clean Django 3.2.8 build. It runs properly locally and puts up the successful install web page. However, when deployed to Heroku I get an error (ModuleNotFoundError: No module named ‘config’) and the system ‘crashes’. I can’t figure out why the gunicorn config.py file is ‘missing’ from the install. I have seen about 5 others have this same issue, without any resolution. Where in the build process in the config.py file created? -
Django Rest Framework two Serializers for the same Model
I'm pretty sure there's a better way to do this: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('category', 'id', 'title', 'image', 'slug', 'author', 'excerpt', 'content', 'status', 'published') class FrontendPostSerializer(serializers.ModelSerializer): author = AuthorSerializer(many=False, read_only=True) category = CategorySerializer(many=False, read_only=True) class Meta: model = Post fields = ('category', 'id', 'title', 'image', 'slug', 'author', 'excerpt', 'content', 'status', 'published') PostSerializer is gonna look like this { "category": 1, "id": 45, "title": "Lorem Ipsum - Lorem ipsum dolor sit amet consectetur", "image": "http://localhost:8000/media/posts/car_SxXcUTV.jpg", "slug": "lorem-ipsum-lorem-ipsum-dolor-sit-amet-consectetur", "author": 4, "excerpt": "Officiis iure rerum voluptates a cumque velit \nquibusdam sed amet tempora. Sit laborum ab, eius fugit doloribus tenetur \nfugiat, temporibus enim commodi iusto libero magni deleniti quod quam \nconsequuntur! Commodi minima excepturi repudiandae velit hic maxime\ndoloremque.", "content": "Officiis iure rerum voluptates a cumque velit \nquibusdam sed amet tempora. Sit laborum ab, eius fugit doloribus tenetur \nfugiat, temporibus enim commodi iusto libero magni deleniti quod quam \nconsequuntur! Commodi minima excepturi repudiandae velit hic maxime\ndoloremque.", "status": "published", "published": "2021-10-01T14:46:34.872576Z" } FrontendPostSerializer is gonna look like this { "category": { "name": "django" }, "id": 45, "title": "Lorem Ipsum - Lorem ipsum dolor sit amet consectetur", "image": "http://localhost:8000/media/posts/car_SxXcUTV.jpg", "slug": "lorem-ipsum-lorem-ipsum-dolor-sit-amet-consectetur", "author": { "username": "luigi.verdi" }, "excerpt": "Officiis iure rerum voluptates … -
Getting PK from another table that isn't user - Django REST framework
I need help with the following problem please. I've managed to connect a user's id to another table, but I can't seem to replicate the same process when connecting a table to another's primary key. What am I doing wrong? MODEL Parent model class TestDataTwo(models.Model): user = models.OneToOneField("auth.User", related_name="testdatatwo", on_delete=models.CASCADE) test_name = models.CharField(max_length=1024, null=True, default="N/A") Child model class TestDataThree(models.Model): user = models.OneToOneField("auth.User", related_name="testdatathree", on_delete=models.CASCADE) sdgdata = models.OneToOneField(TestDataTwo, related_name="testdatatwo", on_delete=models.CASCADE, default=-1) test_name_again = models.CharField(max_length=1024, null=True, default="N/A") SERIALIZER Parent serializer class TestDataTwoSerializer(serializers.ModelSerializer): class Meta: model = TestDataTwo fields = ( "id", "user_id", "test_name", ) Child serializer class TestDataThreeSerializer(serializers.ModelSerializer): class Meta: model = TestDataThree fields = ( "id", "user_id", "test_name_again", ) VIEW Parent serializer class TestDataTwoViewSet(ModelViewSet): queryset = TestDataTwo.objects.all().order_by('id') serializer_class = TestDataTwoSerializer paginator = None # CREATE NEW TESTDATATWO ROW FOR USER def perform_create(self, serializer): serializer.save(user=self.request.user) # GET ALL ENTRIES OF TESTDATATWO FOR SPECIFIC USER, EXCEPT IF SUPERUSER, THEN RETURN ALL def get_queryset(self): # if self.request.user.is_superuser: # return self.queryset # else: return self.queryset.filter(user=self.request.user) # PUT/PATCH def perform_update(self, serializer): serializer.save(user=self.request.user) return Response(serializer.data, status=status.HTTP_200_OK) # DELETE TESTDATATWO ID def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT) Child serializer class TestDataThreeViewSet(ModelViewSet): queryset = TestDataThree.objects.all().order_by('id') serializer_class = TestDataThreeSerializer paginator = None # CREATE NEW … -
DRF - URL kwargs - get list in object
I have this kind of url: /store/<pk>/categories I believe it's self-explanatory what it does. In terms of DB relation, Category has a foreign key to Store. I do have a functioning code, but I think there must be a better or more proper way of implementing it. class CategoriesListView(ListAPIView): permission_classes = (IsAuthenticated,) serializer_class = CategorySerializer queryset = Category.objects.all() # TODO: is that right way of doing this? # or there is some sort of lookup parameter that does the same? def get_queryset(self): store = get_object_or_404(Store, pk=self.kwargs['pk']) return store.categories -
Django: custom button in admin change form return bad url for custom view function
I have problems to link my custom button from change_form.html to my view function. pic : admin change form custom button change_form.html {% extends "admin/change_form.html" %} {% load i18n %} {% block title %} Send Email {% endblock %} {% block content %} {% if request.resolver_match.url_name == 'requests_requests_change' %} <div class="submit-row"> {% csrf_token %} <a href="{% url 'requests:send-email' original.pk %}" class="button" style="background-color: #F08000;float: left">Request Subscription </a> </div> {% endif %} {{ block.super }} {% endblock %} views.py from django.shortcuts import render, redirect def send_email(request, requests_id): return redirect('') # or whatever to test the url urls.py from django.urls import path from . import views app_name = 'requests' urlpatterns = [ path('<int:pk>/send-email/', views.send_email, name='send-email'), ] main project urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', admin.site.urls), # admin site administration path('requests/', include('requests.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) pic: error message Any help would be great! Thanks! -
Is there a way to enable django DEBUG mode using nginx?
I deployed my project on served with nginx and gunicorn. When I am trying to access a particular endpoint there is an error: "500 Internal Server Error", that is bad, so I have decided to enable django debug mode, but nothing has changed. Instead of informative traceback, I get an uninformative http status code, so how can I change it?