Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve in Django REST API the serializing of data from 2 models with ForeignKey
I was wondering what the correct way is to serialize data in Django REST API from 2 models connected with ForeignKey. The situation is: i have a 1st table called NewUsers with the user registrations, and a 2nd table called Ticker with data saved from an external API. The goal is: create a 3rd table with parts of the 2 tables interconnected - one part is the user loggedin, and the other part is the selection of one crypto object. This new table will then be displayed via Django REST API serializer. The problem is: this new 3rd table does not display the complete list of values selected by the user. I have gone through the documentation here https://books.agiliq.com/projects/django-admin-cookbook/en/latest/override_save.html and here https://www.django-rest-framework.org/tutorial/1-serialization/ but could not find a complete solution. What am i missing? my views.py from rest_framework import generics from .serializers import WatchlistSerializer from ticker.serializers import TickerSerializer from watchlist.models import SectionWatchlist from ticker.models import Ticker import requests from rest_framework.views import APIView from rest_framework.decorators import api_view from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class CreateSectionWatchlist(generics.CreateAPIView): queryset = SectionWatchlist.objects.all() serializer_class = WatchlistSerializer class ListSectionWatchlist(generics.ListAPIView): queryset = SectionWatchlist.objects.all() serializer_class = WatchlistSerializer def get_queryset(self): queryset = SectionWatchlist.objects.all() author = self.request.query_params.get('author') if author: queryset … -
Django REST + Vue JS app authentication breaks when uploading?
I am developing a simple app using Django REST framework for the backend and with a Vue multi-page app as a front end. I use axios to make requests to Django from the javascript. Locally, everything works well. All the pages work and login functionality works fine. For authentication, I am using Django's built in authentication and a store in Vuex. However, once I started to deploy, it seems to break. To deploy, I initially decided to use ngrok to create an https tunnel to the backend. My frontend is still on localhost, but as soon as I change the url to use the new API, the login functionality stops working. The rest of the site (which does not require login) works fine, but the bits that do just don't work. When I click the login button, Vue tries to redirect me to the logged in 'dashboard' page, but then it identifies that I am not logged in and kicks me out. The actual login process works and the server responds that I am logged in, but when the site checks again it responds that I am not logged in. There are no errors at any point. I am happy … -
Filtering QuerySet in Djnago where a field has a specific value or is null
what's the right way to this in Django, i want to to filter a queryset where the field has a specific value or is null, any help would be really appreciated -
Django tutorial part2 went wrong
I'm following the tutorial and I received a traceback ~> Question.objects.all()Traceback (most recent call last): File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: polls_question The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 256, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: polls_question >>> from django.utils import timezone >>> q = Question(question_text="What's new?", pub_date=timezone.now()) >>> q.save() Traceback (most recent call last): File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", … -
How would you implement this form feature on Glassdoor with Django?
Glassdoor has a particular feature in their 'Add a Salary' form I'm trying to replicate. I have an idea how I'd like to do it but wanted to see if there were more optimal solutions. As you type in an 'Employer's Name' a request is made back to the server to search for all Employers that have that string in their name. They present these below the form for you to select. This could be done with Ajax. They then have an 'Add a new employer' field at the bottom of the search results if the result returns None, or not what you're looking for. If you select this field some additional fields are added, like 'company address' and 'company website'. I think this could be done with a toggle showing/hiding those form fields. So the initial state of the form fields are hidden. The toggle to show the extra form fields only become available if the user clicks on 'Add a new employer'. Additionally, if the user goes back and updates the company name to one that's already in the db, the extra form fields are hidden once more. I think Ajax + a toggle and hidden form fields … -
How to package plain JSON content in a WSGI response?
I have a Django WSGI (not my decision) website making a call to fetch dynamically generated JavaScript. I put the function in views.py and it's receiving the request and doing the work, but the return value is being rejected. The HTML (JavaScript section of web page) that calls this function does it like this: var jscript = document.createElement('script'); jscript.id = 'generate'; jscript.style.visibility = 'hidden'; jscript.style.display = 'none'; jscript.src = `/generate?callback=catchOptions${query}`; // jsonp https://en.wikipedia.org/wiki/JSONP query is a list of parameters in query string format if (document.getElementById("generate") == null) document.body.appendChild(jscript); // javascript needs this to work properly There's map file that maps /generate to /generate_planet (see below). Getting into the function works great. It's the return value that Djangoff is rejecting. Here is the function in views.py from cgitb import reset from django.shortcuts import render from . import planetor from django.http import JsonResponse def generate_planet(request): res = planetor.generate(request.content_params, "/app/planetor/", "FRAMES=1") # res is JSON text, NOT a python dict return res # res looks like this: `enter code here`{'camera_location': '-30,-30,-30', 'camera_angle': '30', 'sun_color': '5,5,5', 'sun_position': '10000,0,-10000', 'planet_size': '20.06', 'background': 'background_2.jpg', 'planet': 'surface_1.jpg', 'clouds_size': '1.02', 'clouds': 'clouds_16.jpg', 'clouds_density': '0.80', 'atmosphere': 'iodine', 'atmosphere_density': '0.95', 'atmosphere_size': '1.03', 'moons': '4', 'moon_position': None, 'moon_size': None, 'moon': None, … -
'NoneType' object has no attribute 'customer_id'
I have two models in an app called customer. The models are Customer and Account. The logic is one customer can have many accounts. So the auto generated default 'id' column in Customer is Foreign Key in Account. Account also has an auto generated default 'id' column. I have created a function for an account_id field in Account which will be generated on a simple algorithm. customer_id and id from Account will be concatenated as 'customer_id'_'id', (for eg. 1_1). The function will first check the current customer_id of the Account instance created and then check which is the last id for that customer_id. For newly added account, it will capture the id part from account_id (i.e. the part after underscore) and increment it by 1. Then concatenation happens for the same customer_id and id. Following is the code-: models.py from asyncio.windows_events import NULL from django.db import models from django.db.models.signals import pre_save from django.contrib.auth.models import AbstractBaseUser from .utils import set_account_id class Customer(AbstractBaseUser): name = models.CharField(max_length=50) phone = models.BigIntegerField(null=True) email = models.EmailField(max_length=100, null=True) org_name = models.CharField(max_length=100, null = True) org_logo = models.ImageField(upload_to='logos', blank=True) subscription_start_date = models.DateField() subscription_end_date = models.DateField() password = models.CharField(max_length=50, blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'email'] def … -
Creating a windows service for connecting python and run Django server-----
Step-1: Open Visual Studio, go to File Menu, select New Project (Ctrl+Shift+N). A new window will open to create a project. Search for Windows Service (C#) from the upper right corner search box. If you do not get any Windows Service, your visual studio need to install properly (install .NET Desktop Development). Give a service name PythonService and select OK. Step-2: After creating service project, User will get 04 files by default- App.config, Program.cs, ProjectInstaller.cs, Service1.cs App.config is to configure any app data or creating connection Program.cs will initiate the service ProjectInstaller.cs is the installer for service. Double click on it. Click right button and add service installer. serviceInstaller1 will be added on serviceProcessInstaller1. Select property of serviceInstaller1, give a ServieName, change StartType to Automatic (if needed). Go to serviceProcessInstaller1 property, change Account to LocalSystem Step-3: Service1.cs file will consist all the necessary code for python cmd run and execute python command. Then Django server will run. The code for core python command run is- public partial class Service1 : ServiceBase { private System.Timers.Timer timer = new System.Timers.Timer(); int ScheduleTime = Convert.ToInt32(ConfigurationManager.AppSettings["ThreadTime"]); string _workingDirectory = ConfigurationManager.AppSettings["WorkingDirectory"]; string _RunServerCommand = ConfigurationManager.AppSettings["RunServerCommand"]; int sent = 0; public Service1() … -
CS50W Django sessions
I'm currently working on CS50W and have a problem with the concept of Session in Django: When introducing the notion of session, the global variable 'tasks = []' is implemented in user's session. My problem is that in the add function, tasks.append(task) is no longer defined. I have this exact code: from django import forms from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse # Create your views here. class NewTaskForm(forms.Form): task = forms.CharField(label = "New Task") def index (request): if "tasks" not in request.session: request.session["tasks"] = [] return render(request, 'tasks/index.html', { "tasks" : request.session["tasks"] }) def add (request): if request.method == "POST": form = NewTaskForm(request.POST) if form.is_valid(): task = form.cleaned_data["task"] tasks.append(task) return HttpResponseRedirect(reverse("tasks:index")) else : return render (request, 'tasks/add.html', { "form": form }) return render(request, 'tasks/add.html', { "form":NewTaskForm() }) I've tried to replace 'tasks.append(task)' by 'request.session["tasks"]' but it doesn't work. -
Folder sometimes found and sometimes not found - DJANGO AUDIO CONTROLS
i have web that can uploaded file and save it to local storage. but when i got the file back, sometimes the folder of file can be detect but sometimes it's say not found. i want get the file back to played it at audio controls. first, when i uploaded file, the file cannot be play. second, when i open new web, the file can be played. at the same time, when i uploaded new file again, the new file cannot be played until i open new web. here's my code at html: <audio controls="controls"> <source src="/media/mp3/{{last_audio.audio}}" type="audio/mpeg"> </audio> views.py: def homepage(request): form = AudioForm() last_audio = Audio_store.objects.last() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() audio = form.cleaned_data.get("audio") print(audio) context={'form':form, 'last_audio':audio} return render(request, 'homepage.html', context) context={'form':form, 'last_audio':last_audio} return render(request, "homepage.html", context=context) i was already delete database and create again, but it's still same. please help me, i don't know what's wrong. i was using chrome, incognito and microfost edge, and the result its same. -
ChoiceField vs TypedChoiceField (Django)
I read the documentation about ChoiceField and TypedChoiceField but I could only understand that both can create Dropdown Select Box which looks exactly the same as shown below: The code with ChoiceField below: FRUITS = ( (1,'Apple'), (2,'Orange'), (3,'Banana') ) fruits = forms.ChoiceField(choices=FRUITS) # Here The code with TypedChoiceField below: FRUITS = ( (1,'Apple'), (2,'Orange'), (3,'Banana') ) fruits = forms.TypedChoiceField(choices=FRUITS) # Here My questions: What is the difference between ChoiceField and TypedChoiceField? When to use ChoiceField and TypedChoiceField? -
Nested Serializer creates new object
I have a serializer called EntrySerializer and it should return the staff details but if I want to create a new entry it wants to create a new staff object and throws an error. Is there anything like a read only field for my serializer? It should create a new entry but assign an already created staff object. class EntrySerializer(serializers.ModelSerializer): staff = serializers.SerializerMethodField('get_staff') def get_staff(self, obj): return MyUserSerializer(obj.staff).data class Meta: model = Entry depth = 1 fields = ('time_spend', 'staff',) Error: django.db.utils.IntegrityError: ERROR: NULL-value in Column »staff_id« relation »tagesbericht_tagesbericht_Entry« Not-Null-Constraint DETAIL: (54, 00:00:08.5, null, 61). POST: "tagesbericht_entry_set": [ { "staff": 2, "time_spend": "00:12:08" } ] -
Cant Adding to detail page user's posts İn django
Hey ı am trying to add the user's post to the detail page with DetailView but ı cant add this is the code ı wrote profile.py from django.shortcuts import get_object_or_404 from django.views.generic import DetailView from account.models import CustomUserModel from django.shortcuts import get_object_or_404 class ProfilDetailView(DetailView): template_name = 'pages/profil.html' context_object_name='profil' def get(self,request): profil = get_object_or_404( CustomUserModel,username=self.kwargs.get('username') ) yazi = get_object_or_404(YazilarModel,yazar=profil.username) return render(request,'pages/profil.html',context={ 'profil':profil, 'yazilar':yazi.all() }) urls.py path('kullanıcı/<str:username>',ProfilDetailView.as_view(),name='profil'), profil.html {% extends 'base.html'%} {% load static %} {% block title %} {{profil.username}} {% endblock %} {% block content %} <div class="card mb-3"> <div class="row g-0"> <div class="col-md-4"> {% if profil.avatar %} <img src="{{profil.avatar.url}}" class="rounded" class="pt-4" width="200px" height="200px " style="border: radius 15%; margin-right:20px; " alt=""> {% else %} <img src="{% static 'img/no-avatar.jpg'%}" class="rounded" class="pt-4" width="200px" height="200px " style="border: radius 15%; margin-right:20px; " alt=""> {% endif %} </div> <div class="col-md-8"> <div class="card-body"> {% if profil.get_full_name == '' %} <h5 class="card-title"> Adı : Girilmemiş</h5> <h5 class="card-title"> Soyadı : Girilmemiş</h5> {% else %} <h5 class="card-title"> Adı : {{profil.first_name}}</h5> <h5 class="card-title mb-5"> Soyadı : {{profil.last_name}}</h5> {% endif %} <h5>Hakkında :</h5> <hr> <p>Bla Bla Bla</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> </div> </div> <hr> {%endblock%} yazilar.py in models from distutils.command.upload import upload from enum import unique … -
M2M attribute error with FOO_set.all() and FOO not a queryset
Having a problem with a M2M related queryset: simplified model is class Category(models.Model): name = models.CharField(max_length=200) class Product(models.Model): name = models.CharField(max_length=200) category = models.ManyToManyField( Category, blank=True, null=True, related_name="categorytest") I usually do related queries using related name (which works fine here no problem) yet I wanted to try "set_all()" in this case. Say I do: elecs = Category.objects.get(name="Electronics") then: elecs.product_set.all() I get AttributeError: 'Category' object has no attribute 'product_set'. I am a bit surprised because this is an error that happens when using a queryset instead of a model instance yet, if a confirmation was needed, a type(elecs) gives me <class 'store.models.Category'>. I migrated/erased db multiple times, no change. Any idea ? Thanks -
How to put html code of method admin.ModelAdmin class in seperate .html file and add css to it?
I want to put the following code of def show_tags_btn into a separate .html file and add some CSS to it, How can I do it? class BusinessAccountAdmin(admin.ModelAdmin): list_display = ['id', 'business_title', 'business_description', 'status', 'note', 'show_tags_btn', 'is_approved'] def show_tags_btn(self, instance): work_samples = instance.worksamplesmodel_set.all() res = '' for ws in work_samples: res = res+str(ws.work_sample_description)+'<hr>' print(ws.work_sample_description) model = f''' <html> <body> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <div class = "modal fade bd-example-modal-sm-{instance.id}" tabindex = "-1" role = "dialog" aria-labelledby = "mySmallModalLabel" aria-hidden = "true" > <div class="modal-dialog modal-sm"> <div class="modal-content"> {res} </div> </div> </div> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-sm-{instance.id}">Small modal</button> </body> </html> ''' return format_html(model) admin.site.register(BusinessAccountModel,BusinessAccountAdmin) Adding a bootstrap CDN link here is a good idea? After adding CDN link it affect my django admin panel colours, Why? -
Folder sometimes found and sometimes not found - DJANGO AUDIO CONTROLS
i have web that can uploaded file and save it to local storage. but when i got the file back, sometimes the folder of file can be detect but sometimes it's say not found. i want get the file back to played it at audio controls. first, when i uploaded file, the file cannot be play. second, when i open new web, the file can be played. at the same time, when i uploaded new file again, the new file cannot be played until i open new web. at my terminal like this: here's my code at html: <audio controls="controls"> <source src="/media/mp3/{{last_audio.audio}}" type="audio/mpeg"> </audio> views.py: def homepage(request): form = AudioForm() last_audio = Audio_store.objects.last() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() audio = form.cleaned_data.get("audio") print(audio) context={'form':form, 'last_audio':audio} return render(request, 'homepage.html', context) context={'form':form, 'last_audio':last_audio} return render(request, "homepage.html", context=context) i was already delete database and create again, but it's still same. please help me, i don't know what's wrong. i was using chrome, incognito and microfost edge, and the result its same. -
Python how to pass form input value to payload
I need to submit a form to an API and I want to pass the form fields value to the Payload for a python request API,enter code here how can I achieve this? models.py class Book(models.Model): trading_name = models.CharField(max_length=100, null=True) industry = models.CharField(max_length=100, null=True) vat = models.CharField(max_length=100, null=True) address_street = models.CharField(max_length=100, null=True) address_city = models.CharField(max_length=100, null=True) address_postal_code = models.CharField(max_length=100, null=True) address_iso_country = CountryField(max_length=100, null=True) def __str__(self): return self.title forms.py class BookForm(forms.ModelForm): class Meta: model = Book fields = ('trading_name', 'industry', 'vat', 'address_street', 'address_city', 'address_postal_code', 'address_iso_country') views.py def upload_kyb(request): if request.method == 'POST': url = 'https://stoplight.io/mocks/railsbank/api/25652867/v1/customer/endusers' headers = { 'Content-Type': "application/json", 'Accept': "application/json", 'Authorization': "" } payload = "{ \n \"company\": {\n \"name\": \"Example Company\", \n \"trading_name\": \"jiuliasu\",\n \"industry\": \"Telecommunications\",\n \"vat\": \"GB123456789\",\n \"registration_address\": \n {\n \"address_refinement\": \"Floor 15\", \n \"address_number\": \"20\", \n \"address_street\": \"Floor 15\", \n \"address_city\": \"London\", \n \"address_postal_code\": \"SS8 9JH\", \n \"address_iso_country\": \"GBR\" \n }\n\t}\n}" response = requests.request("POST", url, data=json.dumps(payload), headers=headers) print(response.text) print(payload) # form = Kybform(request.POST, request.FILES) form = BookForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('kyb_list') else: form = BookForm() return render(request, 'kybstart/upload_kyb.html', { 'form': form }) I can get the response in the console but how can I actually pass the form inputs dynamically into the Payload? -
I had built my own payment system how can i integrate with any ecommerce website?
I had developed my own payment system. Now I want to integrate with any ecommerce website. How to write view to integrate with it. -
How to fix def of XYZModelAdmin class in admin.py reciving same instance for each time?
In the following code, I am displaying the id in the bootstrap model as an instance.id. but for every row it shows same id of the first instance. class BusinessAccountAdmin(admin.ModelAdmin): list_display = ['id', 'business_title', 'business_description', 'status', 'note', 'show_tags_btn', 'is_approved'] list_editable = ('is_approved',) def show_tags_btn(self, instance): model = f''' <body> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <div class = "modal fade bd-example-modal-sm" tabindex = "-1" role = "dialog" aria-labelledby = "mySmallModalLabel" aria-hidden = "true" > <div class="modal-dialog modal-sm"> <div class="modal-content"> {instance.id} </div> </div> </div> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-sm">Small modal</button> </body> ''' return format_html(model) admin.site.register(BusinessAccountModel,BusinessAccountAdmin) Why def show_tags_btn(self, instance) method receiving same instance for every time? -
Flutter Web Failed to load resource: the server responded with a status of 404
I'm having problem to deploy my flutter web app to cpanel. Please find the screenshot of the error And this is my current base href on index.html <base href="/"> I found some questions asking about this issue but nothing is worked for me. I follow the solution on this link when deploying the app How to serve a Flutter web app with Django? I also tried to change the base href to <base href="./"> , <base href="/web_app_name/"> , and also remove the base href but still didn't work. Hope someone has the solution for this. -
Forbidden <URL> User Registration Python Django
I created a Patient model in models.py file and then used a serializer to convert the data. Previously, I was using the built-in User model and serializers to perform user registration, email verification and login. But I had to add extra fields and thought it would be better to make a separate table in the DB. I've made the migrations and the changes, but I get the forbidden error. I was wondering if my Postman request was correct or not. Please guide me! My models.py file: from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator GENDER_CHOICES = ( ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other') ) class Patient(models.Model): patient_name = models.CharField(max_length=50, null=False) address = models.CharField(max_length=254, null=False) contact_no = models.IntegerField( validators=[MaxValueValidator(99999999999)], blank=False) dob = models.DateField(null=False) gender = models.CharField(choices=GENDER_CHOICES, max_length=128, null=False) email = models.EmailField(max_length=254, null=False, unique=True) password = models.CharField(max_length=25, null=False) is_active = models.BooleanField(null=False) class VerificatonToken(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='token') verification_token = models.CharField( max_length=256, blank=True, null=True) My serializers.py file: (the commented code is from when I was solely using serializers and User for user registration, email confirmation & login. from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework_jwt.settings import api_settings from .models import Patient, … -
How to replace 'delete selected ' action with a delete button? Django admin
i have a question since i only have one action (in django admin) which is delete selected, i want to make a specific button for it called 'Delete ' instead of choosing the action and then clicking on go . How can i do that? -
How to get reverse relationship object django annotate with subquery?
It's not a good structure, but it's an example This is my sample model class Book(models.Model): name = models.CharField(max_length=50) class Borrower(models.Model): book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=50) age = models.IntegerField() class OwnerCard(models.Model): certification_date = models.DateField() class Owner(models.Model): owner_card = models.ForeignKey(OwnerCard, on_delete=models.SET_NULL, null=True) book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=50) age = models.IntegerField() I want to use reverse relationship to get the object of the Borrower and Owner from the Book Model Like this from django.db.models import Subquery, OuterRef Books = Book.objects.all().annotate( borrower=Subquery(Borrower.objects.get(user=OuterRef('user'))), owner=Subquery(Owner.objects.get(user=OuterRef('user'))) ) Or Books = Book.objects.all().annotate( borrower=Subquery(Borrower.objects.filter(user=OuterRef('user')).first()), owner=Subquery(Owner.objects.filter(user=OuterRef('user')).first()) ) and I want use print(Books[0].brrower.name) >>> brrower's name print(Books[0].owner.owner_card.certification_date) >>> certification date But, it's not working. don't have to use annotate or subquery. Is there a way to implement it this way? -
Trying to add a button to Django admin
So, I use a custom administration (grappelli) I need to add my button with functionality. Used the documentation - https://django-grappelli.readthedocs.io/en/latest/customization.html Here’s another - ImportError: cannot import name 'url' from 'django.conf.urls' after upgrading to Django 4.0 I created the timetable\templates\admin\change_list.html, code in it: {% extends "admin/change_list.html" %} {% load i18n %} {% block object-tools-items %} {{ block.super }} <li> {% comment %} <a class="historylink" href="test_data/">My custom admin page</a> {% endcomment %} <a href="#" class="grp-add-link grp-state-focus">Add ТЕСТ (ТаМ ДЕ НАДА)</a> прив)) </li> {% endblock %} If you look at an ordinary admin (without grappelli), the button appeared If With it, then no button. If you edit venv\Lib\site-packages\grappelli\templates\admin\change_list.html, The button appears, but it’s not the case... How can I make grappelli see my button? -
django form styling with bootstrap4 problem
I got some problems styling a form in django with bootstrap. I tried some diffrent ways to get it to work but cant. Any ideas how to style this form with bootstrap 4? at the moment with the code i have it looks like this. enter image description here **edit_profile_page.html** {% extends 'base.html' %} {% block title %}Edit Profile Page{% endblock %} {% block content %} {% if user.is_authenticated %} {% if user.id == profile.user.id %} <h1>Edit Profile Page</h1> <br/><br/> <div class="form-group"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-info">Update Profile Page</button> </div> {% else %} You got no access here! {% endif %} {% else %} You got no access here! {% endif %} {% endblock %} forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm from django.contrib.auth.models import User from django import forms from newsapp.models import Profile class ProfilePageForm(forms.ModelForm): class Meta: model = Profile fields = ('bio', 'profile_pic', 'website_url', 'facebook_url', 'twitter_url', 'instagram_url', 'pinterest_url') widgets = { 'bio': forms.Textarea(attrs={'class': 'form-control'}), 'website_url': forms.TextInput(attrs={'class': 'form-control', }), 'facebook_url': forms.TextInput(attrs={'class': 'form-control'}), 'twitter_url': forms.TextInput(attrs={'class': 'form-control'}), 'instagram_url': forms.TextInput(attrs={'class': 'form-control'}), 'pinterest_url': forms.TextInput(attrs={'class': 'form-control'}), }