Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Data retrieval from two models that are related to each other with user model
I have two models that are not related to each other but both of them are related to the user model. // modelA class ModelA(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(null=False) ... // modelB class ModelB(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) category = models.CharField(null=False) ... When I want to return ModelB information, I need to return the name field of ModelA that their user is the same. How can I do this? I tried several times but to no avail like this: @api_view(['GET']) def retrieve_model_b(request, id): try: from django.db.models import Q _qs = ModelB.objects.filter(Q(company__sahamdar__exact=id)) serializer = SahamdarSerializer(_qs, many=True) return Response(serializer.data, status=status.HTTP_200_OK) ... Serializer is as follow: class ModelBSerializer(serializers.ModelSerializer): name_of_user = PrimaryKeyRelatedField( source='modela_set', many=False, read_only=True, ) class Meta: model = ModelB fields = ('id', 'name_of_user', 'category') -
Inner join and group by in django REST framework
I am new in Django Rest Framework This is my query in SQL SELECT p7_test.professionals.full_name,count(p7_test.job_applications.pro) totalapply FROM p7_test.professionals inner join p7_test.job_applications on p7_test.professionals.id= p7_test.job_applications.pro group by p7_test.professionals.full_name; I want to do it in Django REST Framework -
How to use Djoser with multiple extended users?
Hello I am new to django django rest framework and djoser I was just wondering. How do I use djoser with multiple extended users. Below is my model, serializers and views. Model: I am trying to inherit user with the student model and teacher model (as seen below). I want djoser to use these two model to create the users. from django.db import models from django.contrib.auth.models import User from django.conf import settings # Create your models here. class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='student') age = models.IntegerField() address = models.CharField(max_length=200) def __str__(self): return self.user.username class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='teacher') description = models.TextField() def __str__(self): return self.user.username class Course(models.Model): name = models.CharField(max_length=200) description = models.TextField() price = models.FloatField(default=25.00) def __str__(self): return self.name Serializer: My serializer is not finished yet I still have to override the create and update methods. from rest_framework import serializers from api.models import * from django.contrib.auth.models import User class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('age', 'address') class StudentUserSerializer(serializers.ModelSerializer): student = StudentSerializer() class Meta: model = User fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name', 'student') extra_kwargs = {'password': {'write_only': True, 'required': True}} class TeacherSerializer(serializers.ModelSerializer): class Meta: model = Teacher fields = … -
Error in Django Channel during WebSocket handshake: Unexpected response code: 500
I was following the this tutorial on youtube. The browser gives an error "(index):21 WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/asas/' failed: Error during WebSocket handshake: Unexpected response code: 500 (anonymous) @ (index):21" Code: chatroom.html <script> const roomName = JSON.parse(document.getElementById('room-name').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); console.log(data) document.querySelector("#user-hello").innerHTML = (data.tester) } </script> chat/routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatRoomConsumer), ] chat/comsumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer 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 await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.channel_layer.group_send( self.room_group_name, { 'type': 'tester_message', 'tester': 'Hello World', } ) async def tester_message(self, event): tester = event['tester'] await self.send(text_data = json.dumps({ 'tester':tester })) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) settings.py STATIC_URL = '/static/' ASGI_APPLICATION = "core.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } -
heroku procfile problem : ModuleNotFoundError: No module named 'myApp.wsgi'
I' m deploying my first django app on heroku. After deploy the heroku doesn't launch my app. After checking heroku logs --tail I have got an error: : ModuleNotFoundError: No module named 'tabele.wsgi' My procfile looks like: web: gunicorn tabele.wsgi:application --log-file - I tries also: web: gunicorn tabele:app web: gunicorn tabele.wsgi --log-file - I'm beginner and I don't understand if (in my case 'tabele') should be folder containing manage.py or the different one? In my project folders including manage.py and another one including settings.py and wsgi.py has the same name "tabele" Could you explain me what is what in procfile file for better understanding? Any idea what I'm doing wrong? -
Django get all Model Instances that are within 2 hours of timeframe
As a Django beginner I struggle with a very basic problem: Filter a table based on the date difference of two rows. I have the following model: class DataPoint(models.Model): uid = models.CharField(max_length=128) timestamp = models.DateTimeField(auto_now_add=True) and I want to extract data points that have the same UID and are all within the range of e.g. 2 hours. I could of course use something like: DataPoint.objects.filter(uid=uid, timestamp__range=[timezone.now - timedelta(2), timezone.now]) but that would only return everything within the same 2 hour frame from now, but not dynamically given the DataPoint's timestamp. So this data set: (1) DataPoint: 2021-03-07 12:40 (2) DataPoint: 2021-03-07 11:40 (3) DataPoint: 2021-03-07 10:50 (4) DataPoint: 2021-03-07 08:55 would only return (1), (2), (3) with the query above, even though (4) is still considered connected, as it's within a 2h timeframe of (3). Been trying to get this to work with a RECURSIVE RAW SQL, as I thought this was the only way to do it with Django, but it's not working as expected either. WITH RECURSIVE previous AS ( SELECT id, uid_id, timestamp FROM core_datapoints WHERE id = %s UNION ALL SELECT s.id, s.uid_id, s.timestamp FROM core_datapoints s WHERE uid_id = s.uid_id AND (timestamp - INTERVAL '2 … -
Django group by Many to many in models
I have Model like this Class TaskEntry name = date = goals = models.ManyToManyField(Goal, blank=True) I want to get no of tasks done per goal on per day Example ENtry will be like Task1 5 March goals['Goal1', 'Goal2'] Task2 5 March goals['Goal1', 'Goal3'] Task3 5 March goals['Goal2', 'Goal3'] Task5 5 March goals['Goal1', 'Goal7'] I want result like 5 March Goal1 3 5 March Goal2 2 5 March Goal3 2 5 March Goal7 1 -
NoReverseMatch at /article/add/
I've been building my blog in Django and been able to add a list view and an article detail view but my add view isn't working. I have tried every suggestion I saw online. None of them work for me. Here is my add post HTML {% extends "base.html" %} {% load static %} {% block content %} <br> <br> <br> <div class="container" style="margin-top: 2rem; margin-bottom: 2rem;"> x <h1>Add Blog Post</h1> <form action="{% url 'article-detail' post.slug %}" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-primary"> Post </button> </form> </div> {% endblock content %} Here is my urls.py from django.urls import path from .views import ArticleListView, AddPostView, ArticleDetailView urlpatterns = [ path('', ArticleListView.as_view(), name='index'), path('article/add/', AddPostView.as_view(), name='add-post'), path('article/<slug:slug>/', ArticleDetailView.as_view(), name='article-detail'), ] Here are my class based views from django.db import models from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView from .models import Post # Create your views here. class ArticleListView(ListView): model = Post template_name = 'index.html' paginate_by = 3 class AddPostView(CreateView): model = Post template_name = 'add_post.html' fields = '__all__' context_object_name = 'post' class ArticleDetailView(DetailView): model = Post template_name = 'article_detail.html' context_object_name = 'post' -
how to can i insert varients and UOM as ManyToManyField
Hello I am trying to build and e-commerce project using django and vue. Here is my Product Model: class UOM(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Varients(models.Model): title = models.CharField(max_length=120) def __str__(self): return self.title class Product(models.Model): title = models.CharField(max_length=100, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.IntegerField() brand = models.ForeignKey(Brand, null=True, on_delete=models.CASCADE) img = models.ImageField(upload_to="images/", null=True, blank=True) uoms = models.ManyToManyField(UOM, null=True, blank=True, default="Please Enter UOM") varients = models.ManyToManyField(Varients, null=True, blank=True, default="Please Select Varients") description = models.TextField(max_length=350, null=True, blank=True) def __str__(self): return self.title Here i have UOM and vairents model which i took in product as ManyToMany Field. But i dont know how can i add to cart using django and vue.js Though i can only pass these : HEre is my api.py for add to cart : def api_add_to_cart(request): data = json.loads(request.body) jsonresponse = {'success': True} product_id = data['product_id'] update = data['update'] quantity = data['quantity'] cart = Cart(request) product = get_object_or_404(Product, pk=product_id) if not update: cart.add(product=product, quantity=1, updated_quantity=False) else: cart.add(product=product, quantity=quantity, updated_quantity=True) return JsonResponse(jsonresponse) here is add function for adding a product to a cart def add(self, product, quantity=1, updated_quantity=False): product_id = str(product.id) price = product.price if product_id not in self.cart: self.cart[product_id] = {'quantity':0, 'price': price, 'id': product_id} … -
django.contrib.auth.login does not log the user in
I created a custom User model like the following: class User(AbstractBaseUser): class Types(models.TextChoices): CUSTOMER = 'CUSTOMER', 'Customer' SUPPLIER = 'SUPPLIER', 'Supplier' OPERATOR = 'OPERATOR', 'Operator' base_type = Types.CUSTOMER objects = UserManager() phone = models.IntegerField(unique=True) code = models.IntegerField(blank=True, null=True) type = models.CharField(max_length=20, choices=Types.choices, default=base_type) date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] class Meta: verbose_name = 'user' verbose_name_plural = 'users' def __str__(self): return str(self.phone) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin And a manager for the User model: class UserManager(BaseUserManager): def create_user(self, phone, code=663322, password=None): if not phone: raise ValueError('Users must have a phone number') user = self.model( phone=phone, code=code, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, code=663322, password=None): user = self.create_user( phone=phone, code=code, password=password, ) user.is_admin = True user.save(using=self._db) return user I wanted to have 3 different user types (customer, supplier, operator) so I created 3 profile models and having a OneToOneField to the base user model for each profile model (with some specific fields related to the user type). I also created 3 proxy models like so: class Customer(User): objects = CustomerManager() base_type = User.Types.CUSTOMER class Meta: proxy = True class Supplier(User): … -
Django dj-rest-auth registration
I'm using dj-rest-auth registration, which enables to override register serializer and that's what I'm trying to do. Unfortunately I don't know how I am supposed to do that given my models: class CustomUser(AbstractUser): username = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=100, unique=True) date_joined = models.DateTimeField('date joined', default=timezone.now) year = models.IntegerField(blank=True, null=True) university = models.ForeignKey(University, related_name='students', on_delete=models.CASCADE) class RegisterSerializer(serializers.Serializer): username = serializers.CharField( max_length=40, min_length=3, required=True ) email = serializers.EmailField(required=True) password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) year = serializers.IntegerField(required=True, write_only=True) def validate_username(self, username): username = get_adapter().clean_username(username) return username def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( "A user is already registered with this e-mail address." ) return email def validate_password1(self, password): return get_adapter().clean_password(password) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError("The two password fields didn't match.") return data def custom_signup(self, request, user): user.year = self.validated_data.get('year', '') user.university = University.objects.filter(name=self.validated_data.get('university', '')) user.save(update_fields=['year']) def get_cleaned_data(self): return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'year': self.validated_data.get('year', '') } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) self.custom_signup(request, user) setup_user_email(request, user, []) return user My question is how to add my university foreign key to a register serializer, to enable … -
Rename the default django table
Rename the default django table. I can't change the default table name django_sessions Could anyone help? Thanks for listening model.py from django.contrib.sessions.models import Session Session._meta.db_table = "my_session" -
Exception Value: Field 'id' expected a number but got ''
(I searched this error on stackoverflow and tried the solution ideas bu they did not work.) In my Django Project, I tried to add a like button into my article detail page. If users like the article they click the like button and return the same article page. I saw this video on Youtube and wrote the same code by changing name of the some values according to my project. But I encountered an error which says Field 'id' expected a number but got ''. I read some solutions on Stackoverflow and tried to delete migrations files (except init.py) and then I wrote python manage.py makemigrations and then python manage.py migrate. Unfortunately , it did not work. I want to share my code so maybe, I hope, you can give me some solution ideas. model.py class Article(models.Model): author = models.ForeignKey("auth.User", on_delete = models.CASCADE, verbose_name="Kullanıcı") title = models.CharField(max_length = 50, verbose_name="Başlık") content = RichTextField() created_date = models.DateTimeField(auto_now_add = True, verbose_name="Oluşturma Tarihi") likes = models.ManyToManyField(User, related_name='blog_post') urls.py urlpatterns = [ path('dashboard/',views.dashboard, name ="dashboard"), path('addarticle/',views.addarticle, name ="addarticle"), path('article/<int:id>',views.detail, name ="detail"), path('update/<int:id>',views.updateArticle, name ="update"), path('delete/<int:id>',views.deleteArticle, name ="delete"), path('',views.articles, name ="articles"), path('comment/<int:id>',views.addComment, name ="comment"), path('like/<int:id>',views.LikeView, name ="like_post"), ] views.py def LikeView(request, id): post = get_object_or_404(Article, … -
Django web page opening but not loading in browser
I am using Visual Studio Code for coding python using django framework. But when I open the http://127.0.0.1:8000/ on my browser it always shows waiting for 127.0.0.1:8000 but he page never loads -
.map is not a function reactjs
So I'm following this tutorial, https://www.udemy.com/course/django-with-react-an-ecommerce-website/, but with some custom HTML template that I made. I keep getting the error .map() is not defined. As the udemy course is more so for Django developers, I am a little lost of the react side. Below is my HomeScreen.js page that is supposed to display products. import React from 'react'; import products from '../products' function HomeScreen() { return ( <section class = "w3l-ecommerce-main"> <div class = "ecom-contenthny py-5"> <div class = "container py-lg-5"> <h3 class = "hny-title mb-0 text-center">Shop With<span>Us</span></h3> <p class = "text-center">Handpicked Favourites just for you</p> <div class = "ecom-products-grids row mt-lg-5 mt-3"> { products.map(products => ( <div key = {products._id} class = "col-lg-3 col-6 product-incfhny mt-4"> <div class = "product-grid2 transmitv"> <div class = "product-image2"> <a href = "#"> <img class = "pic-1 img-fluid" src = "/images/shop-1.jpg"/> <img class = "pic-2 img-fluid" src = "/images/shop-11.jpg"/> </a> <ul class = "social"> <li><a href = "#" data-tip = "Quick View"> <span class = "fa fa-eye"></span></a></li> <li><a href = "#" data-tip = "Add to Cart"><span class = "fa fa-shooping-bag"></span></a></li> </ul> <div class = "transmitv single-item"> <form action="#" method = "post"> <input type="hidden" name="cmd" value="_cart"> </input> <input type="hidden" name="add" value="1"> </input> <input type="hidden" … -
VSCode not auto completing python module import
My VSCode editor suddenly stopped listing suggestion when am running import statements. ie. from django.shortcuts import render, redirect, get_object_or_404, get_list_or_404, HttpResponse normally when I type: from django. it should suggest all packages in django or when I type from django.shortcuts import it again should suggest render, get_object_or_404 etc. But this is not more happening. I have to painstakingly type these out myself. please any help would be highly appreciated. Thanks a lot. -
Including another URLconf doesent work, in parent app
I'm facing a problem in the last few days with Django URLs and include(). I'm doing an toturial online to create a chat app using django, and I'm using the newest version of django. my parent app named mySite, and my sub-app called chat. chat.urls from django.urls import path from .import views urlpatterns = [ path('', views.index), ] chat.views from django.shortcuts import render def index(request): return render(request , 'chat/index.html') . ##########################################################################################3 I'm trying to include the chat.URLs in the parent app mySite.urls but I'm getting an error page after I runserver. i tried to migrate and still is not working. mySite.URLs from django.contrib import admin from django.urls import path from django.urls import include from chat import urls urlpatterns = [ path('admin/', admin.site.urls), path('chat/', include('chat.urls')), ] -
How to fix slugs implemented in Django?
I am using django to create a blog where all posts are shown on the home page as well as on pages depending on their subject. While the basics as shown work, I am having great difficulty with the following: For each subject page I would like the url to include ~/subject_slug/ Currently I am getting ~/subject/subject_slug When I eliminate subject/ from urls.py (line 8), I get the desired ~/subject_slug only. HOWEVER, the individual posts cannot now be accessed. Error: Subject.DoesNotExist: Subject matching query does not exist. Line 21 in views.py is pointed to. There I have tried to include either Subject, or subject, in the bracket before subject_slug=subject_slug. Unfortunately that shows: UnboundLocalError: local variable 'subject' referenced before assignment. Attempts with adding subject to the post_detail view have also not worked. For each post I would like the url to include ~/subject_slug/slug/ Therefore I added str:subject_slug/ to urls.py line 10. This throws the error: NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with arguments '('a-slightly-longer-post',)' not found. 1 pattern(s) tried: ['(?P<subject_slug>[^/]+)/(?P[^/]+)/$']. models.py from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import slugify class Subject(models.Model): subject = models.CharField(max_length=200) subject_slug = … -
Connect uploaded file to a post in Django
I am trying to connect an uploaded document with the related post in Django. The idea is that when a user creates a post (I called it seed in my code), he can upload a document with it if he wants to. I tried using the joint method to do so, but it is not working (either telling me it expects an "str" and not an "int" or telling me the ForeignKey condition is not working). Is there any way to then connect those two classes, and successfully upload a file? Thank you for any help!! Here is what I tried: views.py """ def seed_create(request): if request.method == "POST": seed_form = SeedForm(request.POST) docu_form = DocumentForm(request.POST, request.FILES) if seed_form.is_valid() and docu_form.is_valid(): seed_form.instance.user = request.user docu_form.save() seed_form.save() messages.success(request, 'Your seed was successfully created!') return redirect('seed:view_seed') else: messages.error(request, 'Please correct the error below.') else: seed_form = SeedForm(request.POST) docu_form = DocumentForm(request.POST, request.FILES) return render(request, "seed/create.html", context={"seed_form": seed_form, "docu_form": docu_form}) """ models.py """ def gallery_folder(instance, file): return '/'.join(['documents', instance.seed_related_id, file]) class Document(models.Model): seed_related = models.ForeignKey(Seed,on_delete=models.CASCADE,default=1) description = models.CharField(max_length=255, blank=True) file = models.FileField(default="No file",upload_to=gallery_folder) uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title """ forms.py """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('description', 'file') """ -
pass form instance in django formview
I have a forms.py file as class SocialMediaForm(forms.ModelForm): class Meta: model = SocialMedia fields = "__all__" exclude = ("doctor",) labels = {} widgets = { "whatsapp": forms.TextInput(attrs={"class": "form-control"}), "telegram": forms.TextInput(attrs={"class": "form-control"}), "facebook": forms.TextInput(attrs={"class": "form-control"}), "instagram": forms.TextInput(attrs={"class": "form-control"}), "linkedin": forms.TextInput(attrs={"class": "form-control"}), } with a view.py file class SocialMediaProfile(FormView): model = DoctorSocialMedia form_class = SocialMediaForm success_url = "." template_name = "doctor/social_media_profile.html" the question is how could i pass a form instance to template in FormView view as SocialMediaForm(instace=someInstance) # in fun based views. -
Unable to send e-mail from Django EmailBackend but it works by simply using smtplib with the same SMTP parameters
I'm trying to send an e-mail to the user on registration using taigaio, which is based on Django. Here are my current SMTP settings (I didn't yet switched to SSL but I'm planning to): DEFAULT_FROM_EMAIL=noreply@server.org EMAIL_HOST_USER=noreply EMAIL_HOST_PASSWORD="thesupersecretpassword" EMAIL_HOST=smtp.server.org EMAIL_PORT=25 EMAIL_USE_TLS=False EMAIL_USE_SSL=False But the browser raises a 500 Internal Server Error and I got on the server side: (...) File "/taiga-back/taiga/auth/services.py", line 62, in send_register_email return bool(email.send()) File "/opt/venv/lib/python3.7/site-packages/django/core/mail/message.py", line 306, in send return self.get_connection(fail_silently).send_messages([self]) File "/opt/venv/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages new_conn_created = self.open() File "/opt/venv/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 70, in open self.connection.login(self.username, self.password) File "/usr/local/lib/python3.7/smtplib.py", line 710, in login raise SMTPException("No suitable authentication method found.") smtplib.SMTPException: No suitable authentication method found. I also tried to simply send a mail using smtplib as follow (inspired from https://mkyong.com/python/how-do-send-email-in-python-via-smtplib/) to see if I can figure out what's wrong: import smtplib to = 'me@gmail.com' email_user = 'noreply' smtpserver = smtplib.SMTP("smtp.server.org", 25) header = 'To:' + to + '\n' + 'From: ' + email_user + '\n' + 'Subject:testing \n' msg = header + '\n Sending test message. from noreply@server.org \n\n' smtpserver.sendmail(email_user, to, msg) smtpserver.close() And it works fine, I do receive that e-mail. Did I miss something in the Django config for sending e-mails? -
Creating a Formset which relates to Custom User (AbstractUser)
I have a use case here and I don't know how to go about it. I have Custom User and this works well when adding a new user. But then I have another model which I would like the Custom User to populate. It is kind of link a main form subform approach but no data on the main form is going to be edited but only creating new records on the formset (subform). from django.core.validators import RegexValidator from sos.models import Company from django.db import models from django.contrib.auth.models import AbstractUser from django.core.validators import MinValueValidator, MaxValueValidator from django.urls import reverse # page 138 Django for Beginneers # Create your models here. # https://stackoverflow.com/questions/19130942/whats-the-best-way-to-store-phone-number-in-django-models/19131360 class CustomUser(AbstractUser): position = models.CharField(max_length=30, null=True ) email = models.EmailField(null=True, blank=False, unique=True ) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") mobile_phone = models.CharField(validators=[phone_regex], max_length=17, blank=False, null=True, unique=True) date_created = models.DateTimeField(auto_now_add=True, editable=True) is_staff = models.BooleanField(verbose_name="Is Staff Admin?", help_text="Designates whether this user should be able to log in the Admin Interface.") company = models.ForeignKey(Company , on_delete=models.CASCADE, verbose_name="Company Name") def __str__(self): return self.username def get_absolute_url(self): return reverse("customuser_detail", args=[str(self.id)]) class Meta: ordering = ["username"] # email_address = models.EmailField(null=True, blank=False, unique=True ) class … -
Simplest example for Django Meta (SEO)
I want to add these meta tags to every article in a Django blog: title, description, keywords I'm using : Python 3.7, Django 3 I've been searching for it and found DJANGO-META package best to use (in this link : djangopackages.org/grids/g/seo/ ) mostly because of the regular updates. Other packages like DJANGO-SIMPLE-SEO and DJANGO-SEO2 meet my needs but they don't update regularly and are not compatible with the newer versions of Django. The problem is that the DJANGO-META package is not easy to understand (at least for me :) ). Can anyone please explain how to implement the DJANGO-META in a project with the easiest example possible? -
Pdf file created throw following error, file response has no read attribute
I am trying to save pdf file inside directory , pdf file is properly created but it does not contains data and throw error. def file_pdf_to_merge(id): flow_obj=flow_obj_for_display(id) buffer = io.BytesIO() doc = SimpleDocTemplate(buffer) doc.build(flow_obj) buffer.seek(0) file_nm=file_name_only(id) response= FileResponse(buffer,as_attachment=True,filename=file_nm) fs=FileSystemStorage() if fs.exists(file_nm): fs.delete(file_nm) fs.save(file_nm,response) code throws following error. I think due to this error pdf file created is also corrupt or not properly decoded. 'FileResponse' object has no attribute 'read' thanks -
When I Submit Form I Got This Errors Field 'id' expected a number but got Why i got this errors ? What's wrong in my code :(
views---------- def update(request): if request.method == 'POST': aa = Add_Ep(request.POST) print("this is id:") Title = Add_Ep.Ep_Title print(Add_Ep) aa.save() return redirect('/') else: aa = Add_Ep() Form class add_ep(ModelForm): class Meta: model = Add_Ep fields = "__all__" Error: Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['UTwwWtdY9Vy0L6BzYL5jK9SPRqBFsJaBpGwxIOtqdD5kDQC7CRiyPSDxC0rbUo4g'], 'Ep_Title': ['title'], 'CreatorsNote': ['this is creaters note555'], 'series': ['2']}>.