Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
dj-rest-auth registration fetch
Using dj-rest-auth for user auth and registration on my react app. Got login and logout to work using api endpoints in the docs. Failing to register a user, getting HTTP bad request 400. Reading on the web, explains that there's something wrong with my request but cannot figure what: register.js fetch('/api/dj-rest-auth/registration/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user: 'alalala', password1: '1234', password2: '1234', email: 'ala@gmail.com', }) }) .then(res => { res.json() }) settings.py SITE_ID = 1 CORS_ORIGIN_ALLOW_ALL = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'api.serializers.CustomRegisterSerializer' } INSTALLED_APPS = [ #local 'api', # 3'rd party apps 'rest_framework', 'corsheaders', 'rest_framework.authtoken', 'dj_rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', # added django but it disable admin login logout pages 'django.contrib.sites', # django default... ] serializer.py class CustomRegisterSerializer(RegisterSerializer): def get_cleaned_data(self): super(CustomRegisterSerializer, self).get_cleaned_data() return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'password2': self.validated_data.get('password2', ''), 'email': self.validated_data.get('email', ''), } -
Django registration different type users with different fields
I need to create two different users: Gym and Client. The client should theoretically be connected by a many-to-many bond because he can be enrolled in multiple gyms. My doubt is about user registration. I found this around: class User(AbstractUser): is_gym = models.BooleanField(default=False) is_client = models.BooleanField(default=False) class Gym(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user.is_gym = True class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) gyms = models.ManyToManyField(Gym, related_name='clients') user.is_client = True @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.is_gym: Gym.objects.create(user=instance) elif instance.is_client: Client.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): if instance.is_gym: instance.gym.save() elif instance.is_client: instance.client.save() My doubts are two: If I wanted to register users with a button "I am a gym" or "I am a customer" with this code, theoretically I could not do it because User class differs, the gym does not have a surname for example. With this code I should create the Gym and Client class populated at a later time so I should make a second form after verifying the account. -
how do I solved a super(type, obj): obj must be an instance or subtype of type type error?
I'm trying to run a test on my app's index.html and here I have: test.py class IndexTest(TestCase): def setUp(self): url = reverse ('index') self.response = self.client_class.get(self, url) and I get this traceback error Traceback (most recent call last) ... File "...\django\test\client.py", line 836, in get response = super().get(path, data=data, secure=secure, **extra) TypeError: super(type, obj), obj must be an instance or a subtype of type I don't know how to go about this -
Filter Field In Object Where Field Has Many Choices
How can I show a list in object.filter()? When I load the page I'm only getting the queryset2 print to show a post. Which makes sense. but why does the queryset and queryset1 not show the posts with these categories? models.py class Post(models.Model): ANALYSIS = "Analysis" MILESTONE = "Milestone" FEATURES = "Features" TUTORIALS = "Tutorials" CAREERS = "Careers" COMMUNITY = "Community" CATEGORY_CHOICES = [ (ANALYSIS, 'Analysis'), (MILESTONE, "Milestone"), (FEATURES, "Features"), (TUTORIALS, "Tutorials"), (CAREERS, "Careers"), (COMMUNITY, "Community"), ] user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=125) body = RichTextUploadingField(blank=True, null=True) category = models.CharField( max_length=20, choices=CATEGORY_CHOICES, default="watchlist" ) views.py class BlogFilterView(LoginRequiredMixin, FilterListViewDate): model = Post filterset_class = PostFilter template_name = "dashboard/blog_filter.html" paginate_by = 5 def get_queryset(self): # categories = ["ANALYSIS", "MILESTONE", "FEATURES", "TUTORIALS", "CAREERS", "COMMUNITY",] categories = ["Analysis", "Milestone", "Features", "Tutorials", "Careers", "Community",] queryset = Post.objects.filter(category__icontains=categories) print("queryset =", queryset) queryset1 = Post.objects.filter(category__icontains="Analysis").filter(category__icontains="Milestone") \ .filter(category__icontains="Features").filter(category__icontains="Tutorials") \ .filter(category__icontains="Careers").filter(category__icontains="Community") print("queryset1 =", queryset1) queryset2 = Post.objects.filter(category__icontains="Community") print("queryset2 =", queryset2) return queryset -
Limit choices to m2m field of a foreign_key
I have these models class SubjectTeacher(models.Model): teacher = models.ForeignKey(TeacherProfile, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) SEMESTER_CHOICES = [("1st", "First Quarter"), ("2nd", 'Second Quarter'), ('3rd', 'Third Quarter'), ('4th', 'Fourth Quarter')] semester = models.CharField(choices = SEMESTER_CHOICES, default = "1st", max_length=3) students = models.ManyToManyField(StudentProfile, related_name="subjects") def __str__(self): return f'{self.subject.subject_name} | {self.teacher.user.first_name}' class Meta: constraints = [ UniqueConstraint(fields = ["teacher", "subject"], name = "Unique Subject Teacher") ] class StudentGrade(models.Model): subject_teacher = models.ForeignKey("SubjectTeacher", on_delete=models.CASCADE) student = models.ForeignKey('StudentProfile', on_delete=models.CASCADE) grade = models.IntegerField() now I want StudentGrade.student to be based on what is selected (in django-admin) on the StudentGrade.subject_teacher Example: subject_teacher = <subject1> <subject2> selected: <subject1> student = choices from <subject1>.students I already tried looking on similar cases such as editing the ModelForm but I couldn't get the gist of it. -
how to select a specific part of a string Django?
I have strings in the database that are the names of countries and cities for example like this: Italy-Milan OR France-Paris. How can i select only the city part, like select what comes only after the '-' using python? -
Steps to perform after updating nginx config - Django
I run a django+nginx+wsgi app in Ec2. App was working fine until I changed server_name in nginx.conf since I had to stop and start Ec2. After updating the server_name, app was broken I tried symlinking sites-available and sites-enabled I restarted nginx, gunicorn process and supervisord I deleted the app.sock file and recreated it using commands But Stil app is broken Here are my files django.conf(/etc/nginx/sites-available/django.conf) server { listen 80; server_name <public_ip>; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/degrep-v2-base/app.sock; }} gunicorn.conf(/etc/supervisor/conf.d/gunicorn.conf) [program:gunicorn] directory=/home/ubuntu/degrep-v2-base command=/home/ubuntu/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/degrep-v2-base/app.sock degrep_v2.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn If im updating nginx.conf in future, what all steps I need to perform for no downtime? -
How to aggregate the sum of a class model field in django
I've been attempting unsuccessfully to show the total_net_profit on my dashboard. I think there is a problem with my strategy. Does anyone have a solution to this issue? Model class Investment(models.Model): PLAN_CHOICES = ( ("Basic - Daily 2% for 182 Days", "Basic - Daily 2% for 182 Days"), ("Premium - Daily 4% for 365 Days", "Premium - Daily 4% for 365 Days"), ) plan = models.CharField(max_length=100, choices=PLAN_CHOICES, null=True) principal_amount = models.IntegerField(default=0, null=True) investment_id = models.CharField(max_length=10, null=True, blank=True) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=True, null=True) due_date = models.DateTimeField(null=True, blank=True) def daily_interest(self): if self.plan == "Basic - Daily 2% for 182 Days": return self.principal_amount * 365 * 0.02/2/182 else: return self.principal_amount * 365 * 0.04/365 def net_interest(self): if self.plan == "Basic - Daily 2% for 182 Days": return self.principal_amount * 365 * 0.02/2 else: return self.principal_amount * 365 * 0.04 def total_net_profit(self): return self.Investment.aggregate(total_net_interest=Sum('net_interest'))['total_net_interest'] -
How to unittest AWS Stack (coming from Django)?
I am coming from Django stack and now I am on AWS and I have problem with testing my code which use a lot of AWS Stack. With Django, when you run a test, a temporary database is created and migration applied. How to do that when testing the unnittest I am writing for AWS ? Is there any way to simulate the behaviour of AWS component like SQS, Lambda invoke, etc. I am coming in the Django world and you could test everything you want without problem but now it seems like very complicated. Thanks for you help -
Django - form object has no attribute 'status_code'
I am new to Django and working on forms. I got this error message File "C:\Users\foo\what\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\foo\what\lib\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "C:\Users\foo\what\lib\site-packages\django\middleware\common.py", line 108, in process_response if response.status_code == 404 and self.should_redirect_with_slash(request): AttributeError: 'Product' object has no attribute 'status_code' models.py class Product(models.Model): product_name = models.CharField(max_length=100) product_price = models.IntegerField() product_photo = models.ImageField(upload_to='product_photos', height_field=None, width_field=None, max_length=100) def get(self, request): a = Product() return a forms.py class UploadProduct(ModelForm): product_name = forms.TextInput() product_price = forms.NumberInput() product_photo = forms.FileInput() class Meta: model = Product fields = ['product_name', 'product_price', 'product_photo'] views.py def uploadProduct(request): if request.POST: form = UploadProduct(request.POST) if form.is_valid(): form.save() return redirect(upload_product_ok_page) return render(request, 'upload_product.html', {'form': UploadProduct}) def upload_product_ok_page(request): return HttpResponse('ok') urls.py path('upload_product/', Product), path('upload_product/', views.uploadProduct, name="upload_product"), path('', views.upload_product_ok_page, name='upload_product_ok_page'), upload_product.html <form method="POST" action="{% url 'upload_product' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button>Submit</button> </form> I made sure I imported the correct functions, classes and objects. Thanks in advance. -
How to set up Django i18n on Google App Engine (GAE)?
Using Django 4.0.2, and GAE standard, the site text does not change when a language is selected. The main language is english. The second language is Dutch. If I switch the language, then the url changes and includes /nl instead of en/, but the English text remains. On localhost, the English text is replaced with the Dutch text. I'm using django-rosetta and on GAE its dashboard finds two instances of my application, called workspace/ and srv/. Each contains the same .mo file in the same location /workspace/locale/nl/LC_MESSAGES/django.po. I dont know why there are two applications, or if this is relevant. On localhost, I have one application in the expected location. There are no errors, and checking the existence of the .mo file returns True. My locale directory is in the project root. On local this is my project name, on GAE the name of the project root directory is workspace. This should be fine because building file paths using ROOT_DIR still works as expected for locale settings and also all other settings. The relevant settings are: ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent _locale_dir = ROOT_DIR / "locale" _locale_file = _locale_dir / "nl/LC_MESSAGES/django.po" print(f"--- {_locale_file.is_file() = }") LOCALE_PATHS = [ROOT_DIR / "locale", "/workspace/locale", "/srv/locale"] … -
Django form refused to validate because of Select widget
I have a Django form that refused to validate because of this Select widget, I have tried to debug and found out that the particular form field has been returning None instead of 'Buy' or 'Sell'. I can't seem to figure out what's wrong with my code, albeit I suspect it has something to do with my HTML. models.py class Transaction(models.Model): buy = 'BUY' sell = 'SELL' transaction_choices = [ (buy, 'Buy'), (sell, 'Sell'), ] transaction_type = models.CharField( max_length=4, choices=transaction_choices, default=buy, ) forms.py class UpdatePortfolio(forms.ModelForm): transaction_choices = [ ('BUY', 'Buy'), ('SELL', 'Sell'), ] transaction_type = forms.CharField( max_length=4, widget=forms.Select( choices=transaction_choices, attrs={ 'class': 'form-select', 'name': 'transaction_type', 'id': 'floatingTransaction', }) ) class Meta: model = Transaction fields = ( 'transaction_date', 'symbol', 'transaction_date', 'share', 'avg_price', 'cost_basis', ) def clean_transaction_type(self): type = self.cleaned_data.get('transaction_type') if type != 'Buy' or 'Sell': raise forms.ValidationError(f'{type} is an invalid transaction') return type updateportfolio.html <form action="{% url 'mainpage:update' user.id %}" method="POST"> {% csrf_token %} <div class="row1"> <div class="transaction_type col-6"> <p>Transaction Type</p> <select class="form-select" required> {% for type in form.transaction_type %} <option>{{ type }}</option> {% endfor %} </select> </div> <div class="symbol col-6"> <label for="floatingSymbol" class="form-label">Ticker</label> {{ form.symbol }} <datalist id="tickers"> {% for ticker in tickers %} <option value="{{ ticker.tickersymbol }}"></option> {% endfor … -
I'm not getting any option to select product list in order form
Models.py from django.db import models from re import I from django.utils import timezone from django.dispatch import receiver from more_itertools import quantify from django.db.models import Sum # Create your models here. CHOICES = ( ("1", "Available"), ("2", "Not Available") ) class Brand(models.Model): name = models.CharField(max_length=255) status = models.CharField(max_length=10, choices=CHOICES) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=255) status = models.CharField(max_length=10, choices=CHOICES) def __str__(self): return self.name class Product(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=255) code = models.CharField(max_length=10) #image = models.ImageField(upload_to="media/product/images/") quantity = models.IntegerField() rate = models.FloatField(max_length=100) status = models.CharField(max_length=10, choices=CHOICES) def __str__(self): return self.name class Order(models.Model): date = models.DateTimeField(auto_now_add=True) sub_total = models.FloatField(max_length=100) vat = models.FloatField(max_length=100) total_amount = models.FloatField(max_length=100) discount = models.FloatField(max_length=100) grand_total = models.FloatField(max_length=100) paid = models.FloatField(max_length=100) due = models.FloatField(max_length=100) payment_type = models.CharField(max_length=100) payment_status = models.IntegerField() status = models.IntegerField() class OrderItem(models.Model): order_id = models.ForeignKey(Order, on_delete=models.CASCADE) product_id = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() rate = models.FloatField(max_length=100) total = models.FloatField(max_length=100) status = models.IntegerField() views.py from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponse, JsonResponse from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.template.loader import render_to_string from django.views.decorators.csrf import csrf_exempt import json from .models import Brand, Category, Product, … -
How to solve the djongo.exceptions.SQLDecodeError: while trying to run the migrate command
I am creating a DjangoRestful app that uses SimpleJWT for authentication. When I try to add the Blacklist app and make migrations. i.e: py manage.py migrate as suggested in the documentation, I get the error below: Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, main, sessions, token_blacklist Running migrations: Applying token_blacklist.0008_migrate_to_bigautofield...Not implemented alter command for SQL ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long Traceback (most recent call last): File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__ self._query = self.parse() File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 876, in parse raise e File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 889, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 425, in __init__ super().__init__(*args) File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 84, in __init__ super().__init__(*args) File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 441, in parse self._alter(statement) File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long',) Params: ([],) Version: 1.3.6 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\backends\utils.py", line 85, in _execute … -
Combining two different querysets with conditions
I have two different models: class Material(models.Model): line = models.ForeignKey('Line') code = models.ForeignKey('Code') quantity = models.FloatField() class Inventory(models.Model): code = models.ForeignKey('Code') .... I'm trying to get a sum of quantity field for each row in Inventory, and also trying to append the related line fields with it. This is what I have: line = Material.objects.all().values('code','line__line_id').annotate(Sum('quantity')) # This gives me the SUM of quantity as required, output: # <QuerySet [{'code': 'abc', 'line__line_id': 134, 'quantity__sum': 15.0}, # {'code': 'abcd', 'line__line_id': 134, 'quantity__sum': 5.0}]> query_set = Inventory.objects.all().annotate(line=Value(F('line__line__line_id'), output_field=CharField())).order_by('code') filter = self.filterset_class(self.request.GET, query_set) In the query_set, I am getting this line annotation as a literal string "F('line__line__line_id')". How can I make it so query_set has values filtered as: WHERE Inventory.code == Material.code? Basically I want to combine the first queryset with the second one, where the code is the same in both querysets. I do not want to use chain() method as I need it to be a QuerySet object so I can use the FilterSet() from django-filters. -
add tax value 0.17 to database when checkbox checked
I'm working on customer form, I just want that if checked box is checked add 0.17 to database field named tax <input type="checkbox" id="tax" name="tax"> <label for="tax">Included Tax</label> view.py if form.is_valid(): form.save() -
Getting "Uncaught (in promise) TypeError: Failed to fetch" in local server (ReactJS)
Description: I have a ReactJS website which I'm currently working on. There's a LoginPage in which I'm sending a POST request with Axios to the backend (Django). I have set CORS_ALLOW_ALL_ORIGINS = True and website works just fine on the computer with no error or warning logs. Problem: When I try to test it on a android phone in the same network (I use vite and I've set everything for allowing connections through local network) I get "Uncaught (in promise) TypeError: Failed to fetch" error. It was a pain in the a$$ to actually see what was the console log in android but by using some third party apps I managed to find out that was the eror log. Expected result: As I set CORS to be allowed from any host and both backend and frontend servers are running and allowing local network connections there shouldn't be such error. Technologies used: ReactJS 17.0.2, Vite 2.9.9, React router dom 6.3.0, Django 4.0.6. Code snippets: LoginPage.jsx import * as React from "react"; import Avatar from "@mui/material/Avatar"; import Button from "@mui/material/Button"; import CssBaseline from "@mui/material/CssBaseline"; import TextField from "@mui/material/TextField"; import FormControlLabel from "@mui/material/FormControlLabel"; import Checkbox from "@mui/material/Checkbox"; import Link from "@mui/material/Link"; import Grid … -
How to know a value for field already exists and it was deleted?
How can we know that a value in field already exists however it does not exists in the table right now?(because we delete the field) e.g. We have a table that has field with name "title". we had value "x" in this "title" field and right now it does not exists and we deleted the value "x" value. So my question is, how can we know that? -
Django-Oscar - Modelling product classes with 2 main attributes each having different sub-attributes
I am working on an online store for a jewellery brand using Django-Oscar. We have 6 product types (Rings, Earrings etc.), each of which has been defined as a Product Class. All of these product classes have 2 common attribute types (Metal Type and Primary Gemstone Type) each of which take a collection of values. Depending on the values they take (eg. Diamond, Ruby etc. for Gemstone Type), they have different sub-attributes (eg. Carat, Clarity, Origin etc. for Diamond). Also, there are attributes (such as Dimensions, Weight etc.) which are common to all product classes. To model these attributes, I am thinking of customising the Django-Oscar framework as follows: Alter the AbstractProduct model to include two fields: metal and primary-gemstone such that every product instance has these two fields To vary attributes depending on the selection for metal and primary-gemstone, create two models Metal and Gemstone comprising of the possible types of metals and gemstones as fields Create a MetalAttribute model and a GemstoneAttribute model with metal, gemstone (PK from Metal and Gemstone models) and attribute-name (eg., for Diamond gemstone type, attribute names could be carat, cut etc.) fields For the possible values of each attribute for each metal/ gemstone, … -
Django data transfer from MySQL To PostgreSQL loaddata command error
When I am run the command for load data from old database of mysql to new database of postgresql get below error how to solve this? Traceback (most recent call last): File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\serializers\json.py", line 69, in Deserializer objects = json.loads(stream_or_string) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json_init_.py", line 346, in loads return _default_decoder.decode(s) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilan\manage.py", line 22, in main() File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilan\manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management_init_.py", line 425, in execute_from_command_line utility.execute() File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management_init_.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management\base.py", line 417, in execute output = self.handle(*args, **options) File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management\commands\loaddata.py", line 78, in handle self.loaddata(fixture_labels) File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management\commands\loaddata.py", line 138, in loaddata self.load_label(fixture_label) File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management\commands\loaddata.py", line 214, in load_label for obj in objects: File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\serializers\json.py", line 74, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError: Problem installing fixture 'E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilan\alldata.json': -
How to show only objects those are not selected in Django admin panel referred by Foreign Key?
I have following models : class Article(models.Model): title = models.CharField(max_length=150, null=True, blank=True) class Product(models.Model): name = models.CharField(max_length=150, null=True, blank=True) class ArticleProduct(models.Model): class Meta: unique_together = ('article', 'product') article = models.ForeignKey(Article, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) In admin.py : class ArticleProductIngredientInline(admin.StackedInline): model = ArticleProduct autocomplete_fields = ['product'] extra = 0 class ArticleAdmin(admin.ModelAdmin): inlines = [ArticleProductIngredientInline] search_fields = ['category', ] class Meta: model = Article @admin.register(ArticleProduct) class ArticleProductAdminModel(admin.ModelAdmin): autocomplete_fields = ['product', 'article'] class ProductAdminModel(admin.ModelAdmin): search_fields = ['product', ] admin.site.register(Product, ProductAdminModel) admin.site.register(Article, ArticleAdmin) I want that, In particular article when I add some product, it should not show again in while adding second product. Is there any way to it ? -
Cannot iterate zipped list in csv writerow()
I tried to generate csv file from zipped list consists of 1 Object and 3 int lists items = zip(object, list1, list2, list3) I looped the zipped list as follows but when I tried download the csv, there are no data: for object, list1, list2, list3 in items: writer.writerow([object.name, object.department, object.section, list1, list2, list3]) I checked if the data cannot be read or missing by using the segment code below, however it can properly print all the data: for object, list1, list2, list3 in items: print(str(object.name) + ": " + str(list1) + "/" + str(list2) + "/" + str(list3)) I'm not sure where's the part went wrong here as it doesn't print any error message. -
How to include CSRF token in the HTTP header of a GraphQL query with aiohttp and Django?
I'm trying to perform GraphQL mutation between two 2 Django projects, one has the gql client using aiohttp transport, and the other has the graphene server. The mutation works fine when django.middleware.csrf.CsrfViewMiddleware is deactivated, but when it is enabled the server throws an error Forbidden (CSRF cookie not set.): /graphql. At the client side, how can I fetch a CSRF token from the server and include it in the HTTP header ? Client side # Select your transport with a defined url endpoint transport = AIOHTTPTransport(url="http://5.22.220.233:8000/graphql", headers={"Authorization": "CSRF_TOKEN_HERE"} ) # Create a GraphQL client using the defined transport client = Client(transport=transport, fetch_schema_from_transport=True) # Provide a GraphQL query query = gql( """ mutation ... """) -
How to give images to right of the the html Table
I have made a Django website and want to display my result like at the top there is a small form.Under that in the left there is a table and i want to add to images and another column in the right if the table. I have made a design to explain better - enter image description here Now I have written the code for the form 1 and table. I will write the backend code too .I want to know how will I write html for the images and form 2 as they are in right of the table.As soon as write any html code it comes under the table. Anyone can help to add pics and form2 on the right of the table. my html code till now is- *{% extends 'login/basic.html' %} {% block title %}Approval of count{% endblock title %} {% block body %} <!-- <div class="container my-5 px-2"> --> <form action="/approval" method="post">{% csrf_token %} <!-- <div class="container" > <div class="form-group mx-5 my-3"> <div class="form-group mx-5 my-3"> <label class="my-3" for="date">Date</label> <input type="date" id="date" name="date"> </div> <label class="form-group mx-5 my-3" for="servers">Choose the server from - {{serverLst}}</label> <div class="form-group mx-5 my-3"> <select name="serverName" id="forserver" size="4" multiple> {% for … -
django media audio currentTime reseting to 0
I'm trying to make a audiobook website with django(3.2.13). But when I try to go back and forth. The currentTime of the audio goes back to 0. I have tryed it in side of console too. It's weird because when the audio file is small it work's!(When I refesh) But if the file is Big It doesn't work. All of the audios are work's good if I don't change the currentTime of the audio. What could be the problem? #djangotemplate <audio class="playing-audio" src="{{ audio.audios.url }}"></audio> #views.py class AudioDetailView(DetailView): model = Audio template_name = "audios/audio_detail.html" pk_url_kwarg = "audio_id" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) audio_id = self.kwargs.get("audio_id") audio = Audio.objects.get(id=audio_id) context["img_url"] = f"/static/img/{audio.category.title}.png" return context