Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-cms identify browser user
client html cannot access to sessionid (httpOnly). So I am going to get sessionid by csrf token from server side to identify browser users. From server (backend) side in which file can I get mapping csrf token with sessionid token ? -
An invalid form control with name='interest' is not focusable Django
When I add a forms.ModelMultipleChoiceField in my ProfileUpdateForm in forms.py, the submit button stops functioning and request.POST won't execute. The console says An invalid form control with name='interest' is not focusable. I'm not sure where to put name='interest' as I am rendering out multiple forms in only one <form> tag using Django templating etc {{ p_form }} {[ u_form }} (omitted from code to keep it short) forms.py class ProfileUpdateForm(forms.ModelForm): interests = Interest.objects.all() interest = forms.ModelMultipleChoiceField( queryset=interests, widget = forms.SelectMultiple(attrs={ 'placeholder': "Choose your interests", 'class': 'chosen-select', 'multiple tabindex': '4', })) groups = Group.objects.all() group = forms.ModelMultipleChoiceField( queryset=groups, widget = forms.SelectMultiple(attrs={ 'placeholder': "Choose any groups", 'class': 'chosen-select', 'multiple tabindex': '4', })) class Meta: model = Profile fields = ['interest', 'group', 'age'] views.py def profile_view(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if p_form.is_valid(): p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'p_form': p_form, } return render(request, 'users/profile.html', context) profile.html <form method="POST" enctype="multipart/form-data" class='profile-form'> {% csrf_token %} <!-- edit Profile model info --> {{ p_form|crispy }} <button type="submit" value="submit">Update Profile</button> </form> <script> $(".chosen-select").chosen(); $('button').click(function() { $(".chosen-select").val('').trigger("chosen:updated"); }); </script> -
Automatic addition of the day of the week for CharField in models.py
I have a very simple model to choose days of the week in my language, it looks like this: class Day(models.Model): DAY_OF_WEEK = ( ('Monday', 'Poniedziałek'), ('Tuesday', 'Wtorek'), ('Wednesday', 'Środa'), ('Thursday', 'Czwartek'), ('Friday', 'Piątek'), ('Saturday', 'Sobota'), ('Saturday', 'Niedziela') ) day_week = models.CharField(max_length=15, choices=DAY_OF_WEEK, default=date.today) How can I set the field automatically in my form to be set to the current day of the week? adding this to my model does not work according to my expectations (default=date.today). Any help will be appreciated. -
django rest_framework custom exception error
I'm new to django rest_framework, And tried to create customized error reponse in django!. Django Exceptions After going through that, all seems to be pretty straight forward, but the import error raise when i try to add the custom exception. Settings.py REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'project.restapi.utils.custom_exception_handler'} ImportError Exception Value: Could not import 'project.restapi.utils.custom_exception_handler' for API setting 'EXCEPTION_HANDLER'. AttributeError: module 'project.restapi.utils' has no attribute 'custom_exception_handler' model.py class Users(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def retrieve(self, request, *args, **kwargs): # call the original 'list' to get the original response response = super(Users, self).retrieve(request, *args, **kwargs) response.data = {"collection": {"data": response.data},"statusCode":response.status_code,"version":"1.0"} # customize the response data if response is not None: return response else: # return response with this custom representation response.data = {"collection": {"data": response.data},"statusCode":response.status_code,"version":"1.0","error":response.exception} return response So on the above model works fine, except when i try to hit the user which is not in the database should raise error - not found, so i tried to customise the not found to be meaningful to my own. that's it I tried to sort out, but hard to do so!!, Django Version: 2.1.5 Python - 3.7.0 -
function based view failed on CSRF verification in Django 1.11.5
I am learning Django by creating a blog site. But when tried to use function based view to create a post got CSRF verification failed. Using csrf_exempt decorator I could create post without error. But for security need to use CSRF protection, could anybody help with a solution please? Django = 1.11.5, Python = 3.6.8 views.py def post_create(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user new_post.save() return HttpResponseRedirect('/') else: form = PostForm() return render_to_response('create.html',{ 'form': form }) create.html <h2>Create your post here.</h2> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="CREATE"> </form> -
Writing an api call to create a User Django REST
I am really stuck for hours now. I have the following UserSerializer: UserModel = get_user_model() class UserSerializer(serializers.ModelSerializer): def create(self, validated_data): user = get_user_model().objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user class Meta: model = UserModel fields = ('id', 'username', 'deliveries', 'password') And this as my view: class UserList(APIView): def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) I am using the standard Django User Model. But I am not able to sent out a http req. to create a user. I always get "400_BAD_REQ" My request in httpie looks like this: http -v POST http://127.0.0.1:8000/user/user-list/ username="Rudy" password="12345" With other models I do not have these problems. Can someone tell me why this is not working? -
How to "use cookie-free domains" in Django?
i want to "Use cookie-free domains" in my project. For example; like this --> static.example.com/static/css/main.css https://prnt.sc/mmaaas -
How to parse text before being loaded into Django's admin for editing
I am creating a dynamic blog. I use Django's admin to add posts, and I have created some simple tags that python then substitutes for the actual html and css that are needed by the browser. This makes each blog easier to create and easier to read while creating. Before Django saves the new blog, I've coded my model to send the text to a python script, which parses the code and creates the finished html. This all works great, but I would also like to be able to parse the code before Django loads it, that way I can remove the html/css programatically, changing it back to the easier to read tags, making it easier to edit an already created blog. Is there a way to capture control of Django admin BEFORE it loads model data into the form for editing? -
Is it possible to run more than one app under same virtual environment in django
I am stuck when I want to add a field in model.py of accounts app. Here is my code from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pp = models.CharField(max_length=100, blank=True, null=True) xx = models.CharField(max_length=100, blank=True, null=True) When I run migration command it shows "Table 'auth_permission' already exists") But If I want to add a field in question table under polls app it works fine. mysite is the main folder. polls and accounts are two apps inside it. I created polls app first. Can I run two apps and codes under same virtual environment and using same database?? Can you please help me? -
how can i solve html5_webcam problem on the website?
there is a problem about html5 webcam becuase there is no error shows up and check the authorization to access the webcam. and i can see the red sign. but webcam function is not wokring somehow. please check my code thank you so much! takeing_photo.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Document</title> <link href="{% static 'css/photo.css' %}" rel="stylesheet"> </head> <body> <div class="booth"> <video id="video" width="400" height="300"></video> <a href="#" id="capture" class="booth-capture-button">Take photo</a> <canvas id="canvas" width="400" height="300"></canvas> <img id="photo" src="http://placekitten.com/g/400/300" alt="photo of you"> </div> <script src="{% static 'js/photo.js' %}"></script> </body> </html> photo.js (function(){ var video = document.getElementById('video'), photo = document.getElementById('photo'), context = canvas.getContext('2d'), phto = document.getElementById('photo'); vendorUrl = window.URL || window.webkitURL; navigator.getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; navigator.getMedia({ video:true, audio:false }, function(stream){ video.src=vendorUrl.createObjectURL(stream); video.play(); }, function(error){ }); document.getElementById('capture').addEventListener('click', function(){ context.drawImage(video, 0, 0, 400, 300); photo.setAttribute('src', canvas.toDataURL('image/png')) }); })(); photo.css .booth{ width:400px; background-color: #ccc; border:10px solid #ddd; margin:0 auto; } .booth-capture-button { display:block; margin:10px 0; padding:10px 20px; background-color: cornflowerblue; color: #fff; text-align: center; text-decoration: none; } #canvas { display :none; } i just want to make webcam properly and i m wondering there is a way to save the pics into the folder when i … -
How to upload image in Django model without form
I have a question about uploading images into database using django without uploading it with forms. I have web site which request data from API in my api request api response contain 200 hundred entities each entity contain several fields one of them is image of entity. I want to store this image into database. Which field i need to specify when i create model for entity? And how i can store it? -
How to deal with a model having multiple formset?
I have model Exam. It has two property ExamDate and Shift, which I have to add Dynamically. So I created two Formset ExamDate and Shift. It's working fine while creating New Exam but there's a problem in Editing. class ExamUpdate(UpdateView): model = Exam fields = ['title', 'examRoom'] success_url = reverse_lazy('index') examDateFormSet = inlineformset_factory(Exam,ExamDate,form = ExamDateAddForm,formset=BaseExamDateEditFormSet2,extra = 1,can_delete=True) examShiftFormSet = inlineformset_factory(Exam,Shift,form = ExamShiftAddForm,formset = BaseShiftEditFormSet2,extra = 1,can_delete=True) def get_context_data(self, **kwargs): data = super(ExamUpdate, self).get_context_data(**kwargs) if self.request.POST: data['dateformset'] = self.examDateFormSet(self.object,self.request.POST) data ['shiftformset'] = self.examShiftFormSet(self.object,self.request.POST) else: data['dateformset'] = self.examDateFormSet(self.object) data['shiftformset'] = self.examShiftFormSet(self.object) print ("This is data",data) print ("THis is objetc",self.object) return data def form_valid(self, form): context = self.get_context_data() dateformset = context['dateformset'] shiftformset = context ['shiftformset'] with transaction.atomic(): self.object = form.save() if dateformset.is_valid() and shiftformset.is_valid: dateformset.instance = self.object dateformset.save() shiftformset.instance = self.object shiftformset.save() else: print ("DateFormSet Not Valid",dateformset.errors) print ("ShiftFormSet Not Valid",shiftformset.errors) return super(ExamUpdate, self).form_valid(form) class BaseShiftEditFormSet2(forms.BaseModelFormSet): def __init__(self,tests, *args, **kwargs): super().__init__(*args, **kwargs) self.instance = tests self.queryset = tests.shifts.all() class BaseExamDateEditFormSet2 (forms.BaseModelFormSet): def __init__(self,tests,*args, **kwargs): super().__init__(*args, **kwargs) self.instance = tests self.queryset = tests.examdates.all() -
Bokeh, Django - embedding more independent plots via Components
I have database with pairs of Bokeh plot components for embedding - script and div HTML elements. I would like to embed more independent Bokeh plots on sigle page. The template code bellow renders same first plot for each iteration, please advise what Im doing wrong.. Thanks you for help! {% for plot in plots %} <div> {{ plot.plot_div | safe }} {{ plot.plot_script | safe }} </div> {% endfor %} -
how connect Nodmcu ESP8266 with django
I am trying to send data from a temperature sensor using a ESP8266 to a Django web aplication, store the data in a database sqlite3 and view the data obtained in a template, but I don't Know how make the connection between django and the ESP8266 -
Middleware to get headers with underscores?
I am making a server for a chinese manufactured hardware device. I cannot change it's firmware. The http requests sent by this device use headers with underscores which are getting stripped by django. I am new to django I need a clear workaround for this. A friend told me you might need to write a Middleware for it can anyone help? -
Django Chosen JQuery multiselect form not saving request.POST on submit
I've spent the last 12 hours on this and I'm thoroughly confused. Using a JQuery Chosen plugin, a user can select more than one interest and submit to POST to the interest field in the Profile model. There is one submit button on the page which sends the request.POST for all the data (as there are 2 additional forms, edit profile and edit private info). I've placed the Chosen select plugin inside the main <form method="POST" enctype="multipart/form-data" class='profile-form'> but on submit, it does not save any of the interests, while the other data is saved fine. I used to have the interest form as a field within the ProfileUpdateForm and it rendered it out using checkboxes and it saved fine, but I don't want to use that style. I'm pretty confused about what to do, I've tried making a ModelChoiceField form for interest and render it out as {{ i_form }} in the <select> area but that didn't work. Can someone please help me? models.py class Interest(models.Model): interest_name = models.CharField(max_length=30) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) interest = models.ManyToManyField(Interest, blank=False) age = models.CharField(max_length=2) profile.html <form method="POST" enctype="multipart/form-data" class='profile-form'> {% csrf_token %} <!-- select dropdown form for interests --> <select id="second" … -
Too many values to unpack (expected 2) Django
I am creating a form that contains a ChoiceField to which I establish the values of choice by means of view. According to Django documentation ChoiceFields Choices the election values must be: Either an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field, or a callable that returns such an iterable. This argument accepts the same formats as the choices argument to a model field. When loading the view, I do not get any problem. But when I try to get the value of the ChoiceField after validating the form in the view I get an error Too many values to unpack (expected 2). I do not know if I am wrongly adding the values of choice in the ChoiceField. Although I suppose if it were this the view would not load either. What am I doing wrong ? forms.py class FormAffiliateReport(forms.Form): ... referrals = forms.ChoiceField(choices=(), label='Choice Referral', widget=forms.Select(attrs={'class': 'form-control',})) def __init__(self, referrals, *args, **kwargs): super(formReporteVentasReferido, self).__init__(*args, **kwargs) self.fields['referrals'].choices = referrals views.py def affiliate_report(request): if request.session.has_key('affiliate_code'): affiliates = [] affiliate_code = request.session['affiliate_code'] affiliates = get_affiliates(affiliates, affiliate_code) affiliates.sort(key=lambda affiliate: affiliate.name.title()) if request.method == 'POST': form = FormAffiliateReport(request.POST) if form.is_valid(): referrals = form.data['referrals'] return render(request, 'blog/affiliate_report.html', … -
Django Filter - Paginate results
I'm using django-filter to output filtered results of my model. No issues there. Next step is adding a paginator.. though struggling for days now. views.py: def funds_overview(request): f = FundFilter(request.GET, queryset=Fund.objects.all()).qs paginator = Paginator(f, 5) page = request.GET.get('page') funds = paginator.get_page(page) return render(request, 'funds/funds.html', {'filter': funds}) funds.html: <form method="get"> <div class="well"> <h4 style="margin-top: 0">Search Criteria</h4> <div class="row"> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.fund_name.label_tag }} {% render_field filter.form.fund_name class="form-control" %} </div> </div> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Search </button> {% for fund in filter.qs %} <p>{{fund.name}} </p> {% empty %} No funds match your search criteria {% endfor %} Result in the browser The line "no funds match your search criteria" .. can anyone help? i assume something is wrong with calling the GET request twice? Thanks ! -
Render Image in MultipleChoiceField
I have a field of multiple choices, where you can choose, cat, bird, dog, cat, and you can choose more than one, so everything perfect. I wanted the image of the animal next to the field to appear, so that when I saved the form, when I showed the profile, the image of the chosen animal or of the chosen ones was shown. forms.py from django.forms import ModelForm from django import forms from django.forms.widgets import CheckboxSelectMultiple from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from PIL import Image from django import forms from django.core.files import File from .models import ( Usuario, Negocio ) PET_CHOICES = ( ('dog','Cachorro'), ('cat','https://www.petz.com.br/blog/wp-content/uploads/2017/07/gato02-303x228.jpg'), ('bird', 'Pássaros'), ('fish','Peixes'), ('rep','Reptéis'), ('horse','Cavalos'), ('rat','Roedores') ) class UsuarioForm(UserCreationForm): pet = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, choices=PET_CHOICES) -
Pagination in detail view
I use a detail view for my posts in my blog and each post has comments so I want to paginate them but I don't konw how to do it because I did a request for the post model. I know how to do it in function view but not in detail view... ##view : class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['comments'] = Comment.objects.filter(post_id=self.object.id).all() context['comments_number'] = Comment.objects.filter(post_id=self.object.id).count() context['form'] = CommentForm() return context def post(self, request, pk): form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = Post.objects.get(id=pk) comment.user = request.user comment.save() post = Post.objects.get(pk=pk) post.comments_nmb+=1 post.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) ##template: {% extends "blog/base.html" %} {% block content %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted|date:"F d, Y" }}</small> {% if object.author == user %} <div> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a> </div> {% endif %} </div> <h2 class="article-title">{{ object.title }}</h2> <p class="article-content">{{ object.content }}</p> <p>{{comments_number}} Comments</p> {% for comment in comments %} <div class="media"> <a class="float-left"> <img class="rounded-circle account-img" src="{{ comment.user.profile.image.url … -
Data transfer from form to function
Tell me how to send a message and email from the html form of the page, in the Python function to send to the mail? views.py: from django.shortcuts import render, redirect from django.core.mail import send_mail def index(request): name = 'Ivan' text = 'Text message' send_mail(name ,text,'111@mail.ru',['222@mail.ru']) return render(request, 'first/index.html') index.html: <!DOCTYPE html> <html> <head> <title>Index</title> </head> <body> <form method="post"> {% csrf_token %} <textarea name="text" cols="50" rows="10" placeholder="Enter message"></textarea> <p><input type="text" name="e_mail" placeholder="Уnter email address"></p> <input type="submit" value="Sent"> </form> </body> </html> -
transferring many parameters using the one button. Django
How can I transfer many parameters using one button in django? For example, I have such a button: <a class="btn-link" href="/product/parameter={{ parameter_here }}" value="a">submit</a> In my view I get access to it through: parameter = request.GET['parameter'] But when I try to transfer a lot of parameters, using parameter={{ product.name }}/parameter_1={{ product.price }}/parameter_2={{ product.time }} and I get accesses it in the view, I receive something like that: name/price/product Although I'm trying to get only the first parameter (parameter = request.GET['parameter']) Is there a way to pass many parameters and get access to them as in the case of one parameter (or I have to filter it out in the view)? Any help will be appreciated. -
Save unicode pictograms to mysql
I have some code (at django server) that writes json data contained in POST requests into mysql db. Some requests contain specific pictograms like 📸 or 🦁. Those are supposed to be written to a text field, but cause a db error. Code processing the requests looks like json_data = json.loads(request.body.decode('utf-8')) i = Event(event=json_data['event'], dt=parse(json_data['dt']), object_id=json_data['object_id'], user_id=json_data['user_id'], payload=json_data['payload']) i.save() db collation is currently set to uft8_general_ci What is best practice to have such requests saved to the db along others? -
Django Extending UserCreationForm with inexistent field error
I try to extend UserCreationForm of Django and use it with 'bootstrap4' template pack of Crispy Forms. First I have set up my form class. class SignUpForm(UserCreationForm): username = forms.CharField() email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Email'})) password1 = forms.CharField(widget=forms.PasswordInput()) password2 = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('username', 'email', 'password1', 'password2' ) def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({'autofocus': 'autofocus', 'required': 'required', 'placeholder': 'User Name'}) self.fields['email'].widget.attrs.update({'autofocus': 'autofocus', 'required': 'required', 'placeholder': 'Email'}) self.fields['password1'].widget.attrs.update({ 'required': 'required', 'placeholder': 'Password'}) self.fields['password2'].widget.attrs.update({ 'required': 'required', 'placeholder': 'Password Confirmation'}) Here is my home view: def home(request): form=SignUpForm() if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get('password1') password_confirmation = form.cleaned_data.get('password1') if password == password_confirmation: user.set_password(password) user.save() new_user = authenticate(username=user.username, password=password) login(request, new_user) return redirect('/') return render(request, "canicodewithyou/index.html", {'form':form}) and I use my form in html: <form class="form-signin" action="{% url "register" %}"> <div class="form-label-group"> {{form.username|as_crispy_field}} </div> <div class="form-label-group"> {{form.email|as_crispy_field}} </div> <hr> <div class="form-label-group"> {{form.password1|as_crispy_field}} </div> <div class="form-label-group"> {{form.password2|as_crispy_field}} </div> <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Register</button> <a class="d-block text-center mt-2 small" href="#">Sign In</a> <hr class="my-4"> </form> When I submit form I am getting an error |as_crispy_field got passed an invalid or inexistent field Here is my copy-paste traceback Traceback: File "/home/ytsejam/.virtualenvs/canicodewithyou/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/ytsejam/.virtualenvs/canicodewithyou/lib/python3.7/site-packages/django/core/handlers/base.py" … -
Accessing model fields in Django html template
I am trying to print fields from my 'Assignment' class, but nothing I try seems to work. In the html template I am trying to print the 'assignment_title'. Here are all my files to help show where I am up to urls.py url(r'^feedback/$', views.assignment, name='assignments') models.py class Assignment(models.Model): assignment_title = models.CharField(max_length=256, default='') lecturer = models.ForeignKey(User) views.py # Assignment view def assignment(request): obj = Assignment.objects.all() return render(request, 'mainfocus/feedback.html',{'obj': obj}) html <div class="container"> <h1>Feedback</h1> <p>{{ obj.assignment_title }}</p> </div> Just to confirm, I have registered the class in 'admin.py' as well. Any help would be greatly appreciated, I have also migrated and populated the tables so that should not be a problem either