Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
by inheriting the class base view, my own form does not work in django
I write my own login form inheriting LogonView, with my own Form. My own form does not have a password field! because I send a temperory password to the email given by a user. But when I inherit LoginView, the form has 2 fields : username and password. If I inherit CreateView instead of LoginView, instead of displaying profile, it returns: User matching query does not exist. I am newdeveloper. Your help is appreciated. -
Django Rest Framework: KeyError when Overriding 'update' Function in a Serializer
I have a User model and a Group model, which are presented below: class User(models.Model): username = models.CharField(primary_key=True, max_length=32, unique=True) user_email = models.EmailField(max_length=32, unique=False) user_password = models.CharField(max_length=32) user_avatar_path = models.CharField(max_length=64) class Group(models.Model): group_id = models.AutoField(primary_key=True) group_name = models.CharField(max_length=32, unique=False) group_admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='my_groups') members = models.ManyToManyField(User, related_name='groups', through='UserGroup') Every group can have multiple users associated with it and every user can be associated to multiple groups, which is modeled with a ManyToManyField and a through model between the models. When I create a group, the user which creates the group is automatically assigned as the group admin and therefore added as a member of the group: class MemberSerializer(serializers.ModelSerializer): # The nested serializer used within the GroupSerializer username = serializers.ReadOnlyField(source='user.username') class Meta: model = User fields = ['username'] class GroupSerializer(serializers.ModelSerializer): members = MemberSerializer(source='user_groups', many=True, required=False) group_admin = serializers.SlugRelatedField(slug_field='username', queryset=User.objects.all()) # A Group object is related to a User object by username class Meta: model = Group fields = ['group_id', 'group_name', 'group_admin', 'members'] def create(self, validated_data): # Overriden so that when a group is created, the group admin is automatically declared as a member. group = Group.objects.create(**validated_data) group_admin_data = validated_data.pop('group_admin') group.members.add(group_admin_data) return group def update(self, instance, validated_data): members_data = validated_data.pop('members') # … -
Function of defining an absolute URL in a model in Django
I am currently completing the final capstone project for Django on Codecademy, and I've come across a comprehension issue. On Codecademy, they state that it's used to redirect to the homepage when a user submits data, while the Django documentation for get_absolute_url seems to make no reference to redirects. I currently have no absolute urls defined for any of my models, and these are my url patterns and views. At this stage, I'm just trying to understand the purpose of defining an absolute URL in a model, and where the appropriate places to utilize it are. I'm very confused about it's function currently, and would appreciate a simplified explanation with examples. -
Django Rest API is producing 500 status code
I am tasked with creating a Django Rest API containing a serializer. Here is the specific instructions: Instructions Here is my model.py: from django.db import models class Wish(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100,blank=True,default='') wishtext = models.TextField() class Meta: ordering = ('created',) My serializers.py: from rest_framework import serializers from wishes.models import Wish #Add WishSerializer implementation here class WishSerializer(serializers.Serializer): created = serializers.DateTimeField() title = serializers.CharField(max_length=100, default='') wishtext = serializers.CharField() my views.py: from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse,HttpResponse from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse,HttpResponse from rest_framework.response import Response from rest_framework.parsers import JSONParser from wishes.models import Wish from wishes.serializers import WishSerializer @csrf_exempt def wish_list(request): pass """ List all wishes or create a new wish """ if request.method == 'GET': qs = Wish.objects.all() serializer = WishSerializer(qs, many=True) return Response(serializer.data) if request.method == 'POST': serializer = WishSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) @csrf_exempt def wish_detail(request,pk): pass """ Retrieve, update or delete a birthday wish. """ try: wish = Wish.objects.get(pk=pk) except Wish.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = WishSerializer(wish) return Response(serializer.data) elif request.method == 'PUT': serializer = WishSerializer(instance=wish, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) elif request.method == 'DELETE': wish.delete() return Response(status=204) and my url.py: from django.conf.urls import url … -
question about counting time calculated by property
I have created a date and time delta property. this property calculates the total time between two date and times for a job. Now I want to create a property that sums all the time of the jobs and represents it on a card. I have tried many ,but no success. Hopefully someone has a solution @property def Get_time_diference(self): start_time = self.date end_time = self.dateTo total = end_time - start_time return total -
Google Book api , gTTs, googletrans, PyPDF4
I have used Google Book API, gTTs, googletrans, and PyPDF4 in my Django Project. I am trying to draw a Deta Flow Diagram of my project. I am confused about the diagram should I draw like please help me to figure it out -
Which database in the backend should be used for a personal website/blog? [closed]
I want to create a personal website (to learn) and post there various articles. I wonder if I need a database to store these articles. I think it would be nice to have them stored somewhere separately instead of e.g. straight in the hmtl files. Then it would be possible to port these articles elsewhere. However I do not have enough practical knowledge to choose a sensible approach. Right now I am thinking of using SQLite. However, I also want the visitors of my website to leave comments, so to store those I assume I would need something bigger/better? Main points: there will be some dynamic content such as comments from users I do not want to allow visitors to register or port articles, only comment I want visitors to "log in" (to be able to leave a comment) via their social media accounts e.g. Google account I realise these comment and the visitors login information needs to be stored somewhere What is the sane approach to have a database for the personal website? -
Handling an Items catalogue with variable attributes
I am a beginner to Django and I have more of a conceptual question (so I have no code yet). I am currently trying to assemble a catalogue of items through a model called Item. One of the fields that I have in this Model is item_type. Each item_type will have different relevant properties(which in this case would be fields). For example, if it is a pump I would be interested in the nominal pressure, but if it is a boiler I am interested in the heating capacity. What would be the best way of approaching such a case? I was thinking about two solutions: Adding all the possible properties in the Item model and only filling in the relevant ones. However, this would create a problem as I do not want to show the user all these fields when creating a new item through the form. Ideally, I would like to have only a few fields that are common (the name of the item for example), and then, after selecting the item_type the form is extended with the relevant fields of that component type. However, I am not sure how I would be able to achieve this exactly and … -
CSS file don't connecting with HTML (Django)
index.html I have changed {% static "/main/css/index.css" %} to {% static "main/css/index.css" %} {% extends 'main/base.html' %} {% load static %} <link rel = 'stylesheet' type="text/css" href="{% static "/main/css/index.css" %}"/> {% block title %} {{title}} {% endblock %} {% block content %} <body> <div class="grid-wrapper"> <header class="grid-header"> <img class="circles" src="{% static "main/img/main8.jpg" %}" alt="main pic"> <p>hello</p> </header> </div> </body> {% endblock %} index.css .grid-wrapper { display: grid; grid-template-columns: 1 fr; grid-template-rows: 1 fr; grid-template-areas: 'header header'; } .circles { display: block; margin-left: auto; margin-right: auto; } header { position: relative; width: 100%; } p { color: red; text-align: center; position: absolute; width: 100%; text-align: center; top: 0; } settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "main/static"), ] [file's location] I tried changing file names, changing locations, connecting in a different way, but all this does not work. I also changed the settings. -
Why I'm Getting error when I run workon command?
I'm Totally newb in Django! everytime I get error when I run workon even I install workon module but it didn't help me whenever I run python -m workon test it shows me No module named workon! any solution? best regards Nafiz -
dj-rest-auth Reset email link keeps pointing to the backend
I'm using dj-rest-auth with react and i'm trying to use the frontend url instead of the backend url. The solution i am using for the account creation confirmation email affects the reset password email too but only partially. It does not effect the port. It only tries to add a key to the reset link where there is none and throws me an error. So i was wondering if there is a way to change the url from port 8000 to port 3000. This is what i have tried: class AccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request: HttpRequest): return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) def send_mail(self, template_prefix, email, context): if settings.DEBUG: context["activate_url"] = ( "http://localhost:3000/accounts/confirm-email/" + context["key"] ) else: context["activate_url"] = ( settings.FRONTEND_URL + "/accounts/confirm-email/" + context["key"] ) return super().send_mail(template_prefix, email, context) If i get rid of the key part it doesn't give me an error but keeps port 8000 and breaks my account confirmation emails. If i don't get rid of the key it gives me: django | "http://localhost:3000/accounts/confirm-email/" + context["key"] django | KeyError: 'key' -
Django contenttypes follow/unfollow
Trying to use contenttypes to store following relations of users. I can create a follow, but I can't remove a follow from the database. Model Code accounts app ------------ from activities.models import Activity class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) follow = GenericRelation(Activity) activities app -------------- class Activity(models.Model) FOLLOW = 'F' LIKE = 'L' ACTIVITY_TYPES = [ (FOLLOW, 'Follow'), (LIKE, 'Like'), ] ## stores the user_id of the Liker/Follower user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ## stores 'F' or 'L' activity_type = models.CharField(max_length=2, choices=ACTIVITY_TYPES) date = models.ForeignKey(ContentType, on_delete=models.CASCADE) ## stores CustomUser id of the user who is followed or the id of the post that is liked object = models.UUIDField(null=True, blank=True, db_index=True) content_object = GenericForeignKey('content_type', 'object_id') class Meta: indexes = [models.Index(fields=["content_type", "object_id"]),] View Code follower = User.objects.get(id=follower_id) followed = User.objects.get(id=followed_id) ## This is the contenttypes model a = Activity.objects.filter(user=follower.id, object_id=followed.id) ## This is my janky way of checking whether the follower is already following the followed if len(a) == 0: ## This works to create a follow followed.follow.create(activity_type=Activity.FOLLOW, user=follower) I thought this might work to delete the follow followed.follow.remove(a) but it gives me an error 'QuerySet' object has no attribute 'pk' -
The current path, accounts/login/, didn't match any of these
Ive been trying to implement the reset password processs of django but something is not working, I know from the error that there is a url pattern that does not exit but from where accounts/login came from,It worked fine before but my colleague took my laptop and after that this happened urls.py """travel URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.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 path,include from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('',include('loginpage.urls')), path('signup/',include('signup.urls')), path('homepage/',include('Homepage.urls')), path('password_reset/',auth_views.PasswordResetView.as_view(template_name='loginpage/resetpassword.html'),name='password_reset'), path('password_reset_sent/',auth_views.PasswordResetDoneView.as_view(template_name='loginpage/password_resent_sent.html'),name='password_reset_done'), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='loginpage/password_reset_form.html'),name='password_reset_confirm'), path('Password_changed_succesfully/',auth_views.PasswordResetConfirmView.as_view(template_name='loginpage/password_reset_done.html'),name='password_reset_complete') ] resetpassword.html: <!DOCTYPE html> <html> <head> {% load static %} <title>Reset Password</title> <link rel="stylesheet" type="text/css" href="{% static 'reset.css' %}"> <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css" /> </head> <body> <div class="right"><img src="{% static 'images/logo2.png' %}" height="400" width="400"></div> <div class="main"> <input type="checkbox" id="chk" aria-hidden="true"> <div class="resett"> <form … -
Iam Created Login Form but here If I login twice only it redirects the page in django
Here My Html Code I am created an Login Form Here my action is empty if I give an URL in action means. Then I will submit means it will goes to next page without authentication. Please Help me out...If I am login means it will redirect to the Page Dash. But here i want to login twice only means then it works successfully...If I login only once means it does'nt redirect the page I don't know why <form action="" method="post"> {%csrf_token%} <div class="form-outline mb-4"> <input type="text" name="username" id="form3Example3" class="form-control form-control-lg" class="form-control new-input" placeholder="Enter a Name" required> <label class="form-label" for="form3Example3"></label> </div> <div class="form-outline mb-3"> <input type="password" name="password" id="form3Example4" class="form-control form-control-lg" placeholder="Enter password" required> <label class="form-label" for="form3Example4"></label> </div> <div class="d-flex justify-content-between align-items-center"> <div class="form-check mb-0"> <input class="form-check-input me-2" type="checkbox" value="" id="form2Example3" /> <label class="form-check-label" for="form2Example3">Remember me</label> </div> <a href="#!" class="text-body">Forgot password?</a> </div> <div class="text-center text-lg-start mt-4 pt-2"> <input type="submit" value="submit" class="register-button2" /> </form> <p class="small fw-bold mt-2 pt-1 mb-0">Don't have an account? <a href="{% url 'register'%}" class="link-danger">Register</a></p> </div> Views.py def Login(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] user=auth.authenticate(username=username,password=password) if user is not None: request.session['user'] = username auth.login(request,user) print(user) return redirect('Dash') else: messages.info(request,'invalid credientials') return redirect('Login') else: return render(request,'Login.html') This is the Dash View … -
Registration data "lost" somewhere in python django 4
I have my super basic authentication app, and I tried to write a simple Registration with email, first name, last name and (logically) password, but it seems that when I enter my request data it is "lost" somewhere. When I press the "POST" button, all the fields are blank and it says: "This field is required". I've been trying to figure it out for quite a long time, but I am new to django. I hope you can spot the problem. Here is my models.py: class UserManager(BaseUserManager): def create_user(self, first_name, last_name, email, password=None): if first_name is None: raise TypeError('Users must have a first name') if last_name is None: raise TypeError('Users must have a last name') if email is None: raise TypeError('Users must have an email') user = self.model(email=self.normalize_email(email), first_name=first_name, last_name=last_name) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager My serializers.py: class RegistrationSerializer(serializers.ModelSerializer): token = serializers.CharField(max_length=255, read_only=True) class Meta: model = User fields = ['first_name', 'last_name', 'email', 'password', 'token'] def create(self, validated_data): return User.objects.create_user(**validated_data) And my views.py: class RegistrationAPIView(APIView): permission_classes = (AllowAny,) serializer_class = RegistrationSerializer def … -
How to add custom field when verifying access token in rest_framework_simplejwt
I tried to override validate method at TokenVerifySerializer but this raises AttributeError. from rest_framework_simplejwt.serializers import TokenVerifySerializer from rest_framework_simplejwt.views import TokenVerifyView class CustomTokenVerifySerializer(TokenVerifySerializer): def validate(self, attrs): data = super(CustomTokenVerifySerializer, self).validate(attrs) data.update({'fullname': self.user.fullname}) return data class CustomTokenVerifyView(TokenVerifyView): serializer_class = CustomTokenVerifySerializer But that does work when using TokenObtainPairSerializer and TokenObtainPairView. The above snippet raises AttributeError with 'CustomTokenVerifySerializer' object has no attribute 'user'. -
'settings.DATABASES improperly configured. Please Supply the ENGINE value' - when adding legacy database
I've added a second databases and i've connected it to apps via routers... all works well, i can access the data via the admin panel for the respective models and fields as specificied in my models.py in the apps.. perfect. One issue is when i run python manage.py migrate, I get an error saying django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Database code in settings.py: DATABASES = { 'default': { }, 'auth_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'network_db':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'Network.sqlite3', }, 'simulation_db':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'Simulation.sqlite3', } } manage.py diffsettings command DATABASES = {'default': {'ENGINE': 'django.db.backends.dummy', 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None, 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}}, 'auth_db': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': WindowsPath('C:/Users/backend/db.sqlite3')}, 'network_db': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': WindowsPath('C:/Users/backend/Network.sqlite3')}, 'simulation_db': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': WindowsPath('C:/Users/backend/Simulation.sqlite3')}} I've followed the documentation exactly which is how i've connected the legacy database and i'm able to access the data via admin panel.. however i am not sure what i'm doing wrong to cause the error when running python manage.py … -
Django / How to get the primary key from a specific field?
Models.py class scenes(models.Model): name = models.CharField('Event name', max_length=120) record_date = models.DateTimeField('Event date') Let's say I have recorded a scenes with name="world" In views.py, how can I query the pk from the name field ? from .models import scenes scene = scenes.objects.get('what should I put here to get the pk associated with name World ?') -
How can i use spreadsheets in your website
am trying to come up with a way to use spreadsheet in my website like i gather information from logged in users into the spreadsheet.any idea how iwill archive this or what tool to use or plugin in html .am using django as s backend language. -
'Page not found' error in Django code while making the pipeline
I am trying to make an e-commerce website in django. I want to lay the rough pipeline using this code but when i search, for example- http://127.0.0.1:8000/shop/about - This 404 Error come on my screen. Please tell me what to do. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/shop/about Using the URLconf defined in ekona.urls, Django tried these URL patterns, in this order: admin/ shop [name='ShopHome'] shop about [name='about'] shop contact/ [name='ContactUs'] shop tracker/ [name='Tracker'] shop search/ [name='Search'] shop prodview/ [name='ProdView'] shop checkout/ [name='Checkout'] blog The current path, shop/about, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. My settings.py is - """ Django settings for ekona project. Generated by 'django-admin startproject' using Django 4.0.4. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # 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.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! … -
I have a structural problem with my user management code in django
I'm new to django. I'm trying to make a custom user management in django admin. I have an admin,py like this. """ from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .forms0 import UserCreationForm, UserAdminChangeForm from .models import User #from django.contrib import apps.authentication.models import apps.site.register(model) Register your models here. class UserAdmin(BaseUserAdmin): search_fields = ['employee', 'username'] add_form = UserAdminCreationForm form = UserAdminChangeForm list_display = ('username', 'employee', 'admin', 'staff', 'active') list_filter = ('admin', 'staff', 'active') """ It calls form0.py first before my model.py """ add_form = UserAdminCreationForm form = UserAdminChangeForm """ Models.py """ from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, UserManager class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True, null=False, blank=False, verbose_name='Username') employee = models.OneToOneField('Employee', null=True, blank=True, verbose_name='Employee ID', related_name='user', on_delete=models.PROTECT) admin = models.BooleanField(default=False) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) """ form0.py """ from django import forms from django.db import models from .models import User class UserAdminCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'employee', 'admin', 'active', 'staff', 'groups') """ I get this error When I migrate it loads forms0 … -
DRF serializer's BooleanField returns null for empty ForeignKey field
I want to add boolean fields has_video and has_gallery to my serializer. Their values should be true if the ForeignKey fields of MyModel (video, gallery) have values, otherwise these values should be set to false. models.py class MyModel(models.Model): video = models.ForeignKey( to='videos.Video', null=True, blank=True, on_delete=models.SET_NULL, ) gallery = models.ForeignKey( to='galleries.Gallery', null=True, blank=True, on_delete=models.SET_NULL, ) serializers.py class MyModelSerializer(serializers.ModelSerializer): has_video = serializers.BooleanField(source='video', default=False) has_gallery = serializers.BooleanField(source='gallery', default=False) The problem occurs when the video or gallery value of MyModel object is null. I expect the returned values to be false but it is null. "has_video": null, "has_gallery": null, I try to set allow_null parameters to false but the result is the same (the values are still null). has_video = serializers.BooleanField(source='video', default=False, allow_null=False) has_gallery = serializers.BooleanField(source='gallery', default=False, allow_null=False) When the video or gallery is not null, the serializer's fields return true as I expect. The problem is just about null/false values. -
Uncaught ReferenceError: $ is not defined in Javascript
i am getting this error message when trying to submit a form in django using ajax i cannot really tell what is bringing up this error. i have tried many solutions but they dont seem to be working as expected. this is the exact error showing up in my console csrfmiddlewaretoken=tHTBQbePA8SQrkk9SL18uCsPCIYLE5rey9dFd8vKUhlQDYbh2vLNC5Y5gl3QNXue&full_name=&bio=&email=&phone=:39 Uncaught ReferenceError: $ is not defined at ?csrfmiddlewaretoken=tHTBQbePA8SQrkk9SL18uCsPCIYLE5rey9dFd8vKUhlQDYbh2vLNC5Y5gl3QNXue&full_name=&bio=&email=&phone=:39:7 index.html <title>Django Form Submission</title> </head> <body> <div class="container"> <h1 class="text-center mt-5">Create Profile</h1> <h5 class="text-success text-center"></h5> <form class="container mt-5" id="post-form"> {% csrf_token %} <div class="mb-3 mr-5 "> <input type="text" class="form-control" id="full_name" name="full_name" placeholder="Full Name"> </div> <div class="mb-3 mr-5 "> <input type="text" class="form-control" id="bio" name="bio" placeholder="Bio"> </div> <div class="mb-3 mr-5 "> <input type="email" class="form-control" id="email" name="email" placeholder="Email Address"> </div> <div class="mb-3 mr-5 "> <input type="text" class="form-control" id="phone" name="phone" placeholder="Phone"> </div> <button type="submit" class="btn btn-success">Submit</button> </form> </div> <script type="text/javascript"> $(document).on('submit', '#post-form', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '/create', data: { full_name: $('#full_name').val(), bio: $('#bio').val(), email: $('#email').val(), phone: $('#phone').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, success: function (data) { ("h5").html(data) } }) }) </script> </body> </html> views.py from django.shortcuts import render from core.models import Profile from django.http import HttpResponse def index(request): return render(request, 'index.html') def create(request): if request.method == 'POST': full_name = request.POST['full_name'] bio = request.POST['bio'] … -
Serialization Issue Django in filefield
I have an issue when I am trying to get the list of my stored data in Django. Output: {name:/filename, evaluation: "not evaluated"} I am able to get my database content, but I have a "/" before each name value. My question is: How can I do to remove this /? Here is a copy of my code. Thanks for your help class myModel(models.Model): name=models.FileField(storage=fs) evaluation=models.CharField(max_length=256,default="Not evaluated") def list(self, request, *args, **kwargs): queryset = myModel.objects.all() serializer = mySerializer(queryset, many=True) return Response(serializer.data) class mySerializer(serializers.ModelSerializer): class Meta: model = myModel fields = ('name','evaluation') -
I want to assign value of logged in user's user_company to the user_company field of the newly created user
When a user creates a user record for a client, the new client should should have the current logged in user's User.user_company value. In the problem here, I want to assign the value of the logged in user's User.user_company into the new user's clientuser.user_company when save() is called in the view. here is the serializer below with the clientuser object. class ClientSerializers(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) client_name = serializers.CharField(style={'input_type' : 'text'}, required=True) class Meta: model = User fields = ['email', 'username', 'password', 'password2', 'user_type', 'client_name'] extra_kwargs = { 'password': {'write_only': True}, #dont want anyone to see the password 'user_type': {'read_only': True}, } def save(self): clientuser = User( #creating a user record. it will record company fk email=self.validated_data['email'], username=self.validated_data['username'], user_type = 3, first_name = self.validated_data['client_name']) #validating the password password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: #trying to match passwords. raise serializers.ValidationError({'password': 'Passwords must match.'}) clientuser.set_password(password) #setting the password clientuser.save() #saving the user return clientuser I've tried using cur_usr = User() param = 'user_company' usr_comp = getattr(u, param) print(f'usr_comp is {usr_comp}) print statement prints usr_comp is None in the terminal I've also tried using curr_User_Company = User.user_company user.user_company = curr_User_Company it returns the following line in the terminal …