Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve url parameter problem in Django?
I have a strange problem. I have a page that uses url parameters. Users can reach this site based on their project id and name and the group(csoport) name that stored in three models. This is a link for an example page: /performance/monthlyfeedback/{{ request.user.profile.csoport }} That link works fine if the name of the csoport is a number. If it is any kind of a text it gives me 404 error that I can't figure out why. models.py class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) csoport = models.CharField(max_length=100, null=True, blank=True) class Projekt_perf(models.Model): def __str__(self): return str(self.projekt_perf) projekt_perf = models.CharField(max_length=250) jogosult_01_perf = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) class Performance_profile(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE) projekt_perf = models.ForeignKey(Projekt_perf,on_delete=models.CASCADE) views.py I am using raw query in the views. def obj_results(request, projekt_perf_id, projekt_perf, user_name_id, csoport): person = Projekt_perf.objects.raw('SELECT * FROM performance_projekt_perf INNER JOIN performance_performance_profile ON performance_projekt_perf.id = performance_performance_profile.projekt_perf_id INNER JOIN stressz_profile ON performance_performance_profile.user_name_id = stressz_profile.user_id WHERE performance_projekt_perf.id = %s AND projekt_perf = %s AND stressz_profile.user_name_id = %s AND stressz_profile.csoport = %s',[projekt_perf_id, projekt_perf, user_name_id, csoport]) context = { 'person': person, } return render(request, 'performance/obj-results.html', context) urls.py app_name = 'performance' urlpatterns = [ path('monthlyfeedback/<int:projekt_perf_id>', login_required(views.Performance_test), name='performance_feedback'), path('list/<int:projekt_perf_id>/<projekt_perf>', … -
Preparing data for a form view (django, drf, axios, vuejs)
I'm building a web application with Django, DRF, Axios and Vuejs. It works but I'm wondering what are best practices for handling such a case. Considering the form below : I want to create an Item for which I can assign a Company and a Contact. The Company is a model in its own as well as the Contact. The Contact field shows only contacts for the selected Company. How should I query the datas to be the most RESTful possible ? Query all the companies, query all the contacts, and make a computed property that shows only contacts of the currently selected company ? Query all the companies, and each time I select a company I query related Contacts only ? Other solution ? Both have pros and cons and I wonder what is the best way to handle this kind of situation. Also, if there are standard ways to design this. -
How can i access javascript data in my django template for forloop iteration
I am using js to fetch api from django rest api and after fetching api i need to use length of fetched api obj in django template how can i do that? Or is there any other way which this problem can be solve by? ///////////////////////////////////////////js function for fetching api/////////////////////////////////// function getName() { fcom=document.getElementById('fcom').value; dep=document.getElementById('dep').value; console.log(fcom, dep) fetch(`http://localhost:8000/create-f-company-record/${fcom}/${dep}`, { method: 'GET', // or 'PUT' headers: { 'Content-Type': 'application/json', }, }) .then(response => response.json()) .then(data => { console.log(data) console.log(data.length) temdata=data.length if(data!="0"){ document.getElementById('length').value=5 document.getElementById('fdate').value=data.date document.getElementById('fcom').value=data.FCompany document.getElementById('dep').value=data.depostieAmount document.getElementById('pay').value=data.paymenetAmount document.getElementById('deppaydate').value=data.DepPAyDate document.getElementById('net').value=data.netAmount } else{ alert('Could not find data with this id') window.location.reload() } }) } ///////////////////////////////////////django template html file////////////////////////////////////// {% for tem in temdata %} {% endfor %} this temdata variable is inside js function -
UnboundLocalError at /api/registration/ even though I tried fixing it
Screenshot of the Error is at Error The Error I face is: UnboundLocalError at /api/registration/ local variable 'data' referenced before assignment Request Method: POST Request URL: http://217.160.170.83:81/api/registration/ Django Version: 3.2.12 Exception Type: UnboundLocalError Exception Value: local variable 'data' referenced before assignment Exception Location: /var/www/LWD/userAccount/views.py, line 128, in get_response_data Python Executable: /usr/bin/python3 Python Version: 3.8.10 Python Path: ['/var/www/LWD', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Sat, 26 Mar 2022 19:05:05 +0000 My Project Repository Link: https://github.com/Bilal815/LWD LWD/userAccount/views.py: from django.conf import settings from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework import permissions, status, viewsets from rest_framework.views import APIView from rest_framework.generics import ( ListAPIView, RetrieveAPIView, CreateAPIView, GenericAPIView, RetrieveUpdateAPIView, UpdateAPIView, ) from rest_framework.exceptions import PermissionDenied, NotAcceptable, ValidationError from allauth.account.views import ConfirmEmailView from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter from allauth.socialaccount.providers.twitter.views import TwitterOAuthAdapter from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client from rest_auth.registration.views import SocialConnectView, SocialLoginView from rest_auth.social_serializers import TwitterConnectSerializer from allauth.account.models import EmailAddress, EmailConfirmationHMAC from rest_auth.views import ( LoginView, PasswordResetView, PasswordResetConfirmView, PasswordChangeView, LogoutView, ) from rest_auth.serializers import PasswordResetConfirmSerializer from rest_auth.registration.views import RegisterView, VerifyEmailView from rest_auth.registration.serializers import VerifyEmailSerializer from rest_auth.app_settings import JWTSerializer from rest_auth.utils import jwt_encode from django.views.decorators.debug import sensitive_post_parameters from django.utils.decorators import method_decorator from django.contrib.auth.models import User, Permission from django.utils.translation import ugettext_lazy as _ from … -
I get the error "Cannot resolve keyword 'category' into field. Choices are: id" in MPTT
I want to create a subcategory with MPTT but I get the error "Cannot resolve keyword 'category' into field. Choices are: id". I can't find the reason. I would be happy if you half. I'm trying to edit dressing on the admin page. I'm trying to do this from a source I found on the internet. source:https://django-mptt.readthedocs.io/en/latest/models.html models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey # Create your models here. class Category(MPTTModel): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) keywords = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name class Product(models.Model): pass admin.py from django.contrib import admin from mptt.admin import DraggableMPTTAdmin from .models import Category, Product # Register your models here. class CategoryAdmin(DraggableMPTTAdmin): prepopulated_fields = {'slug': ('name',)} mptt_indent_field = "name" list_display = ('tree_actions', 'indented_title', 'related_products_count', 'related_products_cumulative_count') list_display_links = ('indented_title',) def get_queryset(self, request): qs = super().get_queryset(request) qs = Category.objects.add_related_count( qs, Product, 'category', 'products_cumulative_count', cumulative=True) qs = Category.objects.add_related_count(qs, Product, 'categories', 'products_count', cumulative=False) return qs def related_products_count(self, instance): return instance.products_count related_products_count.short_description = 'Kataqoriada olan məhsulların sayı' def related_products_cumulative_count(self, instance): return instance.products_cumulative_count related_products_cumulative_count.short_description = 'Alt kataqoriada olan məhsulların sayı' admin.site.register(Product) admin.site.register(Category, CategoryAdmin) Error: -
Django: I can't figure out how to save the model
I'm just learning django. And for 2 hours I can not understand what the mistake is. Model Blog class Blog(models.Model): title = models.CharField(max_length=255, verbose_name='Заголовок') text = RichTextField(verbose_name='Текст') date = models.DateField(auto_now_add=True, verbose_name='Дата') user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Автор') image = models.ImageField(verbose_name='Фото', upload_to='blog') tags = models.CharField(max_length=500, verbose_name='Теги', help_text='через кому') slug = AutoSlugField(populate_from='title', null=True) class Meta: verbose_name = 'Стаття' verbose_name_plural = 'Статті' def __str__(self): return self.title Model Comment class Comment(models.Model): name = models.CharField(max_length=100, verbose_name='Ім\'я') email = models.EmailField(verbose_name='Email', max_length=255) text = models.CharField(max_length=500, verbose_name='Коментар') datetime = models.DateTimeField(auto_now_add=True) article = models.ForeignKey(Blog, on_delete=models.CASCADE, verbose_name='Стаття') parent = models.IntegerField(verbose_name='Батьківський коментар') class Meta: verbose_name = 'Коментар' verbose_name_plural = 'Коментарі' def __str__(self): return self.name + ', ' + self.email Model CommentForm class CommentForm(ModelForm): class Meta: model = Comment fields = ['name', 'email', 'text'] widgets = { 'name': TextInput(attrs={'class': 'form-control form--control'}), 'email': TextInput(attrs={'class': 'form-control form--control'}), 'text': Textarea(attrs={'rows': 5, 'class': 'form-control form--control'}), } views.py def detail(request, slug): blog = Blog.objects.get(slug=slug) if request.method == 'POST': form = CommentForm(request.POST) form.article_id = blog.pk form.parent = 0 if form.is_valid(): form.save() else: form = CommentForm() return render(request, 'blog/blog_detail.html', context={'blog': blog, 'tags': blog.tags.split(','), 'form': form}) and I keep getting an error - (1048, "Column 'article_id' cannot be null"). I can't understand why, because I give it meaning. And yet: how … -
Auth0 login working only on localhost but won't redirect to my domain
I have no idea if I missed something, but I followed the Auth0 documentation and watched videos about is and set it up and everything works (localhost). Now I want to use it on my domain that I have. I added the settings for my domain over at auth0 website. But what happens is this I click on the login link on my website I go to the correct url http...../login/auth0 The request goes to the auth0 (my domain there) but with the redirect to localhost Removing the locahost from auth0 setting doesn't help since I'm still sending it as the return url. The issue here (I assume) are the arguments that I'm passing and I have no idea how to change them. I'm not sure if there is a way for creating a custom login view and then sending users over to auth0 or if there is some way to pass different value to the auth0 login view in order to change the returnTo url -
DJANGO: How to send and recieve data from a database with consumers
I have a working chat application made with Django. I want to send every last saved message from every group to one single group where they can all be preview. I have tried to do it for one group (General) so far but ran into problems. Here is my code: Consumers.py - Here is the first consumer for the messages that is working and the second one where I tried to send and receive the last message from group (General). import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from django.contrib.auth.models import User from .models import Message from channels.db import database_sync_to_async import datetime class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name print(self.room_group_name) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) @database_sync_to_async def get_user_profile(self): return self.scope['user'].profile async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = self.scope['user'].username profile = await self.get_user_profile() profile_pic = profile.image.url room = text_data_json['room'] date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") await self.save_message(username, room, message, date) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chatroom_message', 'message': message, 'username': username, 'profile_pic': profile_pic, 'date': date, 'room': room } ) async def chatroom_message(self, event): message = event['message'] username = event['username'] profile_pic … -
Circular Dependency Error when creating custom user for dj-stripe
I'm trying to create a subscription plan for my django app using stripe, essentially following the guide bellow to the letter: https://ordinarycoders.com/blog/article/django-stripe-monthly-subscription I'm using dj-stripe to sync my stripe products with my database. My problem is when I come to creating a custom user, I get a Circular Dependency Error when I attempt to migrate. from django.db import models from django.contrib.auth.models import AbstractUser from djstripe.models import Customer, Subscription class User(AbstractUser): customer = models.ForeignKey(Customer, null=True, blank=True, on_delete=models.SET_NULL, related_name='stripe_customer') subscription = models.ForeignKey(Subscription, null=True, blank=True, on_delete=models.SET_NULL, related_name='stripe_subscription') The full error: django.db.migrations.exceptions.CircularDependencyError: djstripe.0008_2_5, djstripe.0009_2_6, djstripe.0010_alter_customer_balance, custom_user.0001_initial, djstripe.0001_initial, djstripe.0007_2_4 I've tried deleting my database and all migrations, reinstalling the packages but nothing seems to work. Is there any way I can get around this? -
Django Infinite dynamic Multi-level nested category
I have three models for now suppose one is category another is subcategory and another is product. Before registering a product user should add subcategory and before adding subcategory we need to add category in subcategory table. So, now adding a products need to be like Men's Fashion (Category)-> Shirt(SubCategory)-> White shirt(Product). It is working fine and I have no issue with it. But there is sudden changes like If I need to add infinite subcategory suppose there maybe some products like to go through two subcategory Men's Fashion(Category) -> Footwear(SubCategory) -> Shoe(SubCategory) -> Premium shoe (Product) or maybe maybe some products like to go through two subcategory Men's Fashion(Category) -> Footwear(SubCategory) -> Shoe(SubCategory) -> Leather Shoe (Subcategory) -> Premium shoe (Product) It will depend on the user he can add as many as subcategory he wants. This has to be like dynamic but I am wondering how. If I take multiple data and add model dynamically (I don't know if I can do this with django because the how can I sync the db without using migrate command) this is pretty much confusing me and I am stuck here. Any kind of help would be really appreciated. class Category(models.Model): … -
Django JSON not being saved in sqlite database simply get an error and the database remains empty
I am trying to save JSON data to sqlite database on Django I have these small code chunks here which are giving me some problems. Here is a chunk of my models.py file class Recipes(models.Model): name = models.CharField(max_length=120, default='') pub_date = models.DateTimeField('date published') style = models.CharField(max_length=200, default='') brewer = models.CharField(max_length=100, default='') type = models.CharField(max_length=20, default='All Grain') version = models.CharField(max_length=20, default='1') batch_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_time = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) efficiency = models.DecimalField(decimal_places=1, max_digits=4, default=75.0) ibu = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) abv = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) notes = models.TextField(default='') carbonation = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) primary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) secondary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) __fermentables = [] @classmethod def create(cls,attr): recipe = cls() # do something with the book for k in Recipes._meta.fields: if k.name in attr: setattr(recipe,k.name,attr[k.name]) return recipe Here is the part of views.py which is giving me trouble def saveRecipe(request): try: data=json.loads(request.read()) print("printing values") print(data["name"]) #prints here works recipe = Recipes.create(attr=data) recipe.name = data["name"] recipe.save() recipe.addYeast(items=data["yeast"]) recipe.addFermentables(items=data["fermentables"]) recipe.addHops(items=data["hops"]) recipe.addMashStep(items=data["mash"]) return HttpResponse(serialize('json', [recipe]), content_type='application/json') except: return HttpResponse("error") Basically I have a button which parses JSON from filled forms and when I print name … -
How is the "required" attribute dynamically set on a MultiWidget?
There are 4x TextInput elements that comprise a MultiWidget. Only the first TextInput requires the required attribute. Yet required is being set on all four elements. Form.use_required_attribute is not suitable for my case due it's binary nature; either values for all form fields are required or not. I've set required=False to every possible place where it's potentially warranted, but I'm still not getting the desired result. How can I get just the first TextInput set to required? class MultiTagWidget(MultiWidget): def __init__(self, *args, **kwargs): widgets = [TextInput(attrs=kwargs['attrs']) for i in range(4)] super().__init__(widgets, *args, **kwargs) def decompress(self, value): if value: return value.split("_") return "" class TagField(MultiValueField): def __init__(self, *args, **kwargs): fields = [] for i in range(4): field = CharField(**{ "min_length": 1, "max_length": 25, "validators":[ RegexValidator("[<>`':;,.\"]", inverse_match=True) ] }) if i == 0: field.error_messages = { 'incomplete': "Provide at least 1 tag for your question" } field.required = True else: field.required = False fields.append(field) super().__init__(fields, *args, **kwargs) def compress(self, data_list): data_list = "_".join(list(set([tag.lower().strip() for tag in data_list]))) return data_list tags = TagField( widget=MultiTagWidget( attrs={"required": False} ), require_all_fields=False, help_text="Add up to 4 tags for your question" ) -
How to quickly see if all items in list of Primary Keys exist prior to bulk_create call?
I'm attempting to do a django bulk_create for a list of objects. However, every so often one of the objects in the bulk_create already exists (it's primary key has already been allocated) so an exception is raised and no objects get created. To fix this I added a loop over each of the new objects to test if they exist prior to the bulk_create call but this feels very inefficient. Is there way to accomplish the same result in fewer queries to the database? -
Is there a way to fill up a (multi)cell's remaining space with dots using pyfpdf2?
I'm currently working on a Django project in which the client needs to print reports where remaining spaces are filled up with dots up to the end of the line dynamically. I'm using the PyFpdf2 library for PDF reports. The outputs should look like this: This is line 1.................... This is line 2.................... I am using basic cells and multicells as: pdf = FPDF() pdf.add_page() pdf.set_font('Arial', '', 12) pdf.cell(40, 8, 'This is line 1........') Anyone can help? -
Django - class CreateView, how can I launch special function after success?
I have a form, where user can type song_name and upload .wav file in my views.py: from django.views.generic import CreateView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import AudioCompositionForm class AddAudio(LoginRequiredMixin, CreateView): form_class = AudioCompositionForm template_name = 'audio_test/add_audio.html' I have a special function which convert wav to mp3 How can I launch this function after success upload? Will be ideal if i can transfer a new object <class 'audio_test.models.AudioComposition'> into in my audio_convert funcion. Thanks -
How can I connect to postgresql database container from within another container?
It appears I can't access 127.0.0.1:5555 from my company_tasks container: version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data - ./init.sql:/docker-entrypoint-initdb.d/init.sql restart: always ports: - "5555:5432" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres rabbit: image: rabbitmq ports: - "5673:5672" depends_on: - db company_tasks: build: . command: > bash -c "pip install psycopg2-binary && pip install -r pip_requirements.txt && python manage.py migrate && python manage.py runserver && celery -A company_tasks worker -l info -B" volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db Though I can access it from the host system with: psql -h 127.0.0.1 -p 5555 -U postgres Company_tasks is a django app and it complains: company_tasks_1 | django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5555 failed: Connection refused company_tasks_1 | Is the server running on that host and accepting TCP/IP connections? my django settings.py: DATABASES = { 'default': { 'ENGINE': "django.db.backends.postgresql", 'NAME': 'company_tasks', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': '127.0.0.1', 'PORT': '5555', } } How Can I make database container visible to company_tasks container? I've tried setting up bridge networks but it didn't work. I can't use 5432 port on the host because another instance of postgres is taking it. -
Django translations does not work for admin panel
I am not able to translate the title of table in models. In models.py from django.utils.translation import ugettext_lazy as _ class Meta: verbose_name = _('Approval Status Table') In urls.py from django.conf.urls.i18n import i18n_patterns path("i18n/", include("django.conf.urls.i18n")), urlpatterns += i18n_patterns( path('admin/', admin.site.urls), ) In Settings.py SITE_ROOT = os.path.dirname(os.path.realpath(name)) LOCALE_PATHS = ( os.path.join(SITE_ROOT, 'locale'), ) I need to translate Admin table name to Swedish. Let me know why it is not working. -
How inheritance works in object-oriented programming in Python
The Question from a noob :) Creating a text field in a model in Django, we do the following: class Book(models.Model): title = models.CharField(max_length=200) CharField, is a class with the following chain of inheritance File: django.db.models.fields.init Classes: class Field(RegisterLookupMixin) / class CharField(Field) And models.Model that is used to registrate a model, in turn, has the following chain of inheritance: File: django.db.models.base Classes: class ModelBase(type) / class Model(metaclass=ModelBase): Questions: How models works when registering a model.CharField ? CharField is not a direct descendant of models, then why can we specify them after each other? When registering a model, we declare class Book(models.Model). Specify CharField in the fields. Why can we do this, despite the fact that they are not directly related by inheritance? -
Creating a list in JavaScript from django variable is autoparsing strings as dates
I'm working in a django project and I'm sending a dataframe with "to_dict" to the template. The dataframe consist of dates and extra info that I deleted for ease of understanding. Im using that data in javascript, but I need the date as a string as the lib I'm using doesn't support date objects for some reason. The problem comes that when I make a list out of the parameter the dates get parsed automatically without me doing anything extra. So for this lines of code: listData = {{data|safe}}; console.log({{data|safe}}); console.log(listData); I get this result: So what i need is that creating a list doesn't parse the string to date and if possible the reason why is this happening. -
KeyError 'Django' and ValueError: source code string cannot contain null bytes
I'm working on an API project. I just stopped my server using CTRL + C as usual only for me to restart the server and i'm getting this error below. I have tried downgrading django but still same error and this the first time i'm having such error since i started this project. from rest_framework import VERSION, exceptions, serializers, status File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\rest_framework\serializers.py", line 27, in <module> import coreapi File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreapi\__init__.py", line 2, in <module> from coreapi import auth, codecs, exceptions, transports, utils File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreapi\codecs\__init__.py", line 3, in <module> from rest_framework.compat import postgres_fields File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\rest_framework\compat.py", line 32, in <module> from coreapi.codecs.corejson import CoreJSONCodec File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreapi\codecs\corejson.py", line 8, in <module> import coreapi File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreapi\__init__.py", line 2, in <module> import coreschema File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreschema\__init__.py", line 6, in <module> from coreapi import auth, codecs, exceptions, transports, utils File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreapi\codecs\__init__.py", line 3, in <module> from coreschema.encodings.html import render_to_form File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreschema\encodings\html.py", line 2, in <module> from coreapi.codecs.corejson import CoreJSONCodec File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreapi\codecs\corejson.py", line 8, in <module> import jinja2 ValueError: source code string cannot contain null bytes import coreschema File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreschema\__init__.py", line 6, in <module> PS C:\Users\Chika Precious\Documents\GitHub\vicsite> -
How edit the value of post inside serializer in Django?
I am using Django and Django Rest Framework. Below the Register serializer is given and the user's birthday in datetime format. However the birthdate sent inside post is in timestamp format. I want to convert timestamp that posted from user's device to datetime inside serializer. How to do it? class Register_Serializer(serializers.ModelSerializer): password2 = serializers.CharField(style={"input_type": "password"}, write_only=True) class Meta: model = Tuser fields = [Constants.EMAIL, Constants.PASSWORD, Constants.PASSWORD2, Constants.BIRTH_DATE] extra_kwargs = { "password": {"write_only": True} } def save(self): user = Tuser(email=self.validated_data[Constants.EMAIL]) password = self.validated_data[Constants.PASSWORD] password2 = self.validated_data[Constants.PASSWORD2] birthday = self.vlidated_date[Constants.BIRTH_DATE] if password != password2: raise serializers.ValidationError({"password": "Passwords do not match"}) user.set_password(password) user.save() return user -
Django Rest Framework return one model inside another model's detail view
Trying to build a forum clone. There are a list of boards. Each board contains a list of threads. Each thread contains a list of posts. I'm confused about some things. Is the BoardDetail view returning a list of threads the correct approach? I'm not sure how that can be achieved. Here is my attempt. views.py class BoardDetail(generics.ListAPIView): # what needs to be done here to return the threads belonging to a particular board? queryset = Thread.objects.filter() serializer_class = ThreadSerializer models.py class Board(models.Model): name = models.CharField(max_length=25, primary_key=True) created = models.DateTimeField(auto_now_add=True) board_admin = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='board_admin') board_moderator = models.ManyToManyField(User, related_name='board_moderator') class Meta: ordering = ['created'] class Thread(models.Model): title = models.CharField(max_length=250) created = models.DateTimeField(auto_now_add=True) thread_admin = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='thread') board_id = models.ForeignKey(Board, on_delete=models.CASCADE, related_name="thread") class Meta: ordering = ['created'] -
How do I get the id of a Foreign Key
I am trying to autofill these fields if the foreign key is selected The Base Class: class ScreeningCamp(models.Model): beneficiary=models.ForeignKey(Beneficiary,on_delete=models.CASCADE) name=models.CharField(max_length=200,default=Beneficiary.objects.get(id=beneficiary.id).name,blank=True) dob=models.DateField(default=Beneficiary.objects.get(id=beneficiary.id).dob,blank=True) gender=models.CharField(max_length=200,choices=GENDER_CHOICES,default=Beneficiary.objects.get(beneficiary.id).gender,blank=True) fatherName=models.CharField(max_length=200) motherName=models.CharField(max_length=200) careGiver=models.CharField(max_length=200,default=Beneficiary.objects.get(id=beneficiary.id).careGiversName,blank=True,null=True) relationship=models.CharField(max_length=200,choices=RELATIONSHIP_CHOICES,default=Beneficiary.objects.get(id=beneficiary.id).relationship,blank=True,null=True) address=models.TextField(Beneficiary.objects.get(id=beneficiary.id).address,blank=True,null=True) village=models.CharField(max_length=200,default=Beneficiary.objects.get(id=beneficiary.id).village,blank=True,null=True) phone=models.CharField(max_length=13,blank=True,null=True,default=Beneficiary.objects.get(id=beneficiary.id).phone,) designation=models.CharField(max_length=200,choices=DESIGNATION_CHOICES,default=Beneficiary.objects.get(id=beneficiary.id).designation,blank=True,null=True) disability=models.CharField(max_length=200,choices=DISABILITY_CHOICES) visitedBy=models.CharField(max_length=200) def __str__(self): return self.name The Parent Class: class Beneficiary(models.Model): image=models.ImageField(upload_to='home/images/',blank=True,null=True) name = models.CharField(max_length=200) gender=models.CharField(max_length=6,choices=GENDER_CHOICES,default='male') dob=models.DateField() registrationDate=models.DateField() uidOrAadhaar=models.CharField(blank=True,max_length=12,null=True) careGiversName=models.CharField(max_length=200,blank=True,null=True) reletionship=models.CharField(max_length=200,choices=RELATIONSHIP_CHOICES,default='other',blank=True,null=True) beneficiaryType=models.CharField(max_length=200,choices=BENIFICIARY_TYPE_CHOICES,default='active') statusOfBeneficiary=models.CharField(max_length=200,choices=STATUS_OF_BENIFICIARY_CHOICES,default='red') address=models.TextField(blank=True,null=True) district=models.CharField(max_length=200,blank=True,null=True) city=models.CharField(max_length=200) pinCode=models.CharField(max_length=200,blank=True,null=True) addressType=models.CharField(max_length=200,choices=ADDRESS_TYPE_CHOICES,blank=True,null=True) phone=models.CharField(max_length=13,blank=True,null=True) email=models.EmailField(blank=True,null=True) diagonisis=models.CharField(max_length=200,choices=DIAGONISIS_CHOICES) diagnosedBy=models.CharField(max_length=200,choices=DIAGNOSED_BY_CHOICES,default="") informedBy=models.CharField(max_length=200,default='') designation=models.CharField(max_length=200,choices=DESIGNATION_CHOICES,default="") symptomsAsInformed=models.TextField(blank=True,null=True) educationHistory=models.CharField(max_length=200,choices=EDUCATION_HISTORY_CHOICES) maritialStatus=models.CharField(max_length=200,choices=MARTIAL_STATUS_CHOICES,blank=True,null=True) occupation=models.CharField(max_length=200,blank=True,null=True) skill=models.CharField(max_length=200,blank=True,null=True) birth=models.CharField(max_length=200,choices=BIRTH_CHOICES,blank=True,null=True) durationOfIllness=models.CharField(max_length=200,choices=DURATION_OF_ILLNESS_CHOICES,blank=True,null=True) pastPyschiatricIllness=models.CharField(max_length=200,choices=PAST_PYSCHIATRIC_ILLNESS_CHOICES,blank=True,null=True) gp=models.CharField(max_length=200) village=models.CharField(max_length=200) family_history_of_MI_present_or_absent=models.BooleanField(default=False) if_present_schizophrenia_or_mania_or_depression=models.BooleanField(default=False) def __str__(self): return self.name class Meta: verbose_name_plural = "Beneficiaries" I just want to autofill name, dob etc from the beneficiary class when the foreign key is selected When it is not selected we have to manually do it I think just getting the id of the selected object will help Can anyone please tell me how to do that? -
How to fix Django's "too many values to unpack (expected 2)" error?
I was trying to create the sending-verification-code system for the whole afternoon. It's like this: serilizer.py class RegisterationSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True, help_text=_("Enter a valid password")) repeated_password = serializers.CharField(write_only=True, required=True, help_text=_("Enter your password again")) def to_internal_value(self, data): email = data["email"] user = User.objects.get(email=email) if User.objects.filter(email=email, is_active=False).exists(): if VerficationCode.objects.filter(user=user).values("expire_date")[0]['expire_date'] < utc.localize(datetime.now()): VerficationCode.objects.filter(user=user).delete() verification_code = give_code() VerficationCode.objects.create(user=user, code=verification_code) send_mail("Verification Code", f"your code is: {verification_code}", "nima@gmail.com", [email]) return Response({"Message": "A verification code has been sent to your email"}, status=status.HTTP_200_OK) elif VerficationCode.objects.filter(user=user).values("expire_date")[0]['expire_date'] >= utc.localize(datetime.now()): raise serializers.ValidationError(_("Your verification code is still valid")) return super().to_internal_value(data) class Meta: model = User fields = ["email", "username", "name", "password", "repeated_password"] extra_kwargs = { 'email': {'help_text': _("Enter your email")}, 'username': {'help_text': _("Enter your username")}, 'name': {'help_text': _("Enter your name"), 'required': False, 'allow_blank': True}, } def validate(self, data): print(User.objects.filter(email=data["email"], is_active=False)) if data["password"] and data["repeated_password"] and data["password"] != data["repeated_password"]: raise serializers.ValidationError(_("Password and repeated password must be the same")) if data["email"].strip() == data["username"].strip(): raise serializers.ValidationError(_("Email and username must be different")) return data This code is overriding the is_valid() method in the user registration serializer. But when I send another response with the username and password of an account that is existed but it's not active and the first inner if in the to_interval... … -
Django cannot show image
I use django in Ubuntu. I set static_url, static_root, media_url and media_root in settings.py like this code. settings.py DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'static','media') In index.html I set image like this code. index.html <img class="rounded mx-auto d-block" width="25%" src="../media/images/iot_logo.png"> After that, I use command django-admin collectstatic and open website but it not show image. How to fix it?