Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django Admin site password field changes when I edit the attribute of other widgets
In the default Django Admin site, the Password field shows how it is encrypted and there's a link to change it. In my project I need to set some fields to LTR (because the site is in RTL), so this is what I do: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.utils.translation import gettext_lazy as _ from django import forms from .models import CustomUser # Register your models here. class CustomUserForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['email'].widget.attrs.update({'dir': 'ltr'}) self.fields['national_id'].widget.attrs.update({'dir': 'ltr'}) self.fields['mobile_number'].widget.attrs.update({'dir': 'ltr'}) @admin.register(CustomUser) class CustomUserAdmin(UserAdmin): form = CustomUserForm fieldsets = ( (None, {'fields': ('email', 'password')}), ( _('Personal info'), { 'fields': ( 'first_name', 'last_name', ) }, ), ( _('Profile info'), { 'fields': ( 'national_id', 'mobile_number', 'home_address', 'work_address', ) }, ), ( _('Permissions'), { 'fields': ( 'is_active', 'is_staff', 'is_superuser', 'is_verified', 'groups', 'user_permissions', ), }, ), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( ( None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2'), }, ), ) list_display = ('email', 'first_name', 'last_name', 'is_staff') list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups') search_fields = ('email', 'first_name', 'last_name', 'national_id', 'mobile_number') ordering = ('email',) filter_horizontal = ( 'groups', 'user_permissions', ) But with that custom form, the Password field looks like this: I have not touched … -
Add multiple instances of a model with some shared fields at once
I'm trying to come up with a way of allowing a user to add multiple instances of a specific model at once in Django Admin, but with some fields being shared between them. Example model: class Something(models.Model): ref = models.ForeignKey(to="AnotherModel", on_delete=models.CASCADE) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) What I am trying to achieve is to have a page in Django Admin where the user would define the ref field only once, then add and populate as many name and is_active fields as he wants, press the Save button and the ref field would get automatically re-used to create as many Something instances as the user created with the name and is_active fields. I know of Django's StackedInLine and TabularInLine, but I am not able to produce the above mentioned functionality with them, at all. Thank you -
How to adjust old migrations for removals in Django?
In our Django project we are currently removing a couple of old models, which were used until recently. When running our tests now, Django tries to create and migrate to the test database, however as the first migrations point to a now not existing model, it throws ValueError: The field ticket.Ticket.ci was declared with a lazy reference to 'plugin.ci', but app 'plugin' doesn't provide model 'ci'.. Adjusting old migrations is never a good idea I suppose, so how exactly can one proceed here? The old migration looks like this: migrations.AddField( model_name='ticket', name='ci', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='plugin.ci'), ), Should I just remove this piece? -
Select2 blocks htmx hx-get
I'm using select2 on my form select with htmx but for some reason hx-get does not send any request while form field has select2 I was trying to turn off select2 and everything works fine, so how can i fix that? template.html <form method="get" class="mb-3"> <div class="well"> <div class="row"> <div class="form-group col-sm-4 col-md-4 mb-3"> <div class="custom-select"> {% render_field form.contractor_object|add_class:'form-select' hx-get="/customer/worklog/" hx-target='#id_test' hx-select="#id_test" %} </div> </div> <div class="form-group col-sm-4 col-md-4 mb-3"> <div class="custom-select" id="id_test"> {% render_field form.contractor_section|add_class:'form-select' %} </div> </div> </div> </div> <div class="mt-4 custom-label"> <div class="row"> <div class="col"> <button type="submit" class="btn btn-outline-primary">Поиск</button> <a class="btn btn-outline-primary" href="{% url 'customer_worklog' %}">Сброс</a></div> </div> </div> </form> <script> $(document).ready(function () { $("#id_contractor_object").select2(); }); </script> <script> $(document).ready(function () { $("#id_contractor_counter").select2(); }); </script> <script> $(document).ready(function () { $('#id_contractor_section').select2(); }); </script> -
Django pointfield admin widget shows wrong point (long/lat switch places)
I have a model with PointField. class Companion(models.Model): startpoint = models.PointField(srid=4326, null=True) My admin.py file class CompanionAdmin(admin.GISModelAdmin): pass admin.site.register(Companion, CompanionAdmin) When I set point in django admin and save it, all looks good. But when i try to find saved coordinates on map, it didn't find anything. As I found out it happens because coordinates switch their places (long is lat, lat is long). I used different admin classes, such as LeafletGeoAdmin, GISModelAdmin, it didn't help. How can I fix it? -
how can i delete column with sum = 0 in excelhtml5 export
i use this code to export my table to excel in datatable-django. $(document).ready(function() { $('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'copy', 'csv', 'excel', 'pdf', 'print' ] } ); } ); I have a table with 72 columns. I only want to export the columns to Excel whose cell sum is not zero. How can I do this? i want just show the column with sum>0 -
Automatic set/update fields in Django
I have to models in models.py class Teams(models.Model): Name = models.CharField(verbose_name="Team Name", max_length=200) Slug = AutoSlugField(populate_from="Name", always_update=True, editable=True, verbose_name="Team Slug") Location = models.CharField(verbose_name="Team Location", max_length=200) Leader = models.ForeignKey('Members', on_delete=models.SET_NULL, null=True, blank=True) ArrivalDate = models.DateTimeField(default=timezone.now, editable=False, verbose_name="Arrival Date") DepartureDate = models.DateTimeField(null=True, blank=True, verbose_name="Departure Date") and class Members(models.Model): Name = models.CharField(verbose_name="Member Name", max_length=200) Team = models.ForeignKey(Teams, on_delete=models.CASCADE) PhoneNumber = models.CharField(max_length=20, null=True, blank=True) Email = models.EmailField(max_length=50, null=True, blank=True) BloodType = models.CharField(max_length=3, choices=BLOOD_TYPE_CHOICES, null=True, blank=True) isLeader = models.BooleanField(default=False) When isLeader field in Members field set True, I want to update Leader field in Teams model. Thanks in advance -
Duplicate entries are returning when filtering model
//Model class ClientUserSelectedPodcast(AuditModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user_selected_podcast', null=True,blank=True) client_unit = models.ForeignKey(Unit, on_delete=models.CASCADE, related_name='user_selected_unit', null=True, blank=True) client_superunit = models.ForeignKey(SuperUnit, on_delete=models.CASCADE, related_name='user_selected_super_unit', null=True, blank=True) selected_type = models.CharField(max_length=100, default="FAVOURITE") class Meta: ordering = ('-pk',) //view class GetNewClientsCountViewSet(APIView): def get(self,request,*args, **kwargs): from podcast.api_serializers import UnitMiniSerializer from datetime import datetime data=[] total_listener_count={} client_count=Client.get_new_clients_count() gender_wise_count={} # gets the podcast unit count of this month podcast_count=Unit.get_new_podcast_unit_count() user_counts=ClientUser.get_new_client_user_count() most_listened_units,most_liked_units=ClientUserSelectedPodcast.get_total_listened_liked_podcast() inhouse_listened_units,inhouse_liked_units=ClientUserSelectedInhouse.get_total_listened_liked_inhouse() podcast_listener_count=ClientUserSelectedPodcast.get_total_podcast_listeners() inhouse_listener_count=ClientUserSelectedInhouse.get_total_inhouse_listeners() podcast_wise_count=ClientUserSelectedPodcast.get_gender_wise_listeners() inhouse_wise_count=ClientUserSelectedInhouse.get_gender_wise_inhouse_listeners() total_listener_count['podcast']=podcast_listener_count total_listener_count['inhouse']=inhouse_listener_count gender_wise_count['podcast']=podcast_wise_count gender_wise_count['inhouse']=inhouse_wise_count # most liked show of this month most_liked_show= ( ClientUserSelectedPodcast.objects .filter(selected_type='FAVOURITE', created_at__month=datetime.now().month) ) print(most_liked_show) data.append({ 'clients':client_count, 'podcast':podcast_count, 'user':user_counts, 'total_listener_count':total_listener_count, 'most_listened_units':most_listened_units, 'most_liked_units':most_liked_units, 'inhouse_listened_units':inhouse_listened_units, 'inhouse_liked_units':inhouse_liked_units, 'gender_wise_count':gender_wise_count }) return Response(data) i want to get the Most liked show for this month i.e selected*type='FAVOURITE'. Queryset: <QuerySet [<ClientUserSelectedPodcast: ClientUserSelectedPodcast object (552)>, <ClientUserSelectedPodcast: ClientUserSelectedPodcast object (551)>, <ClientUserSelectedPodcast: ClientUserSelectedPodcast object (550)>] The problem here is that query is returing different objects but the value in them is same ie the object 552 and 551 has the same entries i.e 552 -> {'user':224, clientunit:'94ba2e2a47254028b0d3d59eeb5b257d', 'selected*_type':FAVOURITE'}, 551-> {'user':224, clientunit:'94ba2e2a47254028b0d3d59eeb5b257d', 'selected_type':FAVOURITE'} What i want if this occurs duplicate occurs i want to take the count as one and want to return the most liked show for this month -
Why is the full path not saved in the database
I have this function in a Django model to save the profile picture to the database: def photo_directory_path(instance, filename): return "user_{0}/profiles/{1}/images/{2}".format(instance.owner.id, instance.id, filename) Here is the model that uses that function: class FounderProfile(models.Model): background_image = models.FileField( upload_to=bg_directory_path, null=True, blank=True, ) profile_picture = models.FileField( upload_to=photo_directory_path, null=True, blank=True, ) tagline = models.CharField(max_length=100, null=True, blank=True) first_name = models.CharField(max_length=30, null=True, blank=True,) middle_name = models.CharField(max_length=30, null=True, blank=True,) last_name = models.CharField(max_length=30, null=True, blank=True,) bio = models.TextField(max_length=5000, null=True, blank=True,) date_of_birth = models.DateField( null=True, blank=True,) owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name="founderprofile") And here is the settings for handling images: STATIC_URL = "static/" STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles/") MEDIA_ROOT = os.path.join(BASE_DIR, "storage").replace("\\", "/") MEDIA_URL = "/storage/" and my main urls.py file: urlpatterns = [ path("", include("pages.urls")), path("admin/", admin.site.urls), path("api/v1/", include("api.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I am using Django Rest Framework and a Vue3 front end. My question is why are the files not saved with the full url which also includes the domain name which in my case is "http://localhost:8000"? Because now I have to add "http://localhost:8000" to the image path otherwise the image does not show and it's not going to work in production -
how do I call delete function in django admin
I am trying to use the Django admin delete function to ensure that the corresponding quantity is deleted from the associated page when the delete function is clicked. For example, I have a class called RestockModel. When I add a new Restock item, the restock quantity can be automatically added in the StockListModel. However, when I need to delete the Restock item, the quantity in StockListModel is not deleted immediately. How can I call the django admin delete function to this statement? Here is the code that how I made the quantity can be added when I create a new restock item: class restockInfo(admin.ModelAdmin): list_display = ["product", "delivery_order_no","restock_quantity", "supplier_name", "created_date"] readonly_fields = ["created_date"] search_fields = ['created_date'] def save_model(self, request, obj, form, change): product = obj.product restock_quantity = obj.restock_quantity if restock_quantity and product.quantity_in_store: if restock_quantity >= 0: obj.product.quantity_in_store = product.quantity_in_store + restock_quantity # don't forget to save stock after change quantity obj.product.save() messages.success(request, 'Successfully added!') super().save_model(request, obj, form, change) else: messages.error(request, 'Invalid Quantity, Please Try Again!!!') return restockInfo This is my restock models: class restockList(models.Model): product = models.ForeignKey("stockList", on_delete=models.CASCADE, null=True) delivery_order_no = models.CharField(max_length=255, null=True) restock_quantity = models.IntegerField(null=True) supplier_name = models.CharField(max_length=255, null=True) created_date = models.DateTimeField(auto_now_add=True, blank=True, editable=False) class Meta: db_table = "restocklist" … -
Does chatgpt provide accurate codes of programming language?
I have seen chatgpt provide codes but i am not sure if its reliable I am expecting the answers to be accurate and reliable. Since chatgpt is a machine learning system i hope it can be amazing if it can give us detailed and be able to let us upload pictures so that we are able to come up with defined structure of answers -
400 Bad Request for djoser based registered user activation
I am new to django and am trying to build a use registration system using djoser, I am getting the email for activation but the activation process is not working, please suggest any solutions, here are the files: models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager # Create your models here. class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save() return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): return self.name def get_short_name(self): return self.name def __str__(self): return self.email settings.py """ Django settings for art_portal project. Generated by 'django-admin startproject' using Django 4.2.2. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path from datetime import timedelta import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in … -
CSRFToken with Django backend and React frontend
I'm trying to set up CSRF cookies between my django backend and react front end. Currently on my backend I have these two view: @method_decorator(ensure_csrf_cookie, name='dispatch') class GetCSRFToken(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response({'success': 'CSRF cookie set'}) @method_decorator(csrf_protect, name='dispatch') class LoginView(APIView): permission_classes = (permissions.AllowAny, ) def post(self, request): data = request.data username = data.get('username') password = data.get('password') user = authenticate(request=request, username=username, password=password) try: if user is not None: login(request, user) return JsonResponse({'message': 'User is authenticated'}) else: return JsonResponse({'message': 'Either password or username is invalid, try again'}, status=400) except: return JsonResponse({'message': 'Something went wrong when authenticating'}) When I test them using Postman they work. I just call the CSRF cookie and copy that cookie and paste it into the X-CSRFToken header of the login on Postman. So both of them work, but then when I test it using the front end it doesnt. From my research this is what I've done. The top one is a CSRFToken.js and the bottom is a piece of my Login.js import React, { useState, useEffect } from 'react'; import axios from 'axios'; const CSRFToken = () => { const [csrftoken, setcsrftoken] = useState(''); const getCookie = (name) => { let cookieValue … -
Issue with adding stock on Django website - Request reset or not hitting server
I'm encountering an issue with my Django website where clients are unable to add stock after a certain period. Our team has tested the functionality successfully from our own computers, but when our client tests it from their side, the request seems to be reset or not hitting the server, even though it initially shows a 200 OK response. We suspect it might be related to antivirus software, as our client is only using the Windows Antivirus Defender. Have any of you experienced a similar issue or have any insights on what could be causing this behavior? Any suggestions or guidance would be greatly appreciated. Thank you! checked all neceessary debug -
How can I serialize a list of objects and return the object if validated?
I have the below in one of my viewset classes: serializer = ResponsesSerializer(data=queryset, many=True) serializer.is_valid(raise_exception=True) validated_data = serializer.validated_data response = Response(validated_data, status=status.HTTP_200_OK) return response For testing purposes, queryset is the below list of objects that is being passed to my ResponsesSerializer, where only the first object has a record key: queryset = [ { "C_Ethnicity.r1": 0, "C_Ethnicity.r2": 0, "EaseOfFind.r1": 0, "EaseOfFind.r2": 1, "Leg.r1": 0, "Leg.r2": 0, "record": 17 }, { "C_Ethnicity.r1": 0, "C_Ethnicity.r2": 0, "EaseOfFind.r1": 0, "EaseOfFind.r2": 1, "Leg.r1": 1, "Leg.r2": 0, }, { "C_Ethnicity.r1": 0, "C_Ethnicity.r2": 0, "EaseOfFind.r1": 0, "EaseOfFind.r2": 1, "Leg.r1": 1, "Leg.r2": 0, } ] In the response, the serializer expectedly raises a validation error for the last two objects without a record key, but I don't know why the first object is then empty: [ {}, { "non_field_errors": [ "Missing 'record' key in dictionary." ] }, { "non_field_errors": [ "Missing 'record' key in dictionary." ] } ] This is the ResponsesSerializer: class ResponsesSerializer(serializers.Serializer): def to_internal_value(self, data): return data def validate(self, data): if 'record' not in data: raise serializers.ValidationError("Missing 'record' key in dictionary.") return data I'm new to serializers, and in this case I just want to add validation criteria that each object in the list can … -
'password_reset_done' not found.'password_reset_done' is not a valid view function or pattern name
Here is my urls.py file urlpatterns =[ path("accounts/",include(("django.contrib.auth.urls","auth"),namespace="accounts")), path('',include('app1.urls') ] My application name is app1 The urls in app1 are only view functions -
Django: creating a data migration for a model that is deleted in another migration results in error
I have a Django app with a Character model, which I am migrating to a brand new model (and database table) called Content. I first created the new model, added the migrations for it, then added a data migration to migrate data from Character to Content, and then I removed the Character model and created a migration for that. While working on the steps one by one, and running the new migration on every step, it all worked (locally). But when running ./manage.py migrate on the staging database I get this error: LookupError: App 'characters' doesn't have a 'Character' model. This how how my data migration looks like: content/migrations/0002_auto_20230630_1434.py from django.db import migrations def run_data_migration(apps, schema_editor): Content = apps.get_model("content", "Content") Character = apps.get_model("characters", "Character") # Migration logic here class Migration(migrations.Migration): dependencies = [ ("content", "0001_initial"), ("characters", "0009_alter_character_avatar_alter_character_avatar_crop"), ] operations = [migrations.RunPython(run_data_migration)] Important to know is that 0009_alter_character_avatar_alter_character_avatar_crop is the migration step before the complete removal of the Character model. So since I am depending on that step before the removal and I am using apps.get_model instead of trying to use the Character model directly, I would've thought this just worked? How do I make sure that the data migration within … -
Newbie one-to-many relationship problem in admin
I am writing a simple application where there is a one to many relationship similar to that of Parent to Child, where one parent may have many children. In this case I give the child a foreign key referring to to the parent. The Parent object doesn't mention children because the relationship is in the other direction. That is fine, but in the admin system the page showing the parent insists that the child fieldd be filled in. There are however cases where a parent has no children. How do I tell the admin system that the child field may be left blank? Thanks for any help. -
Importing within file causes error when running Django test but not when using relative import
I have a directory that looks like this AppDir/ ChildDir/ file1.py file2.py tests/ my_test.py Inside the my_test.py file is the import from ..ChildDir.file1 import MyClass This runs fine when file2.py is not being imported in file1.py, however when I added these imports to file1.py: from file2 import myfunc_a, myfunc_b It gives me the error: ImportError: Failed to import test module: ... Traceback (most recent call last): File "/usr/lib/python3.11/unittest/loader.py", line 407, in _find_test_path module = self._get_module_from_name(name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ... ModuleNotFoundError: No module named 'file2' Executing file1 directly works, its only when running ./manage.py test that it throws this error. However, if I change the import in file1.py to: from .file2 import myfunc_a, myfunc_b ./manage.py test runs fine, however executing file1.py directly throws an error. -
i have this Erorr and i don't fix it [closed]
because I want to run server in django, it's gives an error Error loading mysql.connector module: MySQL Connector/Python C Extension not available (DLL load failed while importing _mysql_connector: The specified module could not be found.) run server but dont' run -
jquery to realtime update a django for loop
Good Afternoon, I am learning on how to use jquery in django and if possible I would like some help on realtime updating a table column in my django app. I have a column with order.status attributes wich can be: orderAwaitingPayment, orderPlaced, orderPackaging, orderReady, ortherOnTheWay and orderDelivered. I already can get a variable order_status and order_number from django channels: <script> const orderSocket = new WebSocket( "ws://" + window.location.host + "/ws/order/" ); orderSocket.onmessage = function(e) { var data = JSON.parse(e.data); var order = data.order var order_number = order.order_number var res_order_status = order.order_status console.log(order_number, res_order_status); }; </script> I have a django template that update the order.status and change color's badge depending on order.status from django database when the page reload but now i would like to update without refreshing the page with jquery. {% for order in orders %} ... <td style="font-size:18px;"> <a href="{% url 'v_dashboard_order_detail' order.order_number %}"> {% if order.status == 'orderAwaitingPayment' %} <span class="badge bg-danger">{{ order.get_status_display }}</span> {% elif order.status == 'orderPlaced' %} <span class="badge bg-primary">{{ order.get_status_display }}</span> {% elif order.status == 'orderPackaging' %} <span class="badge bg-secondary">{{ order.get_status_display }}</span> {% elif order.status == 'orderReady' %} <span class="badge bg-success">{{ order.get_status_display }}</span> {% elif order.status == 'ortherOnTheWay' %} <span class="badge bg-dark">{{ order.get_status_display … -
Django printing multiple form fields
Hello I'm very new to django and python and would ppreciate if you could help me out. I want to create 2 fields, namely password and confirm password but the webpage renders 2 sets of each. this is the code: class RegistrationForm(UserCreationForm): email = forms.EmailField(label="", widget= forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Email Address'})) first_name = forms.CharField(label="",widget= forms.TextInput(attrs={'class':'form-control', 'placeholder': 'First Name'})) last_name = forms.CharField(label="",widget= forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Last Name'})) ph_number = forms.CharField(label="",widget= forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Phone Mumber'})) password_1 = forms.CharField(label="",widget= forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Password 1'})) password_2 = forms.CharField(label="",widget= forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Password 2'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'ph_number', 'password_1', 'password_2' ) def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['username'].widget.attrs['placeholder'] = 'User Name' self.fields['username'].label = '' self.fields['username'].help_text = '<span class="form-text text-muted"><small>Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</small></span>' self.fields['ph_number'].widget.attrs['class'] = 'form-control' self.fields['ph_number'].widget.attrs['placeholder'] = 'Phone Number' self.fields['ph_number'].label = '' self.fields['ph_number'].help_text = '<span class="form-text text-muted small"><small>Your number can\'t be more than 10 digits.</small><small>Your phone number is too short</small></span>' self.fields['password_1'].widget.attrs['class'] = 'form-control' self.fields['password_1'].widget.attrs['placeholder'] = 'Password' self.fields['password_1'].label = '' self.fields['password_1'].help_text = '<ul class="form-text text-muted small"><li>Your password can\'t be too similar to your other personal information.</li><li>Your password must contain at least 8 characters.</li><li>Your password can\'t be a commonly used password.</li><li>Your password can\'t … -
django.db.utils.IntegrityError: NOT NULL constraint failed: new__blog_post.author_id
I am trying to migrate the changes in my model but getting this issue: django.db.utils.IntegrityError: NOT NULL constraint failed: new__blog_post.author_id Code: from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): author= models.ForeignKey(User,on_delete=models.CASCADE,null=True) text= models.TextField(max_length=300) created= models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.text -
Login Token in Django
hello I have a problem witch I have a User model in my Account app and I have a user inside it with this information { "id": 2, "username": "johndoe", "email": "example@gmail.com", "password": "password123" } my problem is when I POST this JSON data to my LoginView I get this error: (ValueError: Cannot query "johndoe": Must be "User" instance. { "email": "example@gmail.com", "password": "password123" } LoginView, Token code: user = User.objects.get(email=email) token, created = Token.objects.get_or_create(user=user) return Response(data={'token': token.key},status=status.HTTP_200_OK) my User model: class User(AbstractUser): id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) full_name = models.CharField(max_length=255, default="") simple_description = models.CharField(max_length=255, default="tourist") biography = models.TextField(null=True, blank=True, default="") profile_picture = models.ImageField(null=True, blank=True) def __str__(self): return self.username I tried to set my User model as the default of the Django User model but when I wanted to create a superuser for my admin panel, it created a regular user with a long password that I didn't put that -
SyntaxError: Expected property name or '}' in JSON
I have a code with Django and JS. At fist I pass a json file to my JS with Django like this : from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from rest_framework.renderers import JSONRenderer import json from .models import Adam class AdamViewset(ModelViewSet): queryset = Adam.objects.all() class MainView(APIView) : def get(self, request) : data = json.dumps(list(Adam.objects.values())) return Response({'data' : data}, template_name='doroste.html') but important part is javascript const dataStr = '{{data}}'; const dataJson = JSON.parse(`${dataStr}`) console.log(dataStr) I expected to get a json but instead I got this error : SyntaxError: Expected property name or '}' in JSON I searched for it but I couldn’t find solution CAUSE MY LIST USES "" INSTEAD OF '' SO IT IS OKAY