Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Limit scope of external css to only a specific page?
I am creating a django project using HTML5, and CSS,. while extending the base.html to other files ,when I load in a new css file, it (obviously) overrides the one I'm using to style the page, and therefore most of the elements are affected like a tag and others. so is there Limit scope of external css to only a specific file.? Please tell me some solution i am a beginner and i am frustrated by this -
How to make dropdown menu for year at top side for orders statics page at Django?
I have 3 years of customer order information. I created a order statics page with Django. But years section not dynamic. This stats page getting datas with this_year = datetime.now().year. That's why displaying only in this years (2022) stats. I want to selectable a dropdown menu. When select previous year 2021, this year will be this_year = 2021. And will be display previous year's stats. How can make a menu for previous years? this_year = datetime.now().year - 1 ? Thank you. Some codes from views.py total_payment = ( orders.filter( date_created__month=this_month, date_created__year=this_year, status="Completed", ) .aggregate(Sum("payment")) .get("payment__sum") or 0 ) -
pyehon - TypeError: unhashable type: 'dict' [duplicate]
This piece of code is giving me an error unhashable type: dict can anyone explain to me what the solution is? cls.url_index = {'/': 'index.html'} cls.url_profile = {f'/profile/{cls.user.username}/': 'profile.html'} cls.url_group_list = {f'/group/{cls.group.slug}/': 'group_list.html'} cls.url_create = {'/create/': 'posts/post_create.html'}, cls.url_edit = {f'/posts/{cls.post.id}/edit/': 'posts/post_edit.html'} cls.url_post_detail = {f'posts/{cls.post.id}/': 'posts/post_detail.html'} cls.redirect_edit = {f'/auth/login/?next=/posts/{cls.post.id}/edit/'} cls.redirect_create = {'/auth/login/?next=/create/'} cls.url_fake = '/fake_page/' cls.ok = HTTPStatus.OK cls.not_found = HTTPStatus.NOT_FOUND ` def test_list_url_exists_at_desired_location(self): urls_posts = { self.url_index: self.ok, self.url_group_list: self.ok, self.url_profile: self.ok, self.url_post_detail: self.ok, self.url_fake: self.not_found, }` -
why authenticate is not working for user objects despite having objects saved in admin panel in Django
here is my loginHtml code <form method="post" action="handleLogin_url" enctype="multipart/form-data"> {{ tryAgain }} <br> {% csrf_token %} <label for="username">Enter Username</label><input id="username" name="username" type="text"> <label for="password">Enter password</label><input id='password' name="password" type="password"> <input type="submit" value="Lets Go"> views.py def handleLogin(HttpRequest): if HttpRequest.method=='POST': enteredname = HttpRequest.POST['username'] # user = User.objects.get(username=enteredname) enteredpassword = HttpRequest.POST['password'] user = authenticate( HttpRequest, username=enteredname,password=enteredpassword) # return render(HttpRequest, 'seeData.html', # {'User': user, 'enteredname': enteredname, 'enteredpassword': enteredpassword}) if user is not None: return render(HttpRequest, 'seeData.html', {'Users':user, 'enteredname':enteredname, 'enteredpassword':enteredpassword}) else : tryAgain = "Invalid username or password try again" return render(HttpRequest, 'LoginHtml.html', {'tryAgain':tryAgain}) else: return render(HttpRequest,'LoginHtml.html') seeDataHtml code {{ User.username }},{{ User.password }}||{{ enteredname }} {{ enteredpassword }} when I try using superuser credentials a superuser object is returned but when I use a user credential no object is returned but when I log into admin site I can see user objects -
How do i initialize value of a form using django sessions
class StudentAnswerForm(ModelForm): questionid = forms.ModelChoiceField(widget=forms.Select(), queryset=Quiz.objects.only('questionid')) studentanswer = forms.CharField(widget=forms.TextInput()) quizid = forms.ModelChoiceField(widget=forms.Select(), queryset=Quiz.objects.only('quizid')) username = forms.CharField(widget=forms.TextInput(),initial=request.session['username']) class Meta: model = StudentAnswer fields = ['quizid','questionid','studentanswer'] #fields = ['student_answer'] my views class AnswerQuiz(View): template = 'ansQuiz.html' def get(self, request): form = StudentAnswerForm() request.session['visits'] = int(request.session.get('visits', 0)) + 1 quiz = Quiz.objects.all() #get data from all objects on Quiz model return render(request, self.template,{'quiz':quiz, 'form':form}) def post(self,request): form = StudentAnswerForm(request.POST) if form.is_valid(): form.save() return render(request, self.template, {'form':form}) -
Many to Many relationship - Returning "main.ModelName.None"
I am trying to return a few values from other models via a ManyToManyField. It's returning main.ModelName.None in the template. The data is visible through the admin panel. As a result, I am assuming the problem is linked to the views or the way I render the data in HTML. I found a few post on the topic with the same problem but it seems there were dealing with an error message that I am not getting. In my case, I just cant render the data. Here is the code: models.py class Project(models.Model): name = models.CharField(verbose_name="Name",max_length=100, blank=True) def __str__(self): return str(self.name) if self.name else '' class Product(models.Model): project = models.ManyToManyField(Project, blank=True, related_name="available_products") class Meta: db_table='Product' def __str__(self): return str(self.name) views.py def show_product(request, product_id): products = Product.objects.get(pk=product_id) return render(request, 'main/show_product.html',{'products':products}) template <h6>Project Name</h6> {{ products.project }} This returns main.Project.None -
I want to know about using required=False in a DRF Serializer
I have a Serializer (not a model serializer) class DummySerializer(serializers.Serializer): clas = serializers.CharField() section = serializers.CharField(required=False) Now, when I give blank input ("") to "section" while PUT, then I receieve error (though I have given required=False) as { "section": [ "This field may not be blank." ] } I want something like this, If I give both "clas" and "section" as input then my request.data should give {"clas": "my_input", "section": "my_input"} and when I give only "clas" then request.data should give {"clas": "my_input" } NOT {"clas": "my_input", "section": ""} Then in my view, I want to give a default value to a variable based on field "section" is there or not as var = request.data.get("section", "default_val") can someone pls help here, how to achieve this behaviour. -
how to set model.field equal to a foreignkey,s model.field value django if no value is provided in the form?
class Album(TimeStampedModel): name = models.CharField(default='New Album' , max_length = 80) release_datetime = models.DateTimeField(blank = False) cost = models.DecimalField(blank = False, decimal_places = 2,max_digits = 15) artist = models.ForeignKey(Artist, on_delete=models.CASCADE) is_approved = models.BooleanField(default=False) def __str__(self): return (f"id: {self.id} \n name: {self.name} cost: {self.cost} \n approved : {self.is_approved}") class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) name = models.CharField(blank = True , max_length = 80) image = models.ImageField(blank = False) thumbnail = ImageSpecField(format='JPEG') I want to make Song.name = album.name if supplied name from form is = "" (empty) how can I do this thanks in advance class Song(models.Model): # album = models.ForeignKey(Album, on_delete=models.CASCADE) name = models.CharField(blank?album.name) # image = models.ImageField(blank = False) # thumbnail = ImageSpecField(format='JPEG') something like that -
Django Custom Model Class,AttributeError has no attributes
From the online examples, this piece of code should create a model class that I can migrate. However, when ever I try to migrate, it keeps on telling me "AttributeError: type object 'Foo' has no attribute 'REQUIRED_FIELDS', or "USERNAME_FIELD" , and then keep on going. I don't understand why it makes me create these fields but in tutorials the code works without them. from django.db import models class Foo(models.Model): pass -
Exception Type: KeyError when registering a new user using a custom made register model
Whenever I try to register a new user when i receive an Exception Type: KeyError error. There seem to be something wrong with the submitted password but I don't understand the issue in depth. Can someone please explain this error to me? And perhaps how to solve it as well. The user is created, I can see that in the admin page. I also want the user to sign in when the account is created. I appreciate all inputs! <3 My model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, User, PermissionsMixin from django.utils import timezone from django.utils.translation import gettext_lazy as _ from generalpage.managers import CustomUserRegisterManager from django.conf import settings from generalpage.managers import CustomUserRegisterManager class UserRegister(AbstractBaseUser, PermissionsMixin): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) username = models.CharField(_("Användarnamn"), max_length=100, null=True, unique=True) age = models.IntegerField(_("Ålder"),null=True, blank=False) email = models.EmailField(_("E-mail"), unique=True, null=False) country = models.CharField(_("Land"),max_length=50, null=True, blank=True) county = models.CharField(_("Län"),max_length=50, null=True, blank=True) city = models.CharField(_("Stad"),max_length=50, null=True, blank=True) profile_picture = models.ImageField(_("Profilbild"),null=True, blank=True, default="avatar.svg", upload_to = "static/images/user_profile_pics/") is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' # defines the unique identifier for the User model REQUIRED_FIELDS = ["username"] # A list of the field names that will be prompted for when creating a user … -
nginx django project nginx.conf
I have a django project. I'm trying to get my project on the server. I have my project on the server, but I'm having a problem with nginx. In connection with this, my css is not visible. Error: nginx: [emerg] unknown directive "etc/nginx/nginx.conf" in /etc/nginx/nginx.conf:7 nginx: configuration file /etc/nginx/nginx.conf test failed etc/nginx/nginx.conf enter code here etc/nginx/nginx.conf -# For more information on configuration, see: -# * Official English Documentation: http://nginx.org/en/docs/ -# * Official Russian Documentation: http://nginx.org/ru/docs/ user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; -# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 4096; include /etc/nginx/mime.types; default_type application/octet-stream; -# Load modular configuration files from the /etc/nginx/conf.d directory. -# See http://nginx.org/en/docs/ngx_core_module.html#include -# for more information. include /etc/nginx/conf.d/*.conf; server { listen 81; listen [::]:81; server_name __; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; error_page 404 /404.html; location = /404.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } location /static/ { root /home/username/public_html/; expires 1d; } } -# Settings for a … -
multiple file upload with reactjs form and Django backend not working
I created backend to upload multiple images with some text and multiple documents using django rest framework. I tested the backend with postman and upload works fine! when i upload files with react form, backend throws error with request.FILES empty. I am using React 17.0.2 version and next 12.0.4 Django version is 3.2.14 and rest-framework version is 3.13.1 Below is the code of react submit form. i am able to see the files in the console is submit form handler. const submitForm = async e => { const formData = new FormData() formData.append('name', e.formData.name) formData.append('city', e.formData.city) formData.append('email', e.formData.city) formData.append('images', e.formData.images) formData.append('email', e.formData.email) formData.append('mobile', e.formData.mobile) formData.append('docs', e.formData.req_doc) formData.append('description', e.formData.description) let url = 'http://localhost:3000/requirement/requirements/' fetch(url, { method: 'POST', headers: { Accept: '*/*', 'Accept-Encoding': 'gzip, deflate, br', content_type: 'multipart/form-data; boundary=<calculated when request is sent>' }, body: formData }).then(function (response) { console.log(response) }) i am also attaching the screenshot of request from browser which shows the images and files being sent in request. https://i.imgur.com/Ni5pm84.png The Django backend code where error occurs is below. class RequirementSerializer(serializers.ModelSerializer): images = RequirementImageSerializer(many=True, required=False) requirement_files = RequirementDocSerializer(many=True, required=False) class Meta: model = Requirement fields = ['id', 'name','description', 'email', 'mobile', 'city', 'created_at', 'updated_at','images','requirement_files'] # def validate_name(self,value): # if(value == "sumit"): … -
Is django storage sftp reliable method for uploading multiple small files uploaded by user to server?
Due to s3 unpredictable requests count on file upload and get, I want to use my own file server. The best method I have found so far is Sftp django storage but I am curious if it is reliable or not. I will use it for uploading images by multiple users say 10000 images per day by 1000 users. My application server and file server will be diferrent. So I am asking if it is a good approach or not? If it is not what method do you advise me to use? -
django + nginx on Docker (400) Bad Request
Although I tried every method raised in StackOverFlow, I cannot solve the problem. When I want to login my site, the error shows up. What I tried ALLOWED_HOSTS = ['*'] Removing underscore from the name of hosts Putting the name of upstream in nginx.conf Putting some stuff for nginx.conf as the following nginx.conf file settings.py ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ") env.prod DEBUG=Fault DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] ecap nginx.conf upstream ecap { server web:8000; } server { listen 80; location / { proxy_pass http://ecap; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/app/web/staticfiles/; } location /mediafiles/ { alias /home/app/web/mediafiles/; } } docker-compose.prod.yml version: '3.8' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn ecap.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:13.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - ./static_volume:/home/app/web/staticfiles - ./media_volume:/home/app/web/mediafiles ports: - 1337:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: log ecap5-nginx-1 | 192.168.192.1 - - [15/Oct/2022:10:17:30 +0000] "POST /login/%7Burl%20'Login'%20%%7D HTTP/1.1" 400 157 "-" "-" "-" I appreciate your cooperation. -
CORS policy Error in react app while Zoho meeting api integrations
I have been trying to integrate zoho meetings with my application(React is front end and django is backend). While fetching the access token i'm getting the following error. Access to fetch at 'https://accounts.zoho.com/oauth/v2/token?code=1000.53axxxxxxxxxxxxxxxxxxxxxxxxxx2e8e5eb43cfe53005f8d93490&client_id=1000.PGPL8RK7R54UR7JSNKTM2ZRETSF4CI&client_secret=xxxxxxxxxxxxxxxxxxx&redirect_uri=http://localhost:3000/app_store/zoho_meet&grant_type=authorization_code' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. here is my axios code part` headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', "Access-Control-Allow-Origin": "*", } }) const url = `https://accounts.zoho.com/oauth/v2/token?code=${zcode}&client_id=1000.xxxxxxxxxxxxxxxI&client_secret=92821f12d14cf11162891xxxxxxxxxxxxxxxxxxxx&redirect_uri=http://localhost:3000/app_store/zoho_meet&grant_type=authorization_code` publicAxios.get(url) .then((res)=>{ console.log(res) }) .catch((err)=>{ console.log(err) }) ` can anybody here help me what steps did i missed here -
Internal server error(digital ocean) django
I wish you can help me with this issue I deployed my project to Ubuntu 22.0 droplet 3 days ago with nginx and gunicorn and certbot everything was working fine but yesterday i was going to update the project and first I installed wkhtmltopdf after that i restarted the server and the website keep gives me Internal server error i dont know what happen to the sever corrupt it like that i wish you could help me I tried to restart ngnix and gunicorn should i need to do something else im new with wkhtmltopdf so i dont understand how this can happen -
do some things same time in the Django unit test
How can I test if two users can reserve the same car simultaneously? def test_if_two_users_can_reserve_the_same_car_simultaneously(self): with patch.object( timezone, "now", return_value=make_aware( datetime.datetime.combine( datetime.date.today() + datetime.timedelta(days=1), datetime.time(10, 30, 0) ), timezone=pytz.timezone("UTC"), ), ): self.client.login(username=self.user.username, password=self.PASSWORD) url = reverse("booking-list") data = { "book_for": datetime.datetime.combine( datetime.date.today() + datetime.timedelta(days=1), datetime.time(11, 30, 0) ), } response = self.client.post(url, data=data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) with patch.object( timezone, "now", return_value=make_aware( datetime.datetime.combine( datetime.date.today() + datetime.timedelta(days=1), datetime.time(10, 30, 0) ), timezone=pytz.timezone("UTC"), ), ): self.client.login( username=self.another_user.username, password=self.PASSWORD ) url = reverse("booking-list") data = { "book_for": datetime.datetime.combine( datetime.date.today() + datetime.timedelta(days=1), datetime.time(11, 30, 0) ), } response = self.client.post(url, data=data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) This is how I wrote it, but in the unit test, it runs line by line. So first one will create then move to second one but I want them both run at same time. (Please answer with an example) -
simple song CRUD application with a music app
simple song CRUD application. In our models.py file inside the “musicapp” application we created, you are expected to add the following Models and Attributes. Model: Artiste, Song, Lyric Attributes for “Artiste” : first_name, last_name, age Attributes for “Song”: title, date released, likes, artiste_id Attributes for “Lyric”: content, song_id As you might have guessed, there is a relationship between all three Models. An Artiste can have multiple songs, and a song can have multiple lyrics.A song must only belong to one Artiste and a lyric must only belong to a song. -
How to authenticate a user in django unit test when rest framework's DEFAULT_AUTHENTICATION_CLASSES is 'JWTStatelessUserAuthentication'?
I had a Django project with the following settings: 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] and in the unit testing phase, I used to assign a Token to an existing user to authenticate the user: def setUp(self): self.user = User.objects.create(username='u1') self.client = APIClient() token = Token.objects.create(user=self.user) self.client.credentials(HTTP_AUTHORIZATION="Token " + token.key) but now, in my current project, I don't authenticate users, instead, I use these settings: 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTStatelessUserAuthentication', ], SIMPLE_JWT = { 'ALGORITHM': '...', 'SIGNING_KEY': '...', } and user authentication stuff is in another project and authentication tokens have an expiration time! How can I authenticate a user in my unit testing?! Is there any solution to this issue? -
How to use dj-rest-auth with many clients
I'd like to have many different clients be able to access my django website (more specifically its API) but I'm not sure how to do this with django-allauth, dj-rest-auth and simplejwt. My current client app is using the built in django template engine and is set up with django-allauth for social authentication (Google etc). It's working using the documented installation recommendations. I would now like to create different types of clients that aren't using the django template engine (e.g. Angular, Vue, flutter mobile etc) but I'm confused how dj-rest-auth is used so that it scales to support any number of client types. Using Google social sign in as an example, when I create a new client, I have to register a new redirect_uri specific to that client. To test this all out, I created a simple flask app with a single link so that I can retrieve a "code/access_token" before sending it to my Django app. The link is created using the following... var codeRequestUrl = `https://accounts.google.com/o/oauth2/v2/auth?\ scope=email&\ access_type=offline&\ include_granted_scopes=true&\ response_type=code&\ state=state_parameter_passthrough_value&\ redirect_uri=http%3A//127.0.0.1:5000/callback&\ client_id=${clientId}`; ...and the code is retrieved at the '/callback' endpoint in flask... @app.route("/callback", methods=['GET']) def redirect(): code = request.args.get('code', '') req = requests.post('http://127.0.0.1:8000/api/dj-rest-auth/google/', data={'code':code}) return "done..." ...from … -
Django IntegrityError (1048, "Column 'item_id_id' cannot be null")
The error posted is Integrity Error 1048 column cannot be null IntegrityError at /Supply/supplyItems (1048, "Column 'item_id_id' cannot be null") Request Method: POST Request URL: http://127.0.0.1:8000/Supply/supplyItems Django Version: 4.1.1 Exception Type: IntegrityError Exception Value: (1048, "Column 'item_id_id' cannot be null") Exception Location: C:\Users\63966\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\mysql\base.py, line 80, in execute Raised during: Supply.views.SupplyItem Python Executable: C:\Users\63966\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.6 Python Path: ['D:\CIT\3rd Year\IM 2\New ' 'folder\sarisaristoreproject\sarisaristoreproject\sarisaristoreproject', 'C:\Users\63966\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\63966\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\63966\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\63966\AppData\Local\Programs\Python\Python310', 'C:\Users\63966\AppData\Local\Programs\Python\Python310\lib\site-packages'] Server time: Sat, 15 Oct 2022 07:25:53 +0000 Here is my models.py class Supplier(models.Model): supplier_id = models.AutoField(primary_key=True) company_name = models.CharField(max_length=20, null=False) company_address = models.CharField(max_length=50, null=False) company_num = models.IntegerField(null=False) def __str__(self): return str(self.company_name) class supplyItem(models.Model): item_id = models.ForeignKey('Items.Items', on_delete=models.CASCADE) supplier_id = models.ForeignKey(Supplier, on_delete=models.CASCADE) numOfItemsS = models.IntegerField() Items model from different App: class Items(models.Model): item_id = models.AutoField(primary_key=True) item_name = models.CharField(max_length=50, null=False) item_qty = models.IntegerField(null=False) item_prc = models.FloatField(null=False) purchase = models.ManyToManyField('registration.Customer', through='Purchase.purchasedItem', related_name='items', blank=True) sell = models.ManyToManyField('registration.Employee', through='Sell.sellItem', related_name='items', blank=True) def __str__(self): return self.item_name My views.py class HomeView(View): template = 'supply.html' def get(self, request): return render(request, self.template) class SupplyItem(View): template = 'SupplyItems.html' def get(self, request): form = SupplyItemForm() return render(request, self.template, {'form': form}) def post(self, request): form = SupplyItemForm(request.POST) if form.is_valid(): form.save() return render(request, self.template, {'form': form}) Forms.py class SupplyItemForm(ModelForm): itemID = forms.ModelChoiceField(widget=forms.Select(), queryset=Items.objects.only('item_id'), label='Item … -
ProgrammingError at / relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se
i dont know why am getting this django_session does not exist error its working when am running it on localserver but when i have deployed to heroku i am getting this error , is anyone help me to resolve this issue coz am not able to figure out , what is it In settings.py file # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'home.apps.HomeConfig', 'blog.apps.BlogConfig' ] DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "<name>", "USER": "<username>", "PASSWORD": "<pass>", "HOST": 'localhost', "PORT": '5432', } } here i have added my credentials -
Django sesssions and Microsoft OAuth 2.0 authorization code flow: what is the right way?
In my web app I collect some data from a user and save them in request.session. Then I need to obtain MS Graph access/refresh tokens. So I request an authorization code. After that I need to return to the initial user's sessions. app_name = 'sua' urlpatterns = [ path('', WizardView.as_view(), name='main'), path('cauth', CloudAuthView.as_view(), name='cauth'), ] class CloudAuthView(View): def get(self, request): auth_code = request.GET.get('code', '') if auth_code: session_key = request.GET.get('state', '') s = SessionStore(session_key=session_key) s['auth_code'] = auth_code print(f'auth_code: {request.session.session_key}; {request.META.get("HTTP_REFERER")}') return redirect(reverse('sua:cauth')) print(f'get: {request.session.session_key}; {request.META.get("HTTP_REFERER")}') auth_url = _get_auth_url(state=request.session.session_key) print(auth_url) return redirect(auth.get_auth_url(state=request.session.session_key)) Logs: Starting development server at http://127.0.0.1:43814/ Quit the server with CTRL-BREAK. [15/Oct/2022 13:30:53] "GET / HTTP/1.1" 200 5528 [15/Oct/2022 13:30:59] "POST / HTTP/1.1" 302 0 get: es52sm9fxogmhwgja3nkgzel2g9declx; http://127.0.0.1:43814/ auth_url: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A43814%2Fcauth&scope=offline_access+User.Read+Files.Read+User.Read.All+User.ReadWrite.All+Directory.Read.All+Directory.ReadWrite.All+Files.ReadWrite.All+Sites.FullControl.All&response_type=code&state=es52sm9fxogmhwgja3nkgzel2g9declx&client_id=xxx [15/Oct/2022 13:30:59] "GET /cauth HTTP/1.1" 302 0 auth_code: j92mb1ougcqjhvr50xsfufap1jayru5s; http://127.0.0.1:43814/ [15/Oct/2022 13:31:00] "GET /cauth?code=0.AUIAGvBhs...&state=es52sm9fxogmhwgja3nkgzel2g9declx&session_state=2794f2aa HTTP/1.1" 302 0 get: j92mb1ougcqjhvr50xsfufap1jayru5s; http://127.0.0.1:43814/ [15/Oct/2022 13:31:00] "GET /cauth HTTP/1.1" 302 0 [15/Oct/2022 13:31:00] "GET / HTTP/1.1" 200 5668 -
filtering an queryset in an Inline object in Django Admin
The contest is an inventory app of an e-commerce project. As expected, there's a Product model. In an attempt to normalize the DB schema, I have created these additional models: ProductType (ForeignKey relationship in Product) ProductSpecification (a FK in ProductType) ProductInventory (with a FK to Product) ProductSpecificationValue (FK to both ProductSpecification and ProductInventory) I hope this makes sense - each ProductType has many Products, and also many Specifications. ProductInventory (suggestions of a better name are welcome), with a FK to product, is a model with SKU and quantity fields. And the fun part - it has a ManyToMany relationship to ProductSpecification, through ProductSpecificationValue. Now the part where I am lost is adding this whole thing to Django Admin site. I can create ProductTypes and Products without any problem, and a ProductTypeAdmin has an inline to add those specs:. @ admin.register(ProductType) class ProductTypeAdmin(admin.ModelAdmin): inlines = [ ProductSpecificationInline, ] The problem starts when I try to add a ProductInventory entity. Because it's associated with a given ProductType, I want to limit the choice of inlines to only those which are related to the same ProductType. class ProductSpecificationValueInline(admin.TabularInline): model = ProductSpecificationValue def get_formset(self, request, obj=None, **kwargs): # obj is always the current Product … -
How to retrieve all Variants of a single Product in a single JSON object per Product- Django Rest Framework
The way I am doing it is like in getProductList function in my views.py and it is giving me each product with its variants in different objects like so: JSON: [ { "prod_id": { "id": 3, "prod_name": "CRUISER-149S-DEERCALF", "category": 2 }, "size_id": { "id": 2, "name": "26" }, "color_id": 2, "image_id": { "id": 10, "prod_image": "/media/products/IMG_7617_ftgqoa.jpg" } }, { "prod_id": { "id": 3, "prod_name": "CRUISER-149S-DEERCALF", "category": 2 }, "size_id": { "id": 3, "name": "27" }, "color_id": 2, "image_id": { "id": 10, "prod_image": "/media/products/IMG_7617_ftgqoa.jpg" } } ] Is there a way to maybe make it more optimized? like have only one object that has all the info of a single product like size for example can be a property with values of all sizes in it like size: [26, 27] instead of a different object if a size is different. models.py class Products(models.Model): prod_name = models.CharField(max_length=200) category = models.ForeignKey(Categories,null=True, on_delete=models.SET_NULL) def __str__(self): return '%s'%(self.prod_name) class Variants(models.Model): prod_id = models.ForeignKey(Products, on_delete=models.CASCADE) size_id = models.ForeignKey(Size, null=True, on_delete=models.SET_NULL, related_name='variants') color_id = models.ForeignKey(Color, null=True, on_delete=models.SET_NULL, default='') image_id = models.ForeignKey(Image,null=True, on_delete=models.SET_NULL, default='') def __str__(self): return '%s %s %s %s %s %s %s'%(self.id , self.prod_id, self.size_id, self.image_id, self.color_id, self.quantity, self.price) serializer.py class ProductsSerializer(serializers.ModelSerializer): # variants = serializers.StringRelatedField(many=True) …