Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework number type still pass validation from model
Hi i'm currently trying to write validation for my update API. i used the model fields in my serializer like so as i only want these fields to be update in the custom User model: class UpdateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'email', 'uid', 'nickname', 'eth_address', 'eth_private_key', 'evt_address', 'evt_private_key' ) My User model: Class User(AbstractUser): uid = models.CharField( "uid", max_length=255, null=True, blank=True) phone_number = models.CharField( "Phone number", max_length=255, null=True, blank=True) nickname = models.CharField( "Nickname", max_length=255, null=True, blank=True) status = models.PositiveSmallIntegerField("Status", default=0) eth_address = models.CharField( "Eth address", max_length=255, null=True, blank=True) eth_private_key = models.CharField( "Eth private key", max_length=255, null=True, blank=True) evt_address = models.CharField( "Evt address", max_length=255, null=True, blank=True) evt_private_key = models.CharField( "Evt private key", max_length=255, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) # deleted class Meta: db_table = "users" pass And here is my DRF update model view: class update_profile(RetrieveUpdateAPIView): permission_classes = () authentication_classes = (FirebaseAuthentication,) def update(self, request): user_data = request.data user = User.objects.get(uid=request.user.uid) serializer = UpdateUserSerializer(user, data=user_data, partial=True) if user_data == {}: raise serializers.ValidationError({'code': 400, 'data': 'Invalid JSON object'}) for key_name in user_data: if key_name not in ['email', 'uid', 'nickname', 'eth_address', 'eth_private_key', 'evt_address', 'evt_private_key']: raise serializers.ValidationError({'code': 400, 'data': 'Invalid input ' + key_name}) if serializer.is_valid(): updated_user … -
Django & React: JWT Authentication
my problem with reactjs it did not send token with request to backend (django framework) when i send get request i got AnonymousUser Bad Request i think the auth is not working in react in postman when i send the same request it works fine action.js import axios from "axios"; import jwt_decode from "jwt-decode"; import * as actionTypes from "./actionTypes"; const instance = axios.create({ baseURL: "http://127.0.0.1:8000/api/" }); const setAuthToken = token => { if (token) { localStorage.setItem("token", token); axios.defaults.headers.common.Authorization = `jwt ${token}`; } else { localStorage.removeItem("token"); delete axios.defaults.headers.common.Authorization; } }; export const checkForExpiredToken = () => { return dispatch => { const token = localStorage.getItem("token"); if (token) { const currentTime = Date.now() / 1000; const user = jwt_decode(token); if (user.exp >= currentTime) { setAuthToken(token); dispatch(setCurrentUser(user)); } else { dispatch(logout()); } } }; }; export const login = (userData, history) => { return async dispatch => { try { let response = await instance.post("login/", userData); let user = response.data; let decodedUser = jwt_decode(user.token); setAuthToken(user.token); dispatch(setCurrentUser(decodedUser)); dispatch({ type: actionTypes.SET_ERRORS, payload: [] }); history.push("/assets"); } catch (error) { console.log("error ===> ", error); dispatch({ type: actionTypes.SET_ERRORS, payload: error.response.data }); } }; }; export const logout = () => { setAuthToken(); return setCurrentUser(); }; const … -
django- Displaying value only after a valid code is submitted
Im new to django. I'm trying to build an ecommerce website. My site has 'promo code' which can be used during checkout. I have created a card where 'purchased item's name, price and other details can be viewed. I want to display 'promo code' and 'amount reduced by promo code' in the card. but only after user enters the 'promo code.' -
How to configure ClamAV autoupdate
I am using ClamAV for scanning our files in our Django application. I am running freshclam manually to update the antivirus database. My question is how to automate it? -
dynamic redirects with two submit button in django generic update view
Trying to redirect to two views in get success url method, but didn't work. My html button is as follows. <input type="submit" name="addMore" class="btn btn-primary btn-block" value="Save and Add More"> <input type="submit" class="btn btn-primary btn-block" value="Save and Exit"> Tried in my generic update views, as follows, but throws TypeError at /add_experience/ quote_from_bytes() expected bytes def get_success_url(self): if 'addMore' in self.request.POST: return redirect('add_experience') else: return redirect("emp_profile_list") -
Django dynamic URL in template
How can I use template variable in dynamic url. I want something like this: href="{% url '{{ questionnaire.url }}' %}" The problem is that I get this error: Reverse for '{{ questionnaire.url }}' not found. '{{ questionnaire.url }}' is not a valid view function or pattern name. -
How to properly send a file with additional variables in a Django HTTP response?
I know how to return a JSON response: return Response({'example':'example'}) and also know how to return a file response: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' return response But if I want to send both in one response, how can I properly do that? Django documentation gives an example for setting additional header fields: >>> response = HttpResponse() >>> response['Age'] = 120 But from reading a couple answers I've seen, it looks like sending business data in headers it not the way to go. Is there a better solution? -
Passing the pk from url to CreateView form_valid
I want to pass pk of other model from URL to my CreateView form. How to do that? Could you help me? When I'm passing specific id it works, but I want to get the pk automatycly, from url. My views.py: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = [ 'commentText' ] def form_valid(self, form): form.instance.commentAuthor = self.request.user form.instance.commentDate = datetime.now() form.instance.commentScenario = Scenario.objects.get(pk=1) #there is my problem return super().form_valid(form) My url.py: path('scenario/<int:pk>/', ScenarioDetailView.as_view(), name='scenario-detail'), Also my model: class Comment(models.Model): commentText = models.CharField(max_length=256) commentScenario = models.ForeignKey(Scenario, on_delete=models.CASCADE) commentAuthor = models.ForeignKey(User, on_delete=models.CASCADE) commentDate = models.DateTimeField(default=timezone.now) Any suggestions? -
'django.contrib.admin.sites' has no attribute 'register' in Django 3.0 python
i make the model in app but when i call this function 'admin.sites.register(modal_class_name)' in admin.py file. i got an error here is my modal class from django.db import models # Create your models here. class Topic(models.Model): top_name=models.CharField(max_length=256,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic=models.ForeignKey(Topic,Topic) name=models.CharField(max_length=256,unique=True) url=models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name=models.ForeignKey(Webpage,Webpage) date=models.DateField() def __str__(self): return str(self.date) and Here is my admin.py file code from django.contrib import admin # Register your models here. from first_app.models import AccessRecord, Topic, Webpage admin.sites.register(AccessRecord) admin.sites.register(Topic) admin.sites.register(Webpage) and when i run the project the error appears,which is following error snapshot -
Django two table relationship, but not both
I have a table called Post. A post can have 2 videos or 2 images, but not both. The table schema for a post looks like this: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) header = models.CharField() created_at = models.DateTimeField(auto_now_add=True) I have two tables that look similar to each other: class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) img = models.ImageField() class PostVideo(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) video = models.FileField() How do I create and enforce the relationship where a post can have maximum and minimum of 2 images or 2 videos, but it can't have both videos and images at the same time? -
How to send bulk email in Django rest framework reading from csv?
CSV file : Name Email Phone A aa@gmail.com 11111 B bb@gmail.com 22222 I have a seralizer : class ImportCsvSerializer(serializers.Serializer): csv = serializers.FileField(required=True) Now I am using : send_mail(subject,'',settings.DEFAULT_FROM_EMAIL,[users.email],html_message =html_message, fail_silently=False) How can I iterate each row and send multiple emails ? -
ModuleNotFoundError: No module named 'sklearn.neighbours'
i am beginner in machine learning and did find what's going wrong in this module error... from sklearn.neighbours import KNeighborsClassifier ModuleNotFoundError: No module named 'sklearn.neighbours' -
reverse lookup django models
i have ImageShoot and Image model. I am trying to add reverse lookup like which Image belongs to which ImageShoot. one ImageShoot can have multiple Images class ImageShoot(models.Model): name = models.CharField(max_length=100) created_at = models.TimeField(auto_now_add=True) def __str__(self): return self.name class Image(models.Model): license_type = ( ('Royalty-Free','Royalty-Free'), ('Rights-Managed','Rights-Managed') ) image_number = models.CharField(default=random_image_number,max_length=12) title = models.CharField(max_length = 100) image = models.ImageField(upload_to = 'home/tboss/Desktop/image' , default = 'home/tboss/Desktop/image/logo.png') category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) shoot = models.ForeignKey(ImageShoot, on_delete=models.CASCADE, related_name='Image') image_keyword = models.TextField(max_length=1000) credit = models.CharField(max_length=150, null=True) location = models.CharField(max_length=100, null=True) license_type = models.CharField(max_length=20,choices=license_type, default='') uploaded_at = models.TimeField(auto_now_add=True) def __str__(self): return self.title admin.py: @admin.register(ImageShoot) class Imageset(admin.ModelAdmin): list_display = ('name','created_at','associated_image') def Imageset(self, obj): associated_image = ImageShoot.image_set.all() return associated_image this admin.py showing error: <class 'image.admin.Imageset'>: (admin.E108) The value of 'list_display[2]' refers to 'associated_image', which is not a callable, an attribute of 'Imageset', or an attribute or method on 'image.ImageShoot' -
django docker db migrations is not working for the new model
i am new here in django docker, I have created new model for django app, I am working on docker, when i am trying to use migrate command of docker, it says No migrations to apply, i am using docker exec -ti 75ce87c91dc7 sh -c "python app/manage.py migrate" this command, but it says No migrations to apply, here i have added my models.py file, do we need to import this models to anywhere else ? from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Userprofile(models.Model) : user = models.OneToOneField(User, on_delete=models.CASCADE) type = models.SmallIntegerField(max_length=1) created_date = models.DateTimeField(default=timezone.now) updated_date = models.DateTimeField(blank=True, null=True) def publish(self): self.updated_date = timezone.now() self.save() def __str__(self): return self.title -
Multiple django formset instances
Scenario I am trying to create a questionnaire. One questionnaire can have a multiple question sets and each question set can have multiple questions. I am trying to create a form of two steps. First step would ask basic details of the questionnaire like name,total sets etc and on the second steps I want to create one form something like: Set 1 Question 1 Question 2 Set 2 Question 1 Question 2 In my django views I have created a formset: db_questionnaire = get_object_or_404(Questionnaire, pk=questionnaire) queryset = Question.objects.filter(questionnaire_id=questionnaire) QuestionFormSet = modelformset_factory(Question, form=QuestionForm, extra=1, max_num=1, can_delete=True, min_num=1, validate_min=True) formset = QuestionFormSet(request.POST or None, request.FILES or None, queryset=queryset) Main Problem This works well when I try to create/edit multiple questions regardless of the questionnaire sets. What I want to achieve is to create a single form which can create questions for each set defined on the first step. -
JavaScript array to Django form input dropdown list
<script> let myArr = ["ProductA","ProductB","ProductC"]; </script> I want to make a Django input dropdown using this javascript array. <input type="text" name="product1" value="0" maxlength="500" class="textinput textInput form-control" id="id_product1"> When user will click on this django form input, i want a dropdown list to appear, from which users can select an option. -
Django Admin Ajax List view and delete?
I have customized the admin theme layout, currently it looks like attached screenshot. I want to implement Ajax based List View including pagination, filters, search & DELETE (similar to Jquery Datatables ) on Django built-in admin template. Is it possible to make listing view completely ajax based? Please guide me with all possible solutions. -
Updating a nested Django object where if it the next object doesn't exist create a new one
So, I have two models a Template (QtnTemplate) and a Question (QtnQuestion). The template (QtnTemplate) has a manyToMany field of questions(qtn_template_questions). What I want to do is when my front end sends a PUT rest command with a template that has another new question added. It will take that data update the template since that new question doesn't exist it will create a new nested question in the backend. In the Serializer for the template I have the following code: from rest_framework import serializers from .models import QtnTemplate from qtn_question.models import QtnQuestion from qtn_question.serializers import QtnQuestionSerializer class QtnTemplateSerializer(serializers.ModelSerializer): # qtn_template_questions = QtnQuestionSerializer(many=True, read_only=False) class Meta: model = QtnTemplate fields = ('id', 'qtn_template_name', 'qtn_template_create_date', 'qtn_template_question_order', 'qtn_template_questions') depth = 1 # This is supposed to check to see if a questionId is already set in the underlying template # if it isn't already set then create a new one def update(self, instance, validated_data): questions = self.data['qtn_template_questions'] for quest in questions: questionId = quest.pop('id') questString = quest.pop('qtn_question_question_string') if questionId is None: QtnQuestion.objects.create(qtn_question_question_string=quest.pop('qtn_question_question_string'), qtn_question_ui_id=quest.pop('qtn_question_ui_id'), qtn_question_risk_weight=quest.pop('qtn_question_risk_weight'), qtn_question_is_selected=quest.pop('qtn_question_is_selected'), qtn_question_setting=quest.pop('qtn_question_setting'), qtn_question_answer_type=pop('quest.qtn_question_answer_type')) instance.save() return instance def to_representation(self, value): data = super().to_representation(value) serializer = QtnQuestionSerializer(value.qtn_template_questions, many=True) data['qtn_template_questions'] = serializer.data return data def to_internal_value(self, data): self.fields['qtn_template_questions'] = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=QtnQuestion.objects.all()) … -
Problems with Django CMS
When I do certain changes the page stop loading on local machine especially modifying settings.py file is impossible what is the reason? following this tutorial http://support.divio.com/en/articles/51835-18-creating-your-first-django-cms-addon I also find problems - errors like syntax error in terminal trying to execute commands and also when adding addon "forms" site stops loading as well on local. after uninstall it works back again. and deleting entries from settings also helps to bring site back to life but i am pretty much unable to install any apps to the site this way -
Can i add an API for a normal view function without performing any operations on viewsets in djnago
suppose i created a model of blog an performed CRUD operations on it without API and now i want to add an API to that model without performing operations in view-sets. Whenever an data is passed through API or our site model it should display in db and on front end. Is it possible?? thanks,in advance -
How to update a model with existing instances
Currently I have multiple of instances of one type of model stored in my database. However I would like to change a field type on the actual model, and propagate that change to those same instances. The proposed change would take an ImageField and alter it to a CharField. By what means could this take effect? I've encountered this post that slightly addresses this with a data migration: Change column type with django migrations It doesn't address the need to change the type on existing instances though. -
Inserting template variable into block tag
Is it possible to create block names dynamically? I would like to do {% block {{obj.id}} %} but get an error saying this cannot be done I need to load custom content depending on obj into the block -
Conditional parameters while using factory pattern
I was using old fashioned functions to process payroll but now I am moving it to a web-app with more features such as adjustable settings in the processing of the payroll. Currently in the middle of reading about design patterns and decided to try to implement the factory pattern in one of my projects modules though I am slightly stuck. The goal is to apply conditional parameters to a classes attribute. To give an idea of how my old function looked it simply converting excel files to dataframes using pandas read_excel() method: def read_excel_files(): df_stylist_analysis = pd.read_excel( Reports.objects.latest('stylist_analysis').stylist_analysis.path, sheet_name=0, header=None, skiprows=4) df_tips = pd.read_excel( Reports.objects.latest('tips_by_employee').tips_by_employee.path, sheet_name=0, header=None, skiprows=0) df_hours1 = pd.read_excel( Reports.objects.latest('hours_week_1').hours_week_1.path, header=None, skiprows=5) df_hours2 = pd.read_excel( Reports.objects.latest('hours_week_2').hours_week_2.path, header=None, skiprows=5) df_retention = pd.read_excel( Reports.objects.latest('client_retention').client_retention.path, sheet_name=0, header=None, skiprows=8) df_efficiency = pd.read_excel( Reports.objects.latest('employee_service_efficiency').employee_service_efficiency.path, sheet_name=0, header=None, skiprows=5) return df_stylist_analysis, df_tips, df_hours1, df_hours2, df_retention, df_efficiency As you can see there are different amounts of rows being skipped on each file. Currently I am trying to implement an Excel factory I wrote in place of the function so that it can handle several Excel file types: class XLSDataExtractor: def __init__(self, filepath, rows): self.data = pd.read_excel(filepath, sheet_name=0, header=None, skiprows=rows) @property def parsed_data(self): return self.data class XLSXDataExtractor: … -
Multiple ModelAdmins for one Wagtail model
What is the best way to go about implementing multiple menu items to manage different aspects of one model in Wagtail? I have tried using more than one ModelAdmin on one model, but then Wagtail chooses the first ModelAdmin, and all of the other pages in the menu follow the first ModelAdmin. Should I try something with proxy models? -
Django - form doesn't show up on template
I'm working on a project and ended up with some problems. I can't make the form to display in the template at all. Code: models.py A very basic db. from django.db import models class Cliente(models.Model): nombre_cliente = models.CharField(max_length=200) domicilio_real = models.CharField(max_length=200) domicilio_obra = models.CharField(max_length=200) correo = models.EmailField() telefono = models.CharField(max_length=200) fecha_alta_cliente = models.DateField() fecha_inicio_obra = models.DateField() fecha_fin_obra = models.DateField() forms.py a form class with fields, widgets and attrs (still, basic). from django import forms from .models import Cliente class CargarForm(forms.Form): nombre_cliente = forms.CharField( label='Nombre del cliente:', max_length=200, widget=forms.TextInput(attrs={'class': 'form-control' 'input-50'})) domicilio_real = forms.CharField( label='Domicilio real:', max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})) domicilio_obra = forms.CharField( label='Domicilio de obra:', max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})) correo = forms.EmailField( label='Correo electrónico:', max_length=254, widget=forms.EmailInput(attrs={'class': 'form-control'})) telefono = forms.CharField( label='Teléfono:', max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})) fecha_alta_cliente = forms.DateField( label='Fecha de alta de cliente:', widget=forms.SelectDateWidget(years=range(2019, 2100), attrs={'class': 'form-control'})) fecha_inicio_obra = forms.DateField( label='Fecha de inicio de obra:', widget=forms.SelectDateWidget(years=range(2019, 2100), attrs={'class': 'form-control'})) fecha_fin_obra = forms.DateField( label='Fecha de alta de cliente:', widget=forms.SelectDateWidget(years=range(2019, 2100), attrs={'class': 'form-control'})) error_messages = { 'nombre_cliente': { 'required': ("El nombre del cliente es obligatorio"), }, 'domicilio_real': { 'required': ("El domicilio real es obligatorio"), }, 'domicilio_obra': { 'required': ("El domicilio de obra es obligatorio"), }, 'correo': { 'required': ("Debe proporcionar correo electrónico"), }, 'fecha_alta_cliente': { …