Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mess with models primary key. Django
There are two models: class Parent(models.Model): name = models.CharField(max_length=25) date = models.DateField(default=now) class Child(models.Model): name = models.CharField(max_length=25) quantity = models.DecimalField(max_digits=10, decimal_places=2) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) In my app I have a set (or list) of parents within a set of child elements inside. When I try to delete child element - request redirects me to the wrong parent. Here below my view: def deleteChild(request, pk): child= get_object_or_404(Child, pk=pk) parent= get_object_or_404(Parent, pk=child.parent.pk) if request.method == 'POST': child.delete() return redirect('detail', pk=parent.pk) context = {'parent': parent.pk} return render(request, 'parent-detail.html', context) my url: path('child-delete/<int:pk>', views.deleteChild, name='child-delete'), I assume one of the reasons are - incorrect ID pass... Point me please what is wrong with this and much appreciate to You All if You give me an advice how to correctly prescribe Models for such case (maybe best practice if any). Because I expect same issue when I start doing updateChild view X))). Thanks a lot and have a nice day! -
ReactJS with Django Elements Displayed As Text
I try to get elements inside my div but they are displayed as text and not Elements. I use Django as the back-end and ReactJS as a link import in my HTML template on the front-end. my template is like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin</script> </head> <body> <div id ="form-container"> </div> <!-- Bootstrap JS CDN --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> <script src="{% static '/js/login.js' %}"></script> </html> and my react JS file is like this: const hello = ('<h1>test</h1>'); const root = ReactDOM.createRoot(document.getElementById("form-container")); root.render(hello); Have tried removing the ' ' or the parenthesis but can't get it to work it either it shows invalid syntax. -
Austi updating Django postgres database when changes in legacy database are made in a docker container
I'm working on a Django project with docker which use different legacy Microsoft SQL Server database. Since I didn't want to alter those legacy databases I use inspectdb and Django router to create models and then use the data there to read and write a default Postgres database with all the Django specific tables. Everything was working fine, each instance of my model objects have the initial data from the SQL server db populating into the Postgres db. However whenever anything is updated in the SQL server db the data in the is not updating in Postgres db unless the docker container is stop and restarted. I'm wondering is there a way to autoupdate my postgres db when changes are made in the connected SQL Server db's with stopping the container? Would I need to use something like celery or a cron job to schedule updates? I've used cron jobs before but only to pull from an api. Is it possibly to run celery or a cron job just on a database and not an api? Or is there a solution that's simplier? I'm also running with nginx and gunicorn on an Ubuntu server. Using volumes to persist db. -
How to display background image in email letter (gmail smtp)
I use WagtailCMS and I installed wagtail-birdsong plagin (its for sending topics for subscribers) It uses django-mjml for email template. When admin create a letter, he choses an image as a background for email letter, but this image doesnt appear at all. I have such HTML- file: {% extends "mail/base.html" %} {% load wagtailimages_tags %} {% block email_body %} {% image self.header_background original as bg_img %} <mj-hero mode="fluid-height" background-width="600px" background-height="400px" background-url="{{ site.root_url }}{{ bg_img.url }}" padding="100px 0px"> <mj-text align="center" font-size="32px" color="orange">{{ self.headline }}</mj-text> </mj-hero> <mj-section css-class="richtext"> <mj-column> <mj-text font-size="18px">Hello {{ contact.email }}!</mj-text> {% for b in self.body %} {{ b }} {% endfor %} </mj-column> </mj-section> {% endblock email_body %} {% block email_head %} <mj-style> .richtext h3 { font-size: 26px; } .richtext p { font-size: 16px; line-height: 1.5; } </mj-style> {% endblock email_head %} base file: {% load mjml %} {% mjml %} <mjml> <mj-head> {% block email_head %} {% endblock email_head %} </mj-head> <mj-body> {% block email_body %} {% endblock email_body %} </mj-body> </mjml> {% endmjml %} so when I get this email and going to dev-tools I can see the root to the image and I can see the image via this root, but I also got a … -
Django 404 Error, views not found. Why? View is not show up or is not found
I programmed in Ruby beforehand and am now moving to Django. I am trying to follow the article here. https://docs.djangoproject.com/en/4.0/intro/tutorial01/ #polls/url.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] # mysite /urls.py """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] Here is my tree: polls/ --> init.py -> admin.py -> apps.py -> migrations/ --> init.py -> models.py -> tests.py -> urls.py -> views.py -> Of course, I ran django-admin startproject mysite before all of tihs and the output for the version is: └──╼ $python -m django --version 4.0.4 I tried starting the server: ─╼ $python manage.py runserver Watching for file changes with StatReloader Performing system checks... System … -
Why does my Django form keeps saying "this field is required"
I'm a beginner at Django. My registration page is making my form invalid and it keeps printing the same error even though both the password fields are filled and they are the same. I have only attached any codes that are relevant to the password fields Error: <ul class="errorlist"><li>password1<ul class="errorlist"><li>This field is required.</li></ul></li><li>password2<ul class="errorlist"><li>This field is required.</li></ul></li><li>__all__<ul class="errorlist nonfield"><li>Passwords do not match.</li></ul></li></ul> forms.py: class RegisterForm(UserCreationForm): password1 = forms.CharField( required=True, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'name': 'password1', 'id': 'floatingPassword', 'placeholder':'Password', }), ) password2 = forms.CharField( required=True, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'name': 'password2', 'id': 'floatingConfirmPassword', 'placeholder':'Confirm password', }), ) class Meta: model = User fields = [ 'password1', 'password2', ] # Compare password def clean(self): self.cleaned_data = super().clean() password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password != password2: raise forms.ValidationError("Passwords do not match.") return self.cleaned_data views.py (In prototype) def register(request): # Create a new form if request.method == 'GET': form = RegisterForm() return render(request, 'users/register.html', {'form': form}) # When the user submits the form elif request.method == 'POST': form = RegisterForm(request.POST) # Check if the form is valid if form.is_valid(): print('FORM is valid!') print(form.cleaned_data) form.save() #user = form.cleaned_data.get('username') #messages.success(request, f"Account has been created for {user}") # UPDATE THE URL LINK IN THE FUTURE return redirect('/login') … -
Can I user `django-filebrowser` with Django version 2.2.6
Hi I am working on django app version 2.2.6 and I want to use tinymce.models HTMLFIELd in my model and one of the requirement is the user want when click on the image tab to pop up with insert image url or brows from local file, the defult of HTMLFIEL is to render only image url option and for me to add the second options it seems I need to install ``django-filebrowser` but when I looked at the docs its say requirement django higher that the django version I am using and I don't want to upgraed django, is there any way to make it work -
Django Files doesn't save
I want to do a django project where you upload an image and this image is displayed on another page. I can edit it only with admin panel. Here is the code: Views.py def home(request): all1 = New.objects.filter(username='mynameis12').all() if not request.user.is_authenticated: return redirect('/login/') return render(request, 'home.html',{'alls':all1}) Models.py class New(models.Model): username = models.CharField(max_length=200) image = models.ImageField(upload_to='media') Forms.py class New1(ModelForm): username = forms.CharField(max_length=200) image = forms.ImageField(required=False) class Meta: model = New fields = ['username','image'] The image is showed but it doesn't be saved. What should I do? Thanks. -
Non FK models tied together by ID (unmanaged model) - how to filter in Django?
I have two models that are related - but they are not a FK relationship in Django because one is a non-managed model with the data coming from a pre-populated DB table. class Enrollment(models.Model): id = models.IntegerField(db_column="ID", primary_key=True) location_id = models.IntegerField(db_column="locationID") grade = models.CharField(db_column="grade", max_length=10) class Meta(object): managed = False db_table = "mytable_Enrollments" class Location(models.Model): name = models.CharField(max_length=50) alternate_name = models.IntegerField() I'm trying to filter Enrollment models using a list of Location models - but they are not tied together in a FK relationship. I am trying to get enrollments for a particular location like this: # This does not work properly - but does not hit the db which is what I want location_ids = Location.objects.filter(id=1).values_list("id", flat=True) enrollments = Enrollment.objects.filter(location_id__in=location_ids) However, this returns an empty queryset. If I cast location_ids to a list (like this: list(location_ids)) and then filter on that, it works. # This works properly - but hits the db which is NOT what I want location_ids = Location.objects.filter(id=1).values_list("id", flat=True) enrollments = Enrollment.objects.filter(location_id__in=list(location_ids)) Is there a way to use the Django ORM to get what I want in this case without causing it to evaluate the queryset? -
why there is no module named django?
C:\Users\zena_\Anaconda3\python.exe C:/Users/zena_/DjangoRestApisPostgreSQL/tutorials/apps.py Traceback (most recent call last): File "C:/Users/zena_/DjangoRestApisPostgreSQL/tutorials/apps.py", line 1, in from django.apps import AppConfig ModuleNotFoundError: No module named 'django' -
Export serialized data to CSV - Django Rest Framework
I have ModelViewSet in DRF: class NameViewSet(ModelViewSet): serializer = NameSerializer def get_queryset(self): /* some manipulations on data */ I want to create endpoint for exporting data to CSV: @action(methods = ['get']) def export(self): /*exporting serialized data to CSV */ Can you tell me how to access serialized data into export function and actually export it to CSV? -
Django: query of a foreign key of a foreign key
This might be stupid question and I am sure that there is a basic query for this situation, but I don't seem to get a hang of it and Google turned out to be a miss for solution. I have models: Project, primary key=project_no; Under project there are product_config models, primary key=id; Under each product_config there is a pre_config model, primary key=product_id; Under each pre_config there is a list of sub_config models, primary key=id; Now I am loading a page for project details and I pass a project_no and make a query for all product_configs: project.objects.get(project_no=project_no) product_config.objects.filter(project_no=project_no) Now I want to create a table for the list of sub_configs according to pre_config under product_config. In a shell I can query the list with: sub_config.objects.filter(product_id=product_id) How I can pass the product_id of pre_config from my product_config to query all the sub_configs? -
DJANGO: Running SQL query using cursor in project.settings.py file
In my project, I have made some setting fields within the "settings.py" file configurable by exposing them to the user via an environment file. So the user can modify the values on the .env file, and that is then used to update the setting fields within the main project settings.py file. I want to improve this by migrating some of this values to the database, so users can set their values interactively via the product's UI instead of having to modify the .env. I have taken the following approach: After the default database has been declared in the DATABASES dictionary, I isntantiate a connection.cursor() to run a raw SQL query that retrieves the settings from the database, as described in the documentation. I manipulate the results of the cursor to construct a dictionary in which keys are setting identifiers and values are the relevant values from the database, as set by the user. This dictionary is then used to assign the appropriate value to each Django setting variable (i.e. SESSION_COOKIE_AGE, MEDIA_ROOT, etc.). So at each setting variable instead of doing a getenv, I retrieve the value from the dictionary using the relevant key. I have observed the code's behavior within … -
Insert Html table to MySQL - DJANGO
i have HTML table like that : (a lot of stores that i entered myself) <form method="post" ,action="#"> {% csrf_token %} <table class="table" dir="rtl"> <thead> <tr> <th scope="col">store name</th> <th scope="col">Address</th> <th scope="col">phone-number</th> <th scope="col">Opening hours</th> <th scope="col">Navigate</th> </tr> </thead> <tr> <th scope="row">food store </th> <td>dsdadad</td> <td>03-6040242</td> <td>Monday to Saturday, 14:30-18:00</td> <td><a href="</a></td> </tr> . . . . . and a lot more rows How can i insert that table to MySQL database ? -
Recursively navigating through dictionnary in django template
I have a dictionnary of unknown depth which I want to display in my Django template. This dictionnary represents the structure of the subfolders inside of a folder. My goal is to display it with the parent subfolders before their children, which would be indented to show that they're children of that folder. So to explain with an example, if I have the following dictionnary : {'Script Hello': {'Script Hello World': {'Script Hello World 2': None, 'Script Hello World 3': None}}, 'Script Hello World 4': None, 'Script Hello World 5': {'Script Hello World 6': None}} I want it to be displayed like this : . Script Hello . Script Hello World . Script Hello World 2 . Script Hello World 3 . Script Hello World 4 . Script Hello World 5 . Script Hello World 6 I've done a small code that does the job if the depth if at most 3 (to determine what I really wanted), but couldn't find a way to make it recursive. My code is this : {% for key, values in list.items %} <li> {{ key }} <ul> {% for key,values in values.items %} <li>{{ key }}</li> <ul> {% for key,values in values.items %} … -
Django celery .delay() in requests get stucked
I have a project running on 3 different environments, on 2 environments it works on production for some reason stopped working (was working before). The code is pretty simple I have a view which runs a task in delay and should return immediately some message to the user: class PrintTaskView(View): def get(self, request): logger.debug('ABOUT TO ADD A TASK') tasks.print_task.delay() logger.debug('TASK WAS ADDED') messages.info(request, _('Print task added to queue')) return HttpResponseRedirect(reverse_lazy('admin:index')) I am so confused because this works smooth on my local machine and on the test environment while on production request gets stuck on loading after the first log has been executed. What is even more confusing is that if I run the code from the shell (manage.py shell) then the print task gets created and picked up by a worker and executed. Also celery beat tasks runs smoothly. My celery settings: # Celery CELERY_BROKER_URL = os.getenv('CELERY_BROKER_URL') CELERY_RESULT_BACKEND = os.getenv('CELERY_RESULT_BACKEND') CELERY_BEAT_SCHEDULE = { ... } website/__init__.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) celery.py from __future__ import absolute_import from celery import Celery from django.conf import settings app = Celery('somename') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, related_name='tasks') Any idea or suggestion is more than welcome :) -
mp4 Upload To S3 from external S3 location or presigned url | DJANGO
Currently my client is sending me presigned url and public S3 location of a mp4 video. below is the format { "URL": "https://brytecam-bucket-1.amazonaws.com/video-url", "location": "s3://brytecam-bucket-1/movies/video.mp4" } If I open the URL in browser, it streams the video. I need to transfer this file to my s3 bucket to store it. I need to know is there any way to transfer this mp4 file to my s3 bucket by using any of means i.e S3 location or URL using django. -
getting error Authentication credentials were not provided in django rest framework
Hi Everyone i am creating login api in DRF and getting response also as i expected but i test token to other api then got error Authentication credentials were not provided, i don't know where i am going wrong please help me out.also custom user model can't possible to use because that model i have already used setting.py- this is setting file REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'api.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication' ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework_datatables.renderers.DatatablesRenderer', ), 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework_datatables.filters.DatatablesFilterBackend', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework_datatables.pagination.DatatablesPageNumberPagination', 'PAGE_SIZE': 100, } models.py class GmsUser(GmsBaseModel): first_name=models.CharField(max_length=255,null=True, blank=True) middle_name=models.CharField(max_length=255,null=True, blank=True) last_name=models.CharField(max_length=255,null=True, blank=True) user_name=models.CharField(max_length=255,null=True, blank=True, unique=True) password=models.CharField(max_length=255,null=True, blank=True) token = models.CharField(max_length=255, null=True) class Meta: db_table = "gms_users" def __str__(self): return self.user_name views.py @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def gms_user_login(request): user_name = request.data.get("user_name") password = request.data.get("password") users=GmsUser.objects.filter(user_name=user_name).values_list('id',flat=True) role=GmsRole.objects.filter(id=GmsUserRole.objects.filter(user=users[0]).values_list('role',flat=True)[0]).values_list('role',flat=True)[0] # city=GmsUserProfile.objects.filter(user=users[0]).values_list('city',flat=True)[0] try: query=GmsUserRole.objects.filter(user=users[0]).exists() except Exception as e: return Response({"message":"User not found","error":True,"code":400,"results":str(e)},status=HTTP_400_BAD_REQUEST) if user_name is None or password is None: return Response({'detail': 'Please provide both username and password'}) else: try: if query: user = GmsUser.objects.get(user_name=user_name) except GmsUser.DoesNotExist: return Response({'detail': 'Invalid UserName'}) if user.password.lower() != password.lower(): return Response({'detail': 'Invalid Password'}) user.token=get_random_string(length=50) user.save() response_data=GmsUserSignupSerializer(user).data response_data1=GmsRoleSerializer(GmsRole.objects.get(role=role)).data response_data2=GmsUserProfileSerializer(GmsUserProfile.objects.get(user=users[0])).data response_data['roles']=response_data1 response_data['user_profile']=response_data2 try: return JsonResponse({"message": "login","error":False,"code":200,"results":{'token':user.token,'user':response_data}},status=HTTP_200_OK) except Exception as e: return JsonResponse({"message": "login","error":True,"code":500,"results":str(e)},status=HTTP_200_OK) Login api Response { "message": … -
"Method \"GET\" not allowed." Django
my views.py file: from rest_framework.views import APIView from rest_framework.response import Response from .serializers import UserSerializer class TestView(APIView): def get(self, request, format=None): print("API called") return Response("You did it!", status=200) class UserView(APIView): def post(self, request, format=None): print("User created") user_data = request.data print(request.data) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(raise_exception=False): user_serializer.save() return Response({'user': user_serializer.data}, status=200) return Response({'msg': "error: no user created"}, status=400) # convert user token to user data def get(self, request, format=None): if request.user.is_authenticated == False or request.user.is_active == False: return Response('Invalid credentials', status=403) user = UserSerializer(request.user) print(user.data) return Response("Testing", status=200) my serializers.py file: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework.settings import api_settings class UserSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( required=True, max_length=32, validators=[UniqueValidator(queryset=User.objects.all())] ) first_name = serializers.CharField( required=True, max_length=32 ) last_name = serializers.CharField( required=True, max_length=32 ) password = serializers.CharField( required=True, min_length=8, write_only=True ) def create(self, validated_data): password = validated_data.pop(password, None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token class Meta: model = User fields = ( 'token', 'username', 'password', 'first_name', 'last_name', 'email', 'id' ) my urls.py file: from django.urls … -
django admin Inline model is not storing id for related table
I've combine two models into one in admin panel using admin.TabularInline and following is my code that i've tried as far my knowledge. class ProdutImageTabulurInline(admin.TabularInline): model = ProductImage exclude = ['user', 'name', 'status'] @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [ ProdutImageTabulurInline ] # For Do operation before save operation def save_model(self, request, obj, form, change): obj.user = request.user return super().save_model(request, obj, form, change) # https://stackoverflow.com/questions/59580458/how-can-i-access-model-instance-in-save-related-method-of-modeladmin-class def save_related(self, request, form, formsets, change): obj = form.instance obj.user = request.user super(ProductAdmin, self).save_related(request, form, formsets, change) I've hidden the User field from ProductImages since i want that it should store default user id as logged in user id. So i used save_model for product table and it store user_id as expected but i want that in products image table too, and which is not working -
Correct way to deactive user and its profile in Django
I have created a view where the logged-in user should be able to deactivate its profile. I expect then to see the change being reflected in my admin section, but it's not. Looks like the user is being deactivated but the user.profile isn't. I am puzzled since, after I did a whole project following Django docs, the way to properly manage user deactivation seems missing. I'd like to stay strict to Class-Based-Views. My actual code: # models.py # Model to handle user profiles class Profile(models.Model): """Create user profiles and manage their attributes""" user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=180, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) avatar = models.ImageField(upload_to='social/static/social/avatars/', null=True, blank=True) follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False, blank=True) is_active = models.BooleanField(default=True) def __str__(self): return self.user.username # Signal function to create a profile when a user is created @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: user_profile = Profile(user=instance) user_profile.save() # views.py class ProfileInactive(View): """User can made its profile unactive""" model = models.Profile template_name = 'social/profile_delete.html' # Users can delete only their profile, or get a 404 error def get_queryset(self): owner = self.request.user return self.model.objects.filter(user=owner) def get(self, request, username): profile = get_object_or_404(models.Profile, user__username=self.kwargs['username']) return render(request, self.template_name, {'profile': profile}) def … -
Django + GUnicorn ASGI with SCRIPT_NAME
I have a django application running with a gunicorn ASGI server and a NGINX reverse proxy for serving static content. All packaged within a docker container. Now I want to serve this container behind a reverse proxy with a path prefix, e.g. "mydomain.com/djangoapp/". The problem is, that django doesn't know it's hosted under a subpath and for example the django admin application then aleays redirects to the root path "/" instead of "/djangoapp/". I already read that there are several settings which handle this problem. I tried setting the "FORCE_SCRIPT_NAME" in the django settings directly to "/djangoapp". It worked for the admin login page, but after clicking the login button it redirected to the wrong root "/". I tried setting the "SCRIPT_NAME" environment variable of the gunicorn server to "/djangoapp". It did not apply at all. I'm running now out of ideas what else to try. Does anybody else have a solution for this problem? -
Django:all instances have the same many-to-many field
I have custom user model, and this user has many-to-many field called classes. When the user creates new class I add it to the many-to-many field classes . But the problem is ,not only this user points to added classes but all users created, point to the same classes. How can I organize models such that a when I add class_instance to many-to-many field classes of single user, only this user has those classes. Here is my code models.py class Class (models.Model): key=models.CharField(max_length=256,unique=True); name=models.CharField(max_length=256); def __str__(self): return self.name; class NewUser(AbstractBaseUser,PermissionsMixin): email=models.EmailField(max_length=255,unique=True,default=NULL,) name=models.CharField(max_length=255) surname=models.CharField(max_length=255) is_staff=models.BooleanField(default=False) is_active=models.BooleanField(default=True) is_teacher=models.BooleanField(default=False) classes=models.ManyToManyField(Class) objects=CustomUserManager(); USERNAME_FIELD='email' REQUIRED_FIELDS=['name','surname','is_teacher'] def __str__(self) : return self.name views.py @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def create_class(request): instance=NewUser.objects.all().filter(id=request.user.id) #getting the user from request(I want only this user to have the added class_instance) serializer=ClassSerializer(data=request.data); if serializer.is_valid(): class_instance=serializer.save(); class_instance.save(); instance[0].classes.add(class_instance); #adding the created class to many-to-many class field instance[0].save(); data={ 'id':instance.id } return JsonResponse(data) -
MySql django.db.utils.OperationalError: (1045, "Access denied for user 'userdb'@'localhost' (using password: YES)")
when I used command "python manage.py runserver ,it threw this error.And then I checked the authority of the users. -
Django DRF gettiing ValueError: Field 'id' expected a number but got 'test' error
I am trying to implement a filtering feature in my Django app. I am using DRF and I am getting the following error when I click on any option in my html template: ValueError: Field 'id' expected a number but got 'test'. I was following this post to create this page but I am not sure how to get rid of error. I tried to change the default in my migration file but it didn't help. When I change values_list('client_type__title') to values_list('client_type') everything is fine but it shows id instead of title. migration file class Migration(migrations.Migration): dependencies = [ ('testapp', '0007_team_publish'), ] operations = [ migrations.CreateModel( name='ClientType', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(default='-', help_text='max 150 characters', max_length=150)), ('body', models.CharField(default='-', help_text='max 400 characters', max_length=400, verbose_name='Description')), ('slug', models.SlugField(blank=True, default='')), ('publish', models.DateTimeField(default=django.utils.timezone.now, verbose_name='publish')), ], options={ 'ordering': ('-publish',), 'get_latest_by': 'publish', }, ), migrations.AddField( model_name='product', name='client_type', field=models.ManyToManyField(blank=True, related_name='client_type_product', to='testapp.ClientType', default='-'), ), ] models.py class ClientType(models.Model): title = models.CharField(max_length=150, default='-', blank=False, null=False, help_text='max 150 characters') body = models.CharField(verbose_name ='Description', max_length=400, default='-', blank=False, null=False, help_text='max 400 characters') slug = models.SlugField(default='', blank=True) publish = models.DateTimeField('publish', default=timezone.now) def __str__(self): return str(self.title) class Product(models.Model): id = models.AutoField(primary_key=True) title = models.CharField('title', max_length=400, blank=False, null=False, help_text='max 400 characters', default='') client_type …