Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - get data from db and update him - how to take the last data and update, i get the data with CartOrder.objects.last()
i want that the paid status will be true on the last order i can filter the data but how i am changing him ? my views.py file: def payment_done(request): a = CartOrder.objects.last() orders = CartOrder.objects.filter(paid_status=a.paid_status) return render(request, 'payment-success.html',{'orders':orders}) my models.py file: class CartOrder(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) total_amt = models.FloatField() paid_status = models.BooleanField(default=False) order_dt = models.DateTimeField(auto_now_add=True) -
Best practices of choice sort in django
I believe everyone knows Counter Strike Global Offensive (CS:GO). So there we have weapons divided by types (Pistol, SMG, Rifle, Heavy). Each type has several weapons (e.g. AK-47, M4A4, AWP are Rifle-type weapons. I have the following model in my Django project: class Weapon(models.Model): WEAPONS = ( ('AK-47', 'AK-47'), ('M4A4', 'M4A4'), ... ) QUALITY_CONSUMER_GRADE = 'CONSUMER GRADE' QUALITY_INDUSTRIAL_GRADE = 'INDUSTRIAL GRADE' QUALITY_MIL_SPEC = 'MIL-SPEC' QUALITY_RESTRICTED = 'RESTRICTED' QUALITY_CLASSIFIED = 'CLASSIFIED' QUALITY_COVERT = 'COVERT' QUALITY = ( (QUALITY_CONSUMER_GRADE, 'Consumer grade'), (QUALITY_INDUSTRIAL_GRADE, 'Industrial grade'), (QUALITY_MIL_SPEC, 'Mil-spec'), (QUALITY_RESTRICTED, 'Restricted'), (QUALITY_CLASSIFIED, 'Classified'), (QUALITY_COVERT, 'Covert') ) CATEGORY_NORMAL = 'NORMAL' CATEGORY_STATTRAK = 'STATTRAK' CATEGORY = ( (CATEGORY_NORMAL, 'Normal'), (CATEGORY_STATTRAK, 'StatTrak') ) TYPE_PISTOL = 'PISTOL' TYPE_HEAVY = 'HEAVY' TYPE_SMG = 'SMG' TYPE_RIFLE = 'RIFLE' TYPE = ( (TYPE_PISTOL, 'Pistol'), (TYPE_HEAVY, 'Heavy'), (TYPE_SMG, 'SMG'), (TYPE_RIFLE, 'Rifle') ) EXTERIOR_FACTORY_NEW = 'FACTORY NEW' EXTERIOR_MINIMAL_WEAR = 'MINIMAL WEAR' EXTERIOR_FIELD_TESTED = 'FIELD-TESTED' EXTERIOR_WELL_WORN = 'WELL-WORN' EXTERIOR_BATTLE_SCARRED = 'BATTLE-SCARRED' EXTERIOR = ( (EXTERIOR_FACTORY_NEW, 'Factory New'), (EXTERIOR_MINIMAL_WEAR, 'Minimal Wear'), (EXTERIOR_FIELD_TESTED, 'Field-Tested'), (EXTERIOR_WELL_WORN, 'Well-Worn'), (EXTERIOR_BATTLE_SCARRED, 'Battle-Scarred') ) name = models.CharField(max_length=64, choices=WEAPONS, default=WEAPONS[0][0]) exterior = models.CharField(max_length=64, choices=EXTERIOR, default=EXTERIOR[0][0]) quality = models.CharField(max_length=64, choices=QUALITY, default=QUALITY[0][0]) category = models.CharField(max_length=64, choices=CATEGORY, default=CATEGORY[0][0]) type = models.CharField(max_length=64, choices=TYPE, default=TYPE[0][0]) price = models.FloatField() slug = models.SlugField(max_length=256, unique=True, editable=False) What is the best practice … -
Group_by in django with a Foreign key field
I've these model: class Student(models.Model): name = models.CharField(max_length=255) school = models.CharField(max_length=255) class Question(models.Model): question_text = models.CharField(max_length=255) correct_count = models.Integer_Field() incorrect_count = models.Integer_Field() class Answer(models.Model): question = models.ForeignKey(Question, related_name='answer_question', on_deleted=models.CASCADE) text = models.CharField(max_length=255) is_correct = models.BooleanField() class Quiz(models.Model): name = models.CharField(max_length=255) month = models.DateField() class QuizQuestion(models.Model): quiz = models.ForeignKey(Quiz, related_name='quiz_question_quiz', on_deleted=models.CASCADE) questions = models.ManyToManyField(Question, related_name='quiz_student') class QuizAnswer(models.Model): student = models.ForeignKey(Student, related_name='quiz_answer_student', on_deleted=models.CASCADE) question = models.ForeignKey(Question, related_name='quiz_answer_question', on_deleted=models.CASCADE) answer = models.ForeignKey(Answer, related_name='quiz_answer_answer', on_deleted=models.CASCADE) quiz = models.ForeignKey(Quiz, related_name='quiz_answer_student', on_deleted=models.CASCADE) marks = models.IntegerField() It's related to a contest in which students from different schools participate. Quiz contest will have multiple choice questions and student selects one answer which gets stored in our QuizAnswer table with question id, answer id, user id, quiz id and if the answer is correct our Question model's correct_count gets incremented otherwise incorrect count get incremented. Now I want to get top 5 schools whose students gave most correct answers with their percentage in descending order. How can I write a query for this? -
Default image didn't change Django
I try to make avatar upload in Django project. I made changes in templates and in models, but the default image does not change to a new one. What could be the problem? model.py class Person(models.Model): avatar = models.ImageField(upload_to="img", null=True, blank=True) template.html {% if person.avatar.url %} <th scope="row"><img height="50" width="50" src="{{ person.avatar.url }}" alt="no image" title="avatar"> {% else %} <th scope="row"><img height="50" width="50" src="{% static "img/default_avatar.jpg" %}" alt="no image" title="avatar"> {% endif %} -
Django Migration MySql to Postgres - IntegrityError
I am trying to migrate a fairly big Django project from using MySql to using Postgres. I am doing that locally for now and I was following the instructions of this guide here I found on the web. After installing the psycopg library correctly I can't execute the existing migrations over the new postgres Database because I get integrity errors. The error would look like this: django.db.utils.IntegrityError: Problem installing fixture '/home/user/project/venv/lib/python3.6/site-packages/allsports/core/fixtures/competitiontype.json': Could not load core.CompetitionType(pk=None): (1062, "Duplicate entry 'season' for key 'name'") and it is thrown when The python manage.py migrate command reaches the first migration that loads some data with the loaddata command from a file that looks like this: [ {"model": "core.competitiongrouptype", "pk": null, "fields": {"name": "conference"}}, {"model": "core.competitiongrouptype", "pk": null, "fields": {"name": "division"}}, {"model": "core.competitiongrouptype", "pk": null, "fields": {"name": "playoff series"}} ] I wanted to know if anybody had this error and whether it is because Postgres manages keys differently. If so any Idea on how to migrate the data from Mysql to Postgres? -
In django-taggit tag is not save along with question post
when I created djanog question models all the fields are created but tag is not created with question model but separately tags are created in django admin taggit model.py class Question(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True,editable=False) nameuser = models.ForeignKey(Profile,on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = RichTextUploadingField() tag = TaggableManager() def __str__(self): return self.content class Meta: ordering = ['-timestamp'] view.py def createQue(request): User = request.user.profile form=QuestionForm() if request.method =='POST': form=QuestionForm(request.POST,request.FILES) if form.is_valid(): content = form.cleaned_data["content"] tag = form.cleaned_data["tag"] print(tag) blog = form.save(commit=False) blog.nameuser=User blog.content = content blog.tag=tag blog.save() return redirect('home') context={'form':form} return render(request,'blog_form.html',context) forms.py class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ['content','tag'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['content'].widget.attrs.update({'class':'form-control ','placeholder':'Enter your question'}) self.fields['tag'].widget.attrs.update({'class':'tag_inputbar','placeholder':'Enter Tags here'}) -
Change schema on views using Django Tenants
I'm using Django Tenants on my project and I'm creating a schema for each Tenant. I have 'django.contrib.auth' and 'django.contrib.contenttypes' both in SHARED_APPS and in TENANT_APPS, and now I want to create specific groups in each tenant schema. The problem is that I'm always reading and writing values from the public schema. I implemented the following: DATABASES = { 'default': { 'ENGINE': 'django_tenants.postgresql_backend', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASS', 'HOST': 'DB_HOST', 'PORT': 'DB_PORT', } } DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) How can I change to a different schema? Can I do it on an app views? -
Django Rest Framework: How to request data validate before serializers?
I'want to validated email variable before UserSerializer,then return filter data, the following code is work , but I declared twice serializer , If I want use once serializer, how can I do ? views.py @api_view(['GET']) def get_user(request): email = request.data.get('email') serializer = UserSerializer(data=request.data) if serializer.is_valid(): Users = User.objects.filter(email=email) serializer = UserSerializer(Users, many= True) return Response({"status": "success", "data": serializer.data}) else: return Response({"status": "errors", "data": serializer.errors}) serializers.py class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) phone = serializers.CharField(required=False) sex = ChoiceField(required=False, choices=User.TYPE_CHOICES) class Meta: model = User fields = ('id', 'email', 'phone', 'name','sex', 'updated', 'created') models.py class User(models.Model): TYPE_CHOICES = ( ('0', 'men'), ('1', 'girl'), ('2', 'nobody'), ) email = models.EmailField(unique=True, max_length=50) phone = models.TextField(unique=True, max_length=11) name = models.TextField(default="AKA") sex = models.CharField( max_length=2, choices=TYPE_CHOICES, default="0" ) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: db_table = "users" -
VSCode autocomplete for Django orm lookups/property not working
How to autocomplete django orm property or lookups in VSCode? Just like it works in Pycharm Professional Edition as follow: -
fromisoformat: argument must be str
I have this date that formatted like this 2022-08-25 17:59:46.95300. messageDate = value['MessageDate'] //2022-08-25 17:59:46.95300// newDate = datetime.strptime(messageDate, '%Y-%m-%d %H:%M:%S.%f' saverecord.created_at = newDate When I run the function, I'm having this error in parse_date return datetime.date.fromisoformat(value) TypeError: fromisoformat: argument must be str -
django mod_wsgi and apache: module not found error
I am trying to move my django project to production using apache2 and mod_wsgi. I keep getting a wsgi_error "ModuleNotFoundError" in the apache logs. I run on ubuntu 22.04. After going through the various posts on the web I still am not getting anywhere, so I have now started from scratch by creating a new example django app. The same error occurs. PS, When I use "runserver" the django app displays fine in the browser. Also a simple wsgi "hello_world" app runs fine in apache. So I think the basic setup is fine. I have created a django test application "mytest" with django-admin startproject mytest The project is created in /home/user/myprojects/mytest, the group of all directories is www-data In mytest I have the usual django structure home/user/myprojects/mytest manage.py mytest asgi.py __init__.py settings.py urls.py wsgi.py The wsgi.py is: (The django/python runs in a virtual environment I found that I needed to add code to the wsgi to actually activate the virtual environment) """ WSGI config for mytest project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/ """ python_home='/home/user/.virtualenvs/myproject' activate_this= python_home + '/bin/activate_this.py' with open(activate_this)as f: code=compile(f.read(),activate_this,'exec') exec(code, dict(__file__=activate_this)) import os … -
Django - If statement with request.user
I have a problem with an if-statement. I just want to check on a page if the user who requests the listing page is the same one as the user who won the listing on that page. My view looks like this: def show_closed_listing(request, listing_id): closed_listing = InactiveListing.objects.get(id=listing_id) field_name = "winning_user" winning_user = getattr(closed_listing,field_name) message = False print(request.user) print(winning_user) if request.user == winning_user: print("This is good") message = "You have won this listing!" else: print("Not good") return render(request, "auctions/closed_listing.html", { "closed_listing" : closed_listing, "message" : message }) When I visit a page, signed in as Test2, when Test2 has won the listing, my terminal shows as follows: Test2 Test2 Not good As also can be seen here I don't get why request.user and winning_user look the same, but the if-statement is false? If needed, here is my model: class InactiveListing(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=512, default="") winning_user = models.CharField(max_length=128) winning_price = models.DecimalField(max_digits=6, decimal_places=2, default=0.01) def __str__(self): return self.title -
django.db.utils.OperationalError: no such column: authentication_user.name
I was trying to add a new field to my User authentication model. But whenever I'm trying to run python manage.py makemigrations, the console is showing, django.db.utils.OperationalError: no such column: authentication_user.name Here is a part of my Model: class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, max_length=36, default=uuid.uuid4, editable=False,blank=False, null=False) cus_id = models.CharField(max_length = 250, null=True, blank=True, default=increment_cus_number) email = models.EmailField(max_length=255, unique=True, db_index=True) username = models.CharField(max_length=250, blank = True, null = True) name = models.CharField(max_length=250, default = '', blank = True, null = True) first_name = models.CharField(max_length=250, blank=True, null=True) last_name = models.CharField(max_length=250, blank=True, null=True) mobile = models.CharField(max_length = 100, null = True) date_of_birth = models.DateField(blank=True, null=True) address = models.TextField(blank=True, null=True) picture = models.ImageField(blank=True, null=True) gender = models.CharField(max_length=100, blank = True, null= True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) business_partner = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email any suggestions/tips regarding this issue would be a great help. -
for loop in django template input is only fetching the last one
I have a for loop in django templates and each iteration must save to two different instances. templates <p><label>{% trans "Payment Method" %}</label> {% for rs in shopcart %} <select class="input" name="payment" id="id_payment{{forloop.counter}}"> <option value="COD" data-description="Item 1" selected="selected">{% trans "COD" %}</option> <option value="Bank Transfer" data-description="Item 2">{% trans "Bank Transfer" %}</option> </select> <p id="description{{forloop.counter}}"></p> <script> $('#id_payment{{forloop.counter}}').change(function(){ var $selected = $(this).find(':selected'); $('#description{{forloop.counter}}').html($selected.data('description')); }).trigger('change'); </script> {% endfor %} views form = OrderForm(request.POST) if form.is_valid(): for rs in shopcart: d = Order() d.payment = form.cleaned_data['payment'] d.save() else: messages.warning(request, form.errors) form = OrderForm() context = { 'form': form } return render(request, 'Order.html', context) I wanted the payment choice to be made for each product in shopcart, but the last choice is fetched and given to all the products in the shopcart. Any advice would be nice. Thankyou in advance! -
Django: get all objects with a defined set of related objects
Let's say we have a many2many relationship as follows: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author, related_name="books") and now I have a known set of Authors: authors = Author.objects.filter(...) How can I get all the books that are authored by that exact set of authors? books = Book.objects.filter(X) what is X? Such that I have all the books authored by exactly that set of authors? I have tried, just because: books = Book.objects.filter(authors__in=authors) But nah, that returns the books to which any of those authors contributed it seems. I want the books that all of those authors contributed to and only those authors. Thus far, this has stumped me. -
Problem to show contact detail page - Django and Vuejs
I'm trying to learn how to use vuejs in a django project (i'm not using DRF) and I'm having trouble configuring my url to display a detail page view. So far i have configured urls.py like shown below: app_name = 'contacts' urlpatterns = [ path('', views.contacts_all, name='contacts_all'), path('<int:contact_id>/', views.contact_details, name='contact_details'), ] Also i have a views.py like shown below: def contacts_all(request): # Check if an Ajax Request if request.headers.get('X-Requested-With') == 'XMLHttpRequest': contacts = list(Contact.objects.values()) return JsonResponse(contacts, safe=False, status=200) return render(request, 'contacts/all-contacts.html') def contact_details(request, contact_id): contact_detail = get_object_or_404(Contact, id=contact_id) context = { 'contact_detail': contact_detail } return render(request, 'contacts/contact-detail.html', context) Also i successfully getting all contacts from django server: <script> const app = new Vue({ delimiters: ['[[', ']]'], el: '#contact-app', data: { contacts: [], }, methods: { // Get all contacts from server async getContacts(){ const response = await axios({ url: 'http://127.0.0.1:8000/contacts/', method: 'get', headers: { 'X-Requested-With': 'XMLHttpRequest' } }).then(response => { console.log(response.data); this.contacts = response.data }).catch(err => { console.log(err) }); }, }, async created(){ await this.getContacts(); } }); </script> And in template i'm successfully showing all contacts data like shown below: <div class="flex-row-fluid ml-lg-8 d-block" id="contact-app"> <div class="card card-custom card-stretch"> <div class="card-body table-responsive px-0"> <div class="list list-hover min-w-500px" data-inbox="list" v-if="contacts.length" > … -
I am unable to get round toggle in my django template
I have a table which contains for loop and if tag using jinja this table shows some data but in last column I want round toggle button but I only get a checkbox, I am unable to find the error please help me. <tbody> {%for student in students%} {%if user.staff.class_coordinator_of == student.division and user.staff.teacher_of_year == student.year%} <tr> <td style="color:white;">{{student.user.first_name}}</td> <td style="color:white;">{{student.user.last_name}}</td> <td style="color:white;">{{student.year}}</td> <td style="color:white;">{{student.division}}</td> <td style="color:white;">{{student.batch}}</td> <td> <label class="switch "> <input type="checkbox" id="" value="" checked> <span class="slider round"></span> </label> </td> </tr> {% endif %} {%endfor%} </tbody> OUTPUT Output Image -
in django set default image to ImageField as Default object
I have a model in the model and Imagefield is there. class Job(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to=" jobOpeningImages", default=' jobOpeningImages/1_oKH7Co9.jpeg', blank=True) But I am not getting any current image URL in the localhost. I am expecting this type of result So how can we achieve the below? in first image Currently: jobOpeningImages/1_oKH7Co9.jpeg -
useEffect fires and print statements run but no actual axios.post call runs reactjs
I have a useEffect function that is firing due to yearsBackSettings changing and the console.log statements inside useEffect fire too: useEffect(() => { console.log("something changed") console.log(yearsBackSettings) if (userId) { const user_profile_api_url = BASE_URL + '/users/' + userId const request_data = { searches: recentSearches, display_settings: displaySettings, years_back_settings: yearsBackSettings } console.log("running user POST") console.log(request_data) axios.post(user_profile_api_url, request_data) .then(response => { console.log("user POST response") console.log(response) }) } }, [recentSearches, displaySettings, yearsBackSettings]) As the image shows, changing yearsBackSettings causes this to run, which SHOULD make a post request with all the new settings: However, for some reason there is nothing happening on the server except the stock search running: the last updated time for stock ibm before save: 08/25/2022 08:13:30 stock was updated within the last 5 minutes...no need to make an api call the last updated time for stock ibm after save: 08/25/2022 08:13:30 [25/Aug/2022 08:17:25] "POST /users/114260670592402026255 HTTP/1.1" 200 9 [25/Aug/2022 08:17:25] "GET /dividends/ibm/3/5 HTTP/1.1" 200 4055 the last updated time for stock ibm before save: 08/25/2022 08:13:30 stock was updated within the last 5 minutes...no need to make an api call the last updated time for stock ibm after save: 08/25/2022 08:13:30 [25/Aug/2022 08:17:26] "GET /dividends/ibm/27/5 HTTP/1.1" 200 8271 the last updated … -
Django url path regex: capturing multiple values from url
How do I capture multiple values from a URL in Django? Conditions: I would like to capture ids from a URL. The ids vary in length (consist of numbers only), and there can be multiple ids in the URL. Check out the following two examples: http://127.0.0.1:8000/library/check?id=53&id=1234 http://127.0.0.1:8000/library/check?id=4654789&id=54777&id=44 The solution may include regex. urlpatterns = [ path("", view=my_view), path("<solution_comes_here>", view=check_view, name="check_view"), ] P.S. all solutions I found on this platform and Django documentation only explain cases for capturing single values from the URL -
How to make import using unique_together?
I need to make an import using not only the id field but also the brand field. So that products can exist with the same ID but a different brand class Part(models.Model): brand = models.CharField('Производитель', max_length=100, blank=True, default='Нет производителя') id = models.CharField('Артикул', max_length=100, unique=True, primary_key=True) name = models.CharField('Название', max_length=100, blank=True, default='Нет имени') description = models.TextField('Комментарий', blank=True, max_length=5000, default='Нет описания') analog = models.ManyToManyField('self', through='ContactConnection',blank=True, related_name='AnalogParts') analog = models.ManyToManyField('self',blank=True, related_name='AnalogParts') images = models.FileField('Главное изображение', upload_to = 'parts/', blank=True) images0 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) images1 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) images2 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) def __str__(self): return str(self.id) return self.name class Meta: verbose_name = 'Запчасть' verbose_name_plural = 'Запчасти' unique_together = [['id', 'brand']] class PartConnection(models.Model): to_part = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='to_parts') from_part = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='from_parts') -
When a button is clicked I want ajax to redirect towards a url but it is not working
I am trying to create a SPA, using django and javascript, I have a home page with two buttons on it (Sign up and sign in), I want that when signup button is clicked, ajax redirects towards signup url Here is my code js $('#id_register').click(function(){ $.ajax({ url: 'register', method:"GET", success: function(data){ console.log(data) }, error: function(error){ console.log(error) } }) }) Here is my html <div class="banner"> <div class="content"> <h3 id="home">Feeling Hungry?</h3> <h4 id="home_para">Order right now!</h4> <div> <button id="id_sign" type="button">Sign In</button> <button id="id_register" type="button">Sign Up</button> </div> </div> </div> </body> It is successfully returning me the data but not redirecting towards the required url. here is my urls.py urlpatterns =[ path('register', RegisterView.as_view()), path('login', LoginView.as_view(), name="login"), path('', HomeView.as_view(), name="home") ] I will be very thankful for the help -
Django: Add model object to aggregated queryset
Is there a way to add object to aggregated queryset? For example: qs = Model.objects.filter(title="abc").aggregate(likes=Count('likes')) and i want to do something like: qs = Model.objects.filter(title="abc").aggregate(likes=Count('likes')).get(pk=1) -
Django serving build with many MIME Type errors (sveltekit)
index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="icon" href="/static/icons/tabIcon.svg" /> <link rel="stylesheet" href="/static/posty.css" /> <meta http-equiv="content-security-policy" content="" /> <link rel="modulepreload" href="/static/_app/immutable/start-6f351e07.js" /> <link rel="modulepreload" href="/static/_app/immutable/chunks/index-d9a79891.js" /> <link rel="modulepreload" href="/static/_app/immutable/chunks/index-d827f58a.js" /> <link rel="modulepreload" href="/static/_app/immutable/chunks/singletons-eca981c1.js" /> </head> <body> <div> <script type="module" data-sveltekit-hydrate="45h" crossorigin> import { set_public_env, start, } from "/static/_app/immutable/start-6f351e07.js"; set_public_env({}); start({ target: document.querySelector('[data-sveltekit-hydrate="45h"]') .parentNode, paths: { base: "", assets: "/static/" }, session: {}, route: true, spa: true, trailing_slash: "never", hydrate: null, }); </script> </div> </body> </html> svelte.config.js import adapter from '@sveltejs/adapter-static'; import preprocess from 'svelte-preprocess'; /** @type {import('@sveltejs/kit').Config} */ const config = { preprocess: preprocess(), kit: { adapter: adapter({ assets: 'build/assets', out: 'dist', fallback: 'index.html', precompress: false }) } }; export default config; settings.py # ... DEBUG = True STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/assets') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # ... Errors The resource from “http://127.0.0.1:8000/_app/immutable/pages/__layout.svelte-bd484656.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). The resource from “http://127.0.0.1:8000/_app/immutable/assets/__layout-ce6f71c3.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). The resource from “http://127.0.0.1:8000/_app/immutable/chunks/index-d9a79891.js” … -
Manager isn't accessible via User instances
I m trying to insert email but there is an error Manager isn't accessible via User instances. here is the my code below from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from rest_framework import serializers from rest_framework.validators import UniqueValidator from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from .models import Trip, User class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) group = serializers.CharField() def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError('Passwords must match.') return data def create(self, validated_data): group_data = validated_data.pop('group') group, _ = Group.objects.get_or_create(name=group_data) data = { key: value for key, value in validated_data.items() if key not in ('password1', 'password2') } data['password'] = validated_data['password1'] user = self.Meta.model.objects.create_user(**data) user.objects(validated_data['email']) user.groups.add(group) user.save() return user class Meta: model = get_user_model() fields = ( 'id', 'username', 'password1', 'password2', 'email', 'first_name', 'last_name', 'group', 'photo', ) read_only_fields = ('id',) class LogInSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) user_data = UserSerializer(user).data for key, value in user_data.items(): if key != 'id': token[key] = value return token