Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have an error Dockerfile with Django . How to solve it?
Docker file doesn't work ! Dockerfile # Pull base image FROM python 3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /Django/bookstore/ #Install dependencies COPY Pipfile Pipfile.lock /Django/ RUN pip install pipenv && pipenv install --system #COPY project COPY . /Django/bookstore/ Docker-compose.yml version: '3.8' services: web: build: . command: python /Django/manage.py runserver 0.0.0.0:8000 volumes: - .:/Django ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: About Django My directory called /Django/bookstore/ Python version 3.8.5 When I am coding Docker on cmd I see an error docker-compose up -d --build Building web ERROR: Dockerfile parse error line 2: FROM requires either one or three arguments -
How to set a list of default serializer instances?
I have some serializers class FruitSerializer(serializers.Serializer): id = serialiser.IntegerField() name = serializers.CharField() class BucketSerialiser(serializers.Serializer): id = serialiser.IntegerField(required=False, default = 1) fruits = FruitSerializer(required=False, many=True) And i want to set default values in the BucketSerialiser.fruits if initially they were not set. For example bucket = BucketSerialiser(data={'id': 1}) ... buket.data -> // it should return the default fruits data. e.g {'id': 1, 'fruits': [{'id': 1, 'name': 'Apple'}, {'id': 2, 'name':'Orange'}]. I tried to do it like this class BucketSerialiser(serializers.Serializer): id = serialiser.IntegerField(required=False, default = 1) fruits = FruitSerializer(required=False, many=True, default = [ FruitSerializer(data={'id': 1, 'name': 'Apple'}), FruitSerializer(data={'id': 2, 'name': 'Orange'})] But it doesn't work. How to implement it correctly? -
assigning additional variables to form in Django
I have a simple application draft where I would like to have three functionalities : priority list for every production line with 3 part number assigned to it ( and number of pieces for each ) order where I can select production line when submitting new order via form I would like to check the priority list and assign the appropriate part number based on the quantity left in stock to the order form. Also I would like to subtract value of 1 from the number of pieces Now, I have the first two and I assume they are not perfect (maybe you can suggest some tweaks). But how can I add the third functionality ? views.py def priority(request): priority_form = PriorityForm() if request.method == 'POST': priority_form = PriorityForm(data=request.POST) if priority_form.is_valid(): priority_form.save() return redirect('priority') else: priority_form = PriorityForm() return render(request, 'dashboard/priority.html', {"form": priority_form}) def order(request): storage = PartNumber.objects.all() username = request.user.username if request.method == 'POST': order_form = OrderForm(username=username, data=request.POST) if order_form.is_valid(): order_form.save() return redirect('order') elif request.method == 'GET': order_form = OrderForm(username=username) return render(request, 'dashboard/order.html', {"form": order_form, "username": username}) forms.py class OrderForm(forms.ModelForm): class Meta: model = Order fields = ('end_user_id', 'production_line_id') def __init__(self, *args, **kwargs): username = kwargs.pop('username', None) super(OrderForm, self).__init__(*args, … -
Django approval model form: how to show both new and old values in admin panel?
I've a model and I want to let users suggest changes on its objects. My approach was to create a separate model and let the admin approve the changes. class SuggestedQuoteChanges(AbstractQuote): original_quote = models.ForeignKey(Quote, on_delete=models.CASCADE) user_email = models.EmailField() justification = models.TextField() def get_changes_fields(self): changes = tuple() # a bit of code... if original_value != new_value: changes += (field.name,) return changes In admin.py I want to show both values, but, at the moment, I only managed to show show the suggested values: class SuggestedQuoteChangesAdmin(admin.ModelAdmin): fieldsets = ( ( "Changes", { "classes": ("collapse",), "fields": (), }, ), (None, {"fields": ("justification", "user_email")}), ) readonly_fields = ("user_email", "justification") def get_fieldsets(self, request, obj=None): fieldsets = super().get_fieldsets(request, obj) fieldsets[0][1]["fields"] = obj.get_changes_fields() return fieldsets I've tried to use __getattr__ in the model to get something like obj.original_quote_field but was unsuccessful. First of all, creating a separate model is the best approach? If yes, how to show both original and suggested values in the admin panel? If no, what approach would you suggest? -
Type 'manage.py help <subcommand>' for help on a specific subcommand
On running python file python3 manage.py in ubuntu terminal i am getting this error. Type 'manage.py help <subcommand>' for help on a specific subcommand. Available subcommands: [auth] changepassword createsuperuser [contenttypes] remove_stale_contenttypes [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver [sessions] clearsessions [staticfiles] collectstatic findstatic runserver This project contains the files of python, django, selenium and matplotlib. Project is based on COVID-19 data visualization. Please help me in solving it. -
While updating records in django check whether the newly entered data is already matching with the other records in database?
forms.py class RoleForm(forms.ModelForm): class Meta: model = Group fields = ['name'] def clean_name(self): name = self.cleaned_data['name'] if Group.objects.filter(name__iexact=name).exists(): raise forms.ValidationError("Role name already exists") return name views.py def updateroles(request, id): roles = Group.objects.all() instance = get_object_or_404(Group, pk=id) if request.method == "POST": fm = RoleForm(request.POST, instance = instance) if fm.is_valid(): fm.save() messages.success(request, 'Updated Successfully') return redirect('roles') else: fm = RoleForm(instance=instance) return render(request, 'crm/roles.html', {'form': fm, 'roles': roles}) While adding new records I want to check whether the records already exists in database.If it exist I need to raise a ValidationError which is working fine.But while updating records check whether the newly entered data is not matching with any other records,if it matches I need to raise a ValidationError like newly entered data matches with some other record.My current code is raising a validationerror even if I click on update without changing the existing data.Any help would be appreciated. -
python: can't open file '.manage.py': [Errno 2] No such file or directory
Im learning django and i get this error: python: can't open file '.manage.py': [Errno 2] No such file or directory when running python .\manage.py makemigrations I know im running the command in the same folder as my manage.py file, so what can be the issue? This is my directory tree: . ├── api │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py └── music_controller ├── asgi.py ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py -
Creating a new user in a django project is not working properly
I am trying to have a user project where users can create a profile. After registration the user is created in the backend but it returns an error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/profile/ The user is logged in but I don't know the reason and how to fix this error. Here is the models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' here is the views.py: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) Here is the urls.py in the main project: urlpatterns = [ path('admin/', admin.site.urls), path('', include('post.urls')), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset............) ] What is the reason for directing to Request URL: … -
Execute a function when certain conditions are met
my django app have a function which is send_sms, I also want to have a automatic sms auto_sms function. when conditions are met on my data models. @views.py def send_sms(request): z = Rainfall.objects.latest('timestamp') numbers = Mobile.objects.all() message = ('Test Message') account_sid = '**************' auth_token = '**************' client = Client(account_sid, auth_token) for i in numbers: client.messages.create(to=i.mobile_number, from_='**************', body=message) return HttpResponseRedirect('/success/', 200) def auto_sms(request): responses = Rainfall.objects.filter( level='Torrential' or 'Intense', timestamp__gt=now() - timedelta(days=1), sms_sent=False, ) if responses.count() >= 10: send_sms(request) responses.update(sms_sent=True) @models.py class Rainfall(models.Model): level = models.CharField(max_length=10, blank=True, default='') amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) Now I'm testing it, that when auto_sms detects multiple(10) 'Torrential or Intense' entries into the database within a day. It must automatically execute send_sms but instead its returning an error: Cannot resolve keyword 'sms_sent' into field. Choices are: amount, id, level, timestamp what am I missing here? please help. Thanks! -
Serializer not passing complete information to API view
I created a serializer which the "user" below is from another Serializer which i imported, now the imported serializer(PubliceProfileSerializer) works fine on its own but it does not display the content of USER when i call it my browser from this serializer. Every other item shows except the user. Please help from rest_framework import serializers from users.api.serializers import PublicProfileSerializer from blog.models import Post class PostSerializer(serializers.ModelSerializer): user = PublicProfileSerializer(source='users.profile', read_only=True) category = serializers.SerializerMethodField() label = serializers.SerializerMethodField() class Meta: model = Post fields = '__all__' def get_category(self, obj): return obj.get_category_display() def get_label(self, obj): return obj.get_label_display() -
ManyToMany with Django Forms & Select2
I'm going to describe this issue to the best of my ability, I've been stuck trying to solve this for over 8 hours now and any insight is very much appreciated. My conclusion of the error is at the end of this post. Here are snippets of code pertaining to the issue: forms.py class AddActivityForm(ModelForm): class Meta: model = Activity fields = ['activity','tagsAssociated'] views.py def addactivity(request): if request.method == 'GET': return redirect(activitymanagement) else: form = AddActivityForm(request.POST) form = form.save(commit=False) #Checking if the activity exists activityExistsCheck = ActivityTbl.objects.filter(createdBy=request.user,activity=form.activity) if activityExistsCheck: print("Activity already exists!") else: form.createdBy = request.user form.save() print("Activity added") return redirect(activitymanagement) models.py class Activity(models.Model): activity = models.CharField(max_length=100) tagsAssociated = models.ManyToManyField(Tag) createdBy = models.ForeignKey(User, on_delete=models.CASCADE) createdOn = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.activity) form_template.html (aka activitymanagement.html) <script> //Script to POST Activity and Associated Tags function postActivityNTag(){ var activityName = document.getElementById("activityName").value; var tagsAssociated = $('#tagsAssociated').select2('data'); var actionForm = ("/activitymanagement/add"); document.getElementById('addNewActivityForm').action = actionForm; document.getElementById('addNewActivityForm').submit() }; </script> <form id="addNewActivityForm" action="{% url 'addactivity' %}" method="POST"> {% csrf_token %} <div class="input-group"> <input placeholder="Create a new activity" type="text" id="activityName" name="activityName" class="form-control" maxlength="100"/> &nbsp <select class="js-example-basic-multiple" id="tagsAssociated" name="tagsAssociated" multiple="multiple"> {% for tag in allTags %} <option value="{{ tag.id }}">{{ tag.tag }}</option> {% endfor %} </select> <button class="btn btn-success btn-sm" … -
Crispy Form (Other Languages) - DJANGO
We are building a platform with Django and used crispy forms which helped us a lot. But our customer does not speak English and we need everything to be in Turkish, tried googling but could not find a lot of answers. Any other tool I can use which could help? Thanks Onur -
Cannot assign "(<User: admin>,)": "Event.owner" must be a "User" instance
This is weird. I have this code: from django.contrib.auth import get_user event.owner = get_user(request), event.save() In the model, owner is a ForeignKey to the User model. At first, I tried assigning it directly to request.user (as I've done all the times). I am not sure why I get this error: Cannot assign "(<User: admin>,)": "Event.owner" must be a "User" instance. -
How can i get the username id in th databas?
I would like to know why the username_id didn't registred in the database , when I use : username = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) I have (username_id= NULL)enter image description here but when I modified it by : username = models.OneToOneField(User,on_delete=models.CASCADE) I have this message : "IntegrityError at /Patformpage (1048, "Column 'username_id' cannot be null"),How can I resolve this problem , I need your help please. Thank you in advance. This is the code of forms.py class PatForm(forms.Form): nom= forms.CharField(widget=forms.TextInput(attrs={'placeholder':'First_name'})) prénom = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Last_name'})) cin = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'CIN'})) sexe = forms.CharField(widget=forms.Select(choices= sexe)) date_de_naissance = forms.DateField(widget=NumberInput(attrs={'type': 'date'})) quartier = forms.CharField(widget=forms.Select(choices= quartiers)) This is the code of models.py class Patient(models.Model): username = models.OneToOneField(User,on_delete=models.CASCADE) nom = models.CharField("Nom ",max_length=30) prénom = models.CharField("Prénom ", max_length=30) cin = models.CharField("C.I.N ", max_length=10) date_de_naissance = models.DateField(null=True, blank=True) sexe = models.CharField(max_length=10, choices=sex_types, default='1') quartier = models.CharField(max_length=20, choices=quartier_types, default='0') def __str__(self): return self.prénom + ' ' + self.nom This is the code of views.py def Patformpage(request): form = PatForm(request.POST) context = { "form": PatForm } if request.method == 'GET': return render(request, 'base_app/inscription-finale-patient.html', context) elif form.is_valid() : newform= Patient(nom=form.cleaned_data['nom'], prénom=form.cleaned_data['prénom'], cin=form.cleaned_data['cin'], date_de_naissance=form.cleaned_data['date_de_naissance'], sexe=form.cleaned_data['sexe'], quartier=form.cleaned_data['quartier']) newform.save() return redirect('accueil') -
Django create ForeignKey object on parents creation
I have a model with a FK relation: class PNotification(models.Model): id = models.AutoField(primary_key=True) #... booleans with default to come class Product(models.Model): notification_object = models.ForeignKey(PNotification, unique=True, on_delete=models.CASCADE) I get an error: You are trying to add a non-nullable field 'notification_object' to product without a default The only way to create a default 'complex' object I found was get_or_create, but if I use this I need to pass an ID, resulting in each product getting the same PNotification. How can I give each Product an individual PNotification, when a Product model is created? -
¿Como Puedo hacer un insert into en DJANGO? [closed]
tengo una tabla llamada T_EXPERIENCIA con llave compuesta ( correxp(PK) y codpers(PFK)), el codpers viene de la tabla empleado , entonces lo que quiero saber es como inserto mis datos utilizando una sentencia INSERT INTO EN Django , porque he intentado insertar con los modelos de Django , sin embargo no me permite repetir el correxp , pero en SQL Sí me permite , como podría hacer? adjunto mis modelos implicados en este caso class TExperiencia(models.Model): correxp = models.IntegerField(primary_key=True) codpers = models.ForeignKey(TEmpleado, models.DO_NOTHING, db_column='codpers', blank=True, null=True) lugartrabajo = models.CharField(max_length=100, blank=True, null=True) destrabajo = models.CharField(max_length=2000, blank=True, null=True) contrato = models.CharField(max_length=400, blank=True, null=True) fecini = models.DateField(blank=True, null=True) fecfin = models.DateField(blank=True, null=True) nromeses = models.IntegerField(blank=True, null=True) nrodias = models.IntegerField(blank=True, null=True) motivoretiro = models.CharField(max_length=30, blank=True, null=True) codprof = models.ForeignKey('TProfesiones', models.DO_NOTHING, db_column='codprof', blank=True, null=True) vigente = models.CharField(max_length=1, blank=True, null=True) class Meta: managed = False db_table = 't_experiencia' class TEmpleado(models.Model): codpersona = models.OneToOneField('TPersona', on_delete=models.CASCADE, db_column='codpersona', primary_key=True) direcc = models.CharField(max_length=100, blank=True, null=True) celular = models.CharField(max_length=33, blank=True, null=True) hobby = models.CharField(max_length=2000, blank=True, null=True) foto = models.BinaryField(blank=True, null=True) fecnac = models.DateField(blank=True, null=True) dni = models.CharField(max_length=20, blank=True, null=True) liccond = models.CharField(max_length=1, blank=True, null=True) feccipvig = models.DateField(blank=True, null=True) nrocip = models.CharField(max_length=10, blank=True, null=True) flgempliea = models.CharField(max_length=1, blank=True, null=True) observac = models.CharField(max_length=300, … -
django postagedb command refresh_from_db results in MemoryError or .DatabaseError: out of memory for query result
I have an influencer object which have many to many field of 20K+ followers. I can read up to 45 influencers one after the other and execute a worker on it followers. It is not happening immediately but after few hours. code: while True: with ThreadPoolExecutor(max_workers=45) as executor: influencers = Influencer.objects.filter( status__in=[ProcessStatus.recorded, ProcessStatus.unfinished, ProcessStatus.in_progress] ) # Process all the influencers. for influencer_obj in influencers: influencer_obj.refresh_from_db() # start the followers filtering process executor.submit(self.update, influencer_obj) exception: return self.cursor.execute(sql, params) django.db.utils.DatabaseError: out of memory for query result I do have a machine with 80GB running the client, while the postage db machine is not leaking memory (using free command). First, where is the memory issue, on the client or on the db server? Second, what can I do to avoid it ? should I release old obj ? -
Resizing Image before converting to Base64 in Django
I'm working on a django application which has a "My Profile" section where users can upload there profile images. I'm storing the images as a base64 code and rendering on the site. This is the code: @login_required def my_profile_edit(request): if request.method == 'POST': form =ProfileEditForm(request.POST or None,request.FILES,instance=request.user) if form.is_valid(): user=form.save(commit =False) user.user_image =form.cleaned_data['user_image'] user.user_image =base64.b64encode(user.user_image.file.read()) user.user_image ='data:image/jpeg;base64,'+ str(user.user_image)[2:-1] user.save() return redirect('my_profile') profile =CustomUser.objects.get(username=request.user) form =ProfileEditForm(instance=profile) return render(request,'profile_edit.html',{'form':form,'profile':profile}) Though it is working fine, I wish to reduce the size/ resize uploaded image first before encoding it into Base64 to improve performance and reduce space. I've tried few things using StringIO/BytesIO but without success. Please let me know the right way of doing so. -
Email temporary password
Hello I am new to django and web programming. I am building a website for my school that allows students to schedule online advising appointments. I need to be able to email students temporary passcodes to their student emails and then validate them on the next page. I have an email form : class EmailForm(forms.Form): student_email = forms.EmailField(max_length = 200, label = 'Mail') def clean_student_email(self): student_email = self.cleaned_data['student_email'] if not student_email.endswith('.edu'): raise ValidationError("Please enter your school email that ends with @edu") return student_email and a login view def login(request): if request.method == 'POST': form = EmailForm(request.POST) if form.is_valid(): student_email = form.cleaned_data['student_email'] random_code = get_random_string() subject = "Temporary Advising Code" message = f'Your temporary code is: \n code: {random_code}' send_mail(subject, message, 'advising email', [student_email]) return HttpResponseRedirect('/enter_code/', {'form' : form}) else: form = EmailForm() return render(request, 'login/login.html', {'form' : form}) Now I am able to generate a random string and send it to the students email but I am wondering if someone can tell me how I can validate that string on the next page. -
django: hide formset field within template
I am trying to hide some fields from a formset. I have learnt how it is easily possible in the view, however that does not make the trick for me because I need to manipulate those values inside of the view. I am wondering how I could have achieve this in the template only or any other method, I have searched online but cannot find something that would not require to manually set each field of the form inside of the template. here is what I have been able to build so far: def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('Id', 'Description','Date','Quantity', 'NetAmount', 'customer_name', 'invoice_number', 'shipping_number')) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) for i in range(len(formset)): formset[i]['invoice_number'] == formset[0]['invoice_number'] for i in range(len(formset)): formset[i]['shipping_number'] == formset[0]['shipping_number'] print("formset", formset) #blank_form = formset.empty_form elif request.method == 'POST': formset = form(request.POST) #invoice_hidden_form = CreateInvoiceForm(request.POST) #blank_form = formset.empty_form if formset.is_valid(): #request.session['sale'] = formset.cleaned_data for check_form in formset: check_form.save() quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity) request.session['sale'] = formset.cleaned_data #if invoice_hidden_form.is_valid(): #invoice_hidden_form.save() #print('invoice_hidden_form is saved successfully') #request.session['invoice'] = invoice_hidden_form.cleaned_data print("this is formset.cleaned_data in newsale", formset.cleaned_data) … -
How to avoid using a return statement in a for-in loop?
My view below is only going through one iteration cycle and then breaking out the loop. I know that it's probably because of the return statement in this line: return JsonResponse([post.serialize() for post in posts], safe=False) but how can I avoid this? I tried changing the return statement to a print statement instead but then I get a ValueError: The view network.views.followingPosts didn't return an HttpResponse object. It returned None instead. Just before the except statement I tried putting a continue there but this had no effect. I'm not really sure how to fix this. Any ideas? def followingPosts(request, user_username): try: user_profile = get_object_or_404(User, username=user_username) following_users = user_profile.get_following() for person in following_users: posts = Post.objects.filter(creator=person) except Profile.DoesNotExist: return JsonResponse({"error": "No user found."}, status=404) if request.method == "GET": return JsonResponse([post.serialize() for post in posts], safe=False) else: return JsonResponse({ "error": "GET request required." }, status=400) -
How to implement DRYPermissions in Django REST framework?
I have user accounts with defined permissions in a permissions column, which contains a string consisting of comma separated permission labels, e.g."create_users,view_users,edit_users,delete_users,". To check whether a user has the permission to perform a specific action it is only necessary to check the permissions of the rows of the user and all groups the user is a member of because whenever an user or customer or any relevance's from user looses permissions, all corresponding users and groups will be updated, i.e. the corresponding permissions will be removed. How can I structure a Viewset or a model in order to assign the mentioned permissions to 'create', 'view', 'edit' and 'delete' actions by the user? I'm trying to do so to have a single function that can be reused for different API endpoints that have the same permission pattern. I think DRYPermissions is a good way to go ahead with, but I am not quite sure on how to implement it or are there any other permission methods which would help me here. Any inputs would be highly helpful. Thank you for your time. -
How to preserve the element order when saving a django JSONField
I'm writing a small app that saves JSON verified by a schema to a PostgreSQL DB using Django's JSONField class. I am relying on the data to keep nodes in order butJSONField apparently uses PostgreSQL's jsonb type, which reorders the JSON data to increase indexing performance. Is there a way to preserve the order of elements using this method by forcing the json type instead of jsonb? Or should I give up and look into a different database's JSON support? Samples: What I send to the DB to be saved: "Item": { "@id": "blah" "ItemComponent": { "Weapon": { "@blah": "blah" "WeaponFlags": { "@blah": "blah" } } }, "Flags": { "@blah": "blah", } } How it is saved to the Database: "Item": { "@id": "blah" "Flags": { "@blah": "blah", }, "ItemComponent": { "Weapon": { "@blah": "blah" "WeaponFlags": { "@blah": "blah" } } } } -
How to use crispy_forms_tags and RichTextUploadingField each for a different fields in the same form
I have blog where I have a post as a Title and content as the below model.py: class Post(models.Model): title = models.CharField(max_length=100, unique=True) content = RichTextUploadingField(null=True, blank=True) in my views.py there are 2 fields title and content: class PostCreateView(CreateView): model = Post fields = ['title', 'content'] My question is how to use crispy_forms_tags for the title and RichTextUploadingField for the content Here is the template: <form method='post'enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Post</legend> {{ form.media }} {{ form.as_p }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> -
Django REST Framework validate date of birth
As part of the end of a login process a user has to enter their date of birth as a validation check. However I'm not clear how to validate the date of birth against a particular user models.py class CustomUser(AbstractUser): date_of_brith = models.DateField() def __str__(self): return self.username serializers class DobSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ["date_of_birth"] @api_view(["GET", "POST"]) def dob_view(request): """ """ if request.method == 'GET': users = CustomUser.objects.all() serializer = DobSerializer(users) return Response(serializer.data) if request.method == "POST": serializer = DobSerializer(data=request.data) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED)