Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 223: ordinal not in range(128)
I am trying to execute a read file command from command line inside a container in k8s for a django app but i get this error. I am able to execute the same command locally but not inside k8s. My complete error stack is as follows: raceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/code/setup/management/commands/load.py", line 40, in handle raw = file.read() File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 223: ordinal not in range(128) -
how to conditionally validate Django
how can you check the correctness of data entry through the validation method Let's say I want to register a person to the master, you cannot register if he already has a person for this time. How can this be done via def validate_work_on (self, value): serializer class SerializerCreateServiceCreate(serializers.ModelSerializer): work_on = serializers.models.CharField(choices=Service.worked_hours) time_to_work = {} class Meta: model = Service fields = '__all__' read_only_fields = ('client_to_job',) def create(self, validated_data): return Service.objects.create( name_master=validated_data.get('name_master'), client_to_job=self.context['request'].user, work_on=validated_data.get('work_on') ) **def validate_work_on(self, value): if value in Service.worked_hours: raise serializers.ValidationError("выберите другое время") return value** class SerializerServiceCreate(SerializerCreateServiceCreate): name_master = SerializerMasters() client_to_job = UserSerializerView() model Service class Service(models.Model): worked_hours = ( ('1', '10:00'), ('2', '11:00'), ('3', '12:00'), ('4', '13:00'), ('5', '14:00'), ('6', '15:00'), ('7', '16:00'), ('8', '17:00'), ('9', '18:00'), ('10', '19:00'), ('11', '20:00'), ) name_master = models.ForeignKey(Masters, verbose_name='Мастер', on_delete=models.CASCADE) client_to_job = models.ForeignKey(User, verbose_name='Клиент', on_delete=models.CASCADE) work_on = models.CharField(verbose_name='Рабочие часы', choices=worked_hours, max_length=30) class Meta: verbose_name = 'Сервис' verbose_name_plural = 'Сервисы' and class api view class ServiceCreateView(CreateAPIView): permission_classes = [IsAuthenticated] serializer_class = SerializerCreateServiceCreate def get_object(self): return self.request.user how one can validate against this condition, I don’t understand -
Django - Add Status 'Read' to messages
I have a django model Message which has sender, recipient, sent_at and a M2MField read. In the template when user Bob clicks on user Jane, their messages are loaded in and a view with the recipient's name (Jane) gets called to filters down Bob's messages and add Bob to Jane's message' read field. It works for the first 2 messages: Bob sends a message, Jane clicks on user Bob, Jane gets added to Bob's message' read field. Jane sends a message, Bob clicks on user Jane, Bob gets added to Jane's message' read field. But after the first message from Bob and the first from Jane it stops working. Here is the view: class ReadMXApiView(APIView): def get(self, request, format=None, *args, **kwargs): sender_ = self.kwargs['username'] myself = request.user my_mex = Message.objects.filter(recipient__username=request.user).filter(sender__username=sender_) if my_mex.exists(): if myself in my_mex.latest('sent_at').read.all(): return Response('No new messages from '+sender_) else: for m in my_mex: m.read.add(myself) return Response('I read the messages') return Response('No messages from '+sender_) Thank you for any suggestions -
How to add plain text to show up in my template using css?
I want to add plain text inbetween my CharFields or TextAreas that I created using Django and Css. I do not want to add the code in my template file but in my forms.py file. The final result should be like this: "I would pay _____ for this". Here, I can either include the first part of the sentence in the "label" of my CharField or I can include it in my FieldSet using "<h5..."etc. However, if I want to include the second part of the sentence which is "for this", it doesnt show up when I use the same structure with "<h5 .."etc. And I cant include another label. Does someone have an idea how to just simply add plain text (coded in my forms.py) inbetween my survey? Thanks a lot! Example how it looks now and should look forms.py class SurveyPolicy(forms.Form): policy6a = forms.CharField( # required=False, label='', widget = forms.Textarea(attrs={'rows':1}) ) policy6b = forms.IntegerField( # required=False, label='', widget=forms.NumberInput() ) def __init__(self, *args, **kwargs): super(SurveyPolicy, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'survey-form' self.helper.label_class = 'col-lg-12' self.helper.field_class = 'col-lg-12' self.helper.layout = Layout( Fieldset( "<hr><h5 style='color: #2D2D2D; text-align: center; font-family: Roboto;'>I would pay ...</h5>", Div('policy6a', css_class='form-group row-ml-0 mb-0'), Div('policy6b', css_class='form-group … -
Django Serializing of ValueQuerySet
So I got the following ValueQuerySet records = Maintenance.objects.values('failure').annotate(fcount=Count('failure')) Out[13]: <QuerySet [{'failure': 'Bend Pin', 'fcount': 2}, {'failure': 'Winding Failure', 'fcount': 2}, {'failure': 'Degraded Capacitor', 'fcount': 2}]> I tried serializing this with Django's serializer; from django.core import serializers serializers.serialize('json', records, fields('failure', 'fcount')) AttributeError: 'dict' object has no attribute '_meta' I know I can serialize the records with json.dumps, but I want to understand why Django's serializer gives me this error. I'm running on Python 3.8.2. and Django 3.0.5. -
How to make a `INSERT INTO` sql query for django postgres JSONField?
Consider a model: from django.db import models from django.contrib.postgres.fields import JSONField class A(models.Model): field_A = JSONField(null=True) I want to write a INSERT INTO query for this table to add values rather than using the django ORM wrapper. I tried the following: from django.db import connection cur=connection.cursor() query = "INSERT INTO A VALUES ({'a':1,'b':2})" cur.execute(query) The above line throws me an error saying invalid while pointing at the start of the json object. Looking for the help of someone who can suggest me the best way to do this using SQL? -
python - django upgrade. rest_framework.response.Response not serializing data
I am upgrading my project from django 1.8.18 to 1.11.29. After changing dependencies in requirements.txt file below piece of code is not working as expected. I have tried to debug this but couldn't get any further. Issue I am facing is that Response(serializer.data) is not converting ReturnList to dict as was doing earlier. Is there anything else that needs to be updated? Output with django 1.8.18: {"msg": "Batty1",} {"msg": "[OrderedDict([('session_id', '16a635d0-0f7a-4366-b648-a907ea4f4692')])]"} {"msg": "st data"} {"msg": "<class 'rest_framework.utils.serializer_helpers.ReturnList'>"} {"msg": "r data"} {"count": 1, "previous": null, "results": [{"session_id": "16a635d0-0f7a-4366-b648-a907ea4f4692"}]} {"msg": "t data"} {"msg": "<type 'dict'>"} Output with django 1.11.29: {"msg": "Batty1",} {"msg": "[OrderedDict([('session_id', '16a635d0-0f7a-4366-b648-a907ea4f4692')])]"} {"msg": "st data"} {"msg": "<class 'rest_framework.utils.serializer_helpers.ReturnList'>"} {"msg": "r data"} {"msg": "[OrderedDict([('session_id', '16a635d0-0f7a-4366-b648-a907ea4f4692')])]"} {"msg": "t data"} {"msg": "<class 'rest_framework.utils.serializer_helpers.ReturnList'>"} Versions changed are: -
How to disable autofocus from username field in Django's UserCreationForm?
I am using the UserCreationForm class to create a signup page in my Django app. Here is my code that defines the form: class SignUpForm(UserCreationForm): email = ... username = forms.CharField(label="Username", widget=forms.TextInput(attrs={ ... "autofocus": False, ... })) password1 = ... password2 = ... Despite the autofocus attribute being set to False, when I open the form in my browser the focus is still on the username field. How can I disable it? -
How to indicate to a specific version of database? [Django] [PostgreSQL]
I using django version 3.0.2. I'd like to use postgreSQL as my instance db. And there are two version postgreSQL in server. After config setting.py DATABASES parameter, and runserver. It showed error. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dj_web_console', 'USER': 'django', 'PASSWORD': 'django', 'HOST': 'localhost', 'PORT': '', } } psycopg2.OperationalError: FATAL: password authentication failed for user "django" I'm sure that the username and password are correct. How to config pg_path in Django as odoo: In this case, I can use the specific version of pgsql. And run smoothly. -
URL pattern in django to match limited set of words
I have a URL pattern in Django where there is a variable (called name) that should only take one of a select list of words. Something like this: path("profile/<marta|jose|felipe|manuela:name>/", views.profile), So basically only these paths are valid: profile/marta/ profile/jose/ profile/felipe/ profile/manuela/ How exactly can I configure this in the Django url patterns? The above syntax tries to illustrate the idea but doesn't work. I've seen this ten year old question but that uses the previous format in the url patterns file so I imagine it should be done differently now...? -
Django graphene returns Bad Request in unit test
I have defined the following graphql schema to create an inactive user from .models import User, UserManager import graphene from graphene_django import DjangoObjectType class UserType(DjangoObjectType): class Meta: model = User class PreSignupInput(graphene.InputObjectType): email = graphene.String(required=True) terms_of_use = graphene.Boolean(required=True) class PreSignup(graphene.Mutation): class Arguments: pre_signup_data = PreSignupInput(required=False) user = graphene.Field(UserType) def mutate(self, info, user_data=None): user = UserManager().create_inactive_user_with_email(user_data.email, user_data.terms_of_use) return PreSignup(user=user) class Mutation(graphene.ObjectType): pre_signup = PreSignup.Field() The User class is also defined as AUTH_USER_MODEL in the config and create_inactive_user_with_email creates an instance of User, saves it to the db and returns it. Whenever I run the following test: from graphene_django.utils.testing import GraphQLTestCase class UserSchemaTest(GraphQLTestCase): def test_create_inactive_user(self): response = self.query( ''' mutation preSignup($input: PreSignupInput!) { preSignup(input: $input) { user { id email } } } ''', op_name='preSignup', input_data={'email': 'test@example.com', 'terms_of_use': True} ) print(response.json()) self.assertResponseNoErrors(response) It fails with a Bad Request error and the following error message: { 'errors': [ {'message': 'Unknown argument "input" on field "preSignup" of type "Mutation".', 'locations': [{'line': 3, 'column': 27}]}] } Is there anything I'm missing? I used this tutorial for the test. Thank you! -
How to send two parameter id and name in onclick function?
Here I have many users(with id,name,role defined) in html. When I click in one of the user It displays the modal and inside this modal I want to display the id,name and role of that user. I am only being able to dispaly id. How can I display name and role also ? html {% for user in users %} <li> <i class="fas fa-user-circle"></i>{{ user.name }}, {{user.role}} <a href="" class="text-primary" onclick = "send_message({{user.id}} )">Message</a> </li> {% endfor %} script function send_message(id){ event.preventDefault(); $('#sendmessage').modal('show'); $('#send_message_modal_title').text("Send Message to User"); $('#sendmessage').on('shown.bs.modal', function (e) { $("#user_id").val(id); $("#user_name").val(name, role); }) modal <input name="cleaner" id="user_id"> <input type="text" value="name and role" class="form-control"> #how to display name and role ? -
SQL, order by .(Django, Queryset)
There is a table "Ad" with fields id, is_pro (boolean). There are entries (1, False), (2, True), (1, True), (1, False), (1, True), and so on. It should be sorted in the following way, True, False, True, False, True, False, True, False, True, False ... Any ideas? -
Subset query in ManytoMany relationship Django
I have two tables:Article and Publication. An Article can have multiple Publications. Given a list of Publication objects, I want to write a query that gives me only those articles which have Publications objects present in my list.(subset only) For e.g. ABC article has Publications P1, P2. BCD has P2, P3 DEF has P3, P4 Given publications are [P1, P2, P3]. So query output should be - ABC, BCD. DEF will be excluded as it has P4 which is not present in list. Using filter and exclude doesn't work properly in M2M relationship. So I am solving it using for loops which doesn't seem efficient and I want more Pythonic and ORM efficient solution. models.py from django.db import models class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ['title'] def __str__(self): return self.title class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) class Meta: ordering = ['headline'] def __str__(self): return self.headline Views.py article = Article.objects.get(pk=pk) publications_in_article = article.publications.all() for publication in publications_in_article : if publication not in cleaned_data.get('publications'): exclude_publications.append({'id': publication.id, 'name': publication.title}) break return exclude_publications -
how can I show comments in django class view?
in my models.py file I hav 2 classes Question and Answer.And in views.py file I am using ready class forms from django.views.generic. So how can I show question answers in detailview HTML? models.py file from django.db import models from django.conf import settings from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User class Question(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField('Title', max_length=70) content = models.TextField('Body', null=True, blank=True) date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('current', kwargs={'pk': self.pk}) class Meta: verbose_name_plural = 'Questions' verbose_name = 'Question' class Answer(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) content = models.TextField('Body', null=True, blank=True) date = models.DateTimeField(default=timezone.now) def __str__(self): return self.content class Meta: verbose_name_plural = 'Answers' verbose_name = 'Answer' views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import Question, Answer from django.shortcuts import redirect from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) def index(request): context = { 'questions': Question.objects.all() } return render(request, 'f/index.html', context) class QuestionListView(ListView): model = Question template_name = 'f/index.html' context_object_name = 'questions' ordering = ['-date'] class QuestionDetailView(DetailView): model = Question answers = Answer class QuestionCreateView(LoginRequiredMixin, CreateView): model = Question fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return … -
how should Django auth User login with one type password [closed]
I am using django(2.2.10) web app and using django User model for authentication . I need add a feature login with registered number and otp . I need both authentication.User can either Login with password or he can choose otp . How should i impliment these feature in django web app . -
How can I access browser cookies of any site in Django?
I am creating an SSO system to connect 2 Django project, one project I locally hosted on localhost:8000 and other on localhost:8080. I did login on 8000 in chrome browser, I want to get stored 8000 cookies_data(session_key) by using an API of 8080 port. Is there any way in Django to access browser cookies of any site(in my case localhost:8000).? -
Add a field in Serializer depending on other field : django
I have a seriliazer: class aaaser(serializers.ModelSerializer): client_code = serializers.SerializerMethodField() status = serializers.SerializerMethodField() def get_status(self, obj): status_code = obj.status if obj.status else -1 return status_code class Meta: model = models.Order fields = ('client_code', 'status', 'order_id', 'details') In this seriliazer i want to add a field with name cancel_reason which should ONLY be added if value of status == 5. class aaaser(serializers.ModelSerializer): client_code = serializers.SerializerMethodField() status = serializers.SerializerMethodField() def get_status(self, obj): status_code = obj.status if obj.status else -1 if status_code == 5: # this felt dumb but had to try! cancel_reason = serializers.SerializerMethodField() return status_code def get_cancel_reason(self, obj): return "Dummy-reason" class Meta: model = models.Order fields = ('client_code', 'status', 'order_id', 'details') ^This Doesn't work Please suggest a solution or a alternative to SerializerMethodField for this usecase.. Thanks a lot!! -
Web site and mobile app: how to combine this 2 IT support?
I've been working with Django for one year now, to develop web site applications. And I've just started to learn about Flutter, the cross-plateform solution by Google to develop mobile app. Having this 2 IT supports TOGETHER for the same project would be ideal. That means web site application and mobile app should "share" the same database, at least for authentication (user should have the same account for web app and mobile app) but not only. Basically, principle of my web site applications is to give a random number from a list. A number can only be assigned once. So, mobile app should share the same database to get access to the list of number to be assigned. is it feasible? -
Filtering products by size in django by passing parameter in url
I am working on a django site. I have a product page on which I display products . I am wanting to filter the products based on the sizes available in the product. This is my url followed by the views.py and models.py: path("products/<str:type>/<str:sort>/<str:size>",views.products,name="products"), path("products/<str:type>/<str:sort>/",views.products,{'size':''}), def products(request,type,sort,size): sorting = ['category_id'] if sort == 'all': sorting.append('timeadded') elif sort == 'new': sorting.append('-timeadded') elif sort == 'priceltoh': sorting.append('price') elif sort == 'pricehtol': sorting.append('-price') prods=Product.objects.filter(category__type=type).order_by(*sorting) context = { 'categories':Category.objects.filter(type=type), 'prods':prods, } return render(request,"products.html",context) models.py: class Product(models.Model): S=models.IntegerField(blank=True,null=True,default=0) #example value 2 M=models.IntegerField(blank=True,null=True,default=0) #example value 0 L=models.IntegerField(blank=True,null=True,default=0) #example value 1 I have removed the parts which I dont think is required here: What I am wanting to do is that for example if I pass L as size in url then the products should filter such that all products with L>0 are displayed . Also if a size is chosen such that for that size not a single product has size>0 for that size then I send a message in template accordingly. I tried several ways to implement it but they were inefficient.Any help would be appriciated.Thanks -
How to update the web page on a new "question" in Django
I'am Working On A Q&A; Web Application. It was completed, but i have noticed a small bug, that is- we have to manually refresh the page in order to get the latest questions posted. But i thought it would be much much better if the page refreshed automatically when a new question was posted. I did hours of research on this, but it didn't solve my problem. Here Are The Reference Links- Django refresh page https://www.codingforentrepreneurs.com/blog/ajaxify-django-forms/ https://docs.djangoproject.com/en/3.1/ref/contrib/messages/ Using Django How Can I Automatically Update Information on a Template auto refresh url in django I didn't manage to find any useful info for me to fix the bug, that is why i posted this question becuase i thought some help by the community Specifications- OS: Windows 10 Python: 3.7.7 Django: 3.0.8 Here Are The Files For The Project- views.py from django.shortcuts import render from django.views import generic as genr from .models import Question, Answer from django.contrib.auth import mixins as mxn from django.urls import reverse_lazy # Create your views here. class HomePage(genr.TemplateView): template_name = 'core/home_page.html' class QuestionListView(genr.ListView): model = Question class QuestionDetailView(genr.DetailView): model = Question def get_context_data(self, **kwargs): context = super(QuestionDetailView, self).get_context_data(**kwargs) context['answer_list'] = Answer.objects.all() return context class QuestionCreateView(mxn.LoginRequiredMixin, genr.CreateView): model = … -
login form is not working in django. it only shows 'invalid credentials, please try again'
when email and password fill up in login form it shows invalid credentials, please try again' instead of successfully logged in. after fill up the login form it only read else part of the code and shows message invalid credentials, please try again. signup form is working and data of signup form save in database but after signup when i come to login its not working correctly. urls.py from django.urls import path, include from account import views from django.contrib import admin urlpatterns = [ path('', views.account, name='account'), path('signup', views.signup, name='signup'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), ] views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.models import User, auth from django.contrib import messages from django.contrib.auth import authenticate, login, logout def login(request): if request.method == 'POST': # get the post parameters email = request.POST['email'] password = request.POST['pass'] user = authenticate(email=email,password=password) if user is not None: login(request, user) messages.success(request,'successfully logged in') return render(request, 'dashboard/dashboard.hmtl') else: messages.error(request, 'invalid credentials, please try again') return redirect('account') else: return HttpResponse('404 - Not Found') base.html <!doctype html> {% load static %} <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <title>{% block … -
raised unexpected: EncodeError(TypeError('Object of type Products is not JSON serializable'))
I am working on a django project. In the project I am scraping some data from a webpage and storing the result in a django model. I achieve all this with celery. I want to display the records in the django model in my django template. But I am getting the following error when I do that raised unexpected: EncodeError(TypeError('Object of type Products is not JSON serializable')) This is my code so far mainapp/tasks.py from celery import Celery from celery.schedules import crontab from celery import shared_task from .models import Products from .scrape import ScrapeFunction app = Celery('tasks') app.conf.beat_schedule = { # executes every 1 minute 'scraping-task-one-min': { 'task': 'tasks.display_record', 'schedule': crontab() } } @shared_task def get_website(website): ... return 'done' @shared_task(serializer='json') def display_record(): return Products.objects.all().last() All of the scraping happens through the get_website() task. This task calls scrape.py where all the scraping happens. scrape.py also save the record into the model. All of this is working fine. The error occurs when I want to display the record in the template. Please check the display_record() task. And here is the views.py file. mainapp/views.py def index(request): if request.method == 'POST': website = request.POST.get('website-name') get_website.delay(website) return redirect('output') return render(request, 'index.html') def output(request): record = … -
Postgres/python django import json dump database
I got json database dump file to import into postgres but this file is not sql file (which I know how to import) it is json file. Its structure looks like this: [ { "model": "model.name", "pk": 1, "fields": { "version": 1584369114566125, "field_a": "something", "field_b": "something" } }, { "model": "model.name", "pk": 1, "fields": { "version": 1584369114566125, "field_a": "something", "field_b": "something" } }, ... ] I want to import it but I don't know if is there option for importing database in such format and structure without writing sql function? I was trying to find if there is in documentation of pg_dump any option for exporting in json but I didn't find. My guess is also that server is written in django and maybe django has script for exporting/importing database in such file? -
Anyone knows django inline formset alternative for nodejs
I need something similar to Django inline form set to use in my nodejs application. I tried searching it out on npm and some forms but couldn't get any success. Any Help will be appreciated