Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is there any other way i can use django @login_required parameter?
this little stuffs has been frustrating me since yesterday, i was trying to add @login_required parameter to my create function in django, the code works really well without adding the @login_required parameter, but bring page not found when i add @login_required. this is my code. urls.py app_name = 'accounts' urlpatterns = [ path('signup', views.signup_view, name='signupp') , path('login', views.login_view, name='loginn'), path('logout', views.logout_view, name='logoutt') ] views from django.contrib.auth.decorators import login_required @login_required(login_url='accounts/loginn/') def jayapp_create(request): return render(request, 'jayapp/jayapp_create.html' ) when i go to http://127.0.0.1:8000/jayapp/create/ it shows Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/jayapp/accounts/loginn/?next=/jayapp/create Using the URLconf defined in JayDjango.urls, Django tried these URL patterns, in this order: admin/ accounts/ jayapp/ [name='list-in'] jayapp/ log jayapp/ create [name='create'] jayapp/ / [name='detail'] backen/ ^media/(?P.*)$ The current path, jayapp/accounts/loginn/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
DRF : Getting nestted serializer fields for custom checks
Here is my master and detail serializers. class MasterSerializer(serializers.ModelSerializer): class Meta: model = Master fields = ['id','date_signed','info1','info2'] class DetailSerializer(serializers.ModelSerializer): master = MasterSerializer(read_only=True) class Meta: model = Detail fields = ['id','master','date_start','date_end','info3','info4'...] def validate(self, attrs): # 1. check if date sign is always grater than date start # 2. check date start is greater than date end What i am trying to do is to check if the date_signed in master serializer is always a date before the date_start one. For that i need the date_signed in the detail serializer. So how can i get it. May be is a simpler question, but i am finding it difficult as i just started learning drf. I searched a lot, but couldnt get the solution i needed. Hope to get some help to point me in the right direction. Thanks in advance -
How to create a django reset framework api serializer for models that is `ManyToMany` field with `through` attribute?
How can I create a serializer for Model that has ManyToMany field with through attribute using django reset framework. I need to embed this serializer with the parent serializer to be represented at the same API route. -
My search form is not reflecting the details of my page DJANGO
I'm currently trying to create a search page that shows the content of a page but it is not working. Kindly guide me on what I am doing wrong. I don't have a model to reference this to as the content of the pages were created in a folder called utils.py with files that contain what I am trying to display. I've tried two different search view functions and brainstormed my head out so I would really appreciate help on this URLS.PY app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry_page, name="entrypage"), path("search", views.search, name="search"), ] LAYOUT.HTML <form action="{% url 'encyclopedia:search' %}" method="get"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> ENTRYPAGE.HTML {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} {{ content|safe }} {% endblock %} INDEX.HTML <h1>All Pages</h1> <ul> {% for entry in entries %} <li><a href="{% url 'encyclopedia:entrypage' entry.title %}">{{ entry|safe }}</a></li> {% endfor %} </ul> VIEWS.PY def entry_page(request, title): title = util.get_entry(title) if title: content = markdown2.markdown(title) context = { "title": title, "content": content, } return render(request, "encyclopedia/entrypage.html", context) else: return render(request, "encyclopedia/errorpage.html") # def search(request): # if request.method == 'GET': # query = request.GET.get('q') # … -
The field was declared with a lazy reference to 'auth.user', but app 'auth' isn't installed
its my installed apps : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'leadgenerator', 'leadgenerator.apps.ui', 'leadgenerator.apps.accounts', 'leadgenerator.apps.instagram', 'leadgenerator.apps.BorseBots', 'leadgenerator.apps.TelegramBorse', 'leadgenerator.apps.Utils', 'leadgenerator.apps.Blog', 'leadgenerator.apps.Crypto', 'channels', 'multiselectfield', 'django_redis', 'django_filters', 'extra_views', 'django_select2', 'compressor', 'django_celery_beat', 'crispy_forms', 'django_tables2', 'ckeditor', 'ckeditor_uploader', # 'leadgenerator.ckeditor5', 'leadgenerator.rolepermissions', 'rolepermissions', # login and login_as 'loginas', 'allauth', 'allauth.account', 'allauth.socialaccount', 'phonenumber_field', # blog 'modelcluster', 'taggit', # end blog 'imagekit', 'pwa' ] and i used user in models : from django.contrib.auth.models import User as djangoUser class BlogPost(models.Model): author = models.ForeignKey(djangoUser, on_delete=models.CASCADE, related_name='blog_posts', verbose_name=_('Author')) migration now is 0013 when i use backward migrate like this : migrate Blog 0011 error happend : ValueError: The field Blog.BlogPost.author was declared with a lazy reference to 'auth.user', but app 'auth' isn't installed. also i do not have AUTH_USER_MODEL in settings.py also i can not remove data base because have so many data on it. what is problem?? using django2.2 python3.7 postgresql -
How to use render_to_string() to validate template
I'm trying to validate the template being entered by the user class TemplatesForm(forms.ModelForm): class Meta: model = Templates def validate_temp(self): name = self.cleaned_data.get('name') html = self.cleaned_data.get('html') html_form = render_to_string(html) try: HttpResponse(html_form) except TemplateSyntaxError as e: logger.error(f"email template of name={name}suffers syntax error ") raise e class TemplateAdmin(TabbedDjangoJqueryTranslationAdmin): form = EmailTemplateForm list_display = ('name', 'code', 'subject_en', 'subject_ar') actions = None search_fields = ['name', 'code', 'text_en', 'text_ar', 'html_en', 'html_ar', 'subject_en', 'subject_ar'] admin.site.register(EmailTemplate, EmailTemplateAdmin) is this trial correct or something is better -
I need help in django
I want to print First semester's Subjects in First Semester & Second semester's Subjects in Second Semester and so on. See this pic cick in image here Maybe there is some logic in views.py that Im not having on my mind rn.Can someone help me in this logic and how to render it in semester.html page My code is here. models.py from django.db import models from django.db.models.base import ModelState # Create your models here. class Course(models.Model): faculty = models.CharField(max_length=100) class Semester(models.Model): sem = models.CharField(max_length=100) faculty = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return F"Semester {self.sem} at Faculty {self.faculty}" class Subject(models.Model): faculty = models.ForeignKey(Course, on_delete=models.CASCADE) sem = models.ForeignKey(Semester, on_delete=models.CASCADE) subject_name = models.CharField(max_length=100) def __str__(self): return str(self.id) views.py from django.shortcuts import render from django.views import View from django.contrib import messages from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField from django import forms from django.utils.translation import gettext, gettext_lazy as _ from .forms import CustomerRegistrationForm from .models import Course, Semester, Subject # Create your views here. def home(request): return render(request, 'app/home.html') def faculty(request): course = Course.objects.all() return render(request, 'app/faculty.html', {'course':course}) class SemesterView(View): def get(self, request,id): obj = Course.objects.get(id=id) print(obj) semobj = Semester.objects.filter(faculty=obj) print(semobj) subobj = Subject.objects.filter(faculty=obj) print(subobj) return render(request, 'app/semester.html', {'obj':obj, 'semobj':semobj, 'subobj':subobj}) semester.html {% extends 'app/base.html' %} … -
WebSocket connection failed no error message
WebsocketConnectionFailed When I access the web directly, I can establish a websocket connection.When I set up websocket in acapp, it will fail on my pc. When I use other people's computers, everything works fine. When the connection fails, the console cannot even give an error message. -
How to delete an entry from queryset in django html template without refresing page?
On my HTML template, I am printing a list of my QuerySet that I passed from views.py in Django. I want users to delete an entry from the list without refreshing the page. How do I do that? -
How do I host a function in a web server, which returns a value back to the client?
I made an ML model that classifies images, and I want to implement it to my application. But the problem is that the file is too heavy and requires an unreasonable amount of disk space for an android application. So I was wondering if I could host the Model function in a server, which would return the prediction back to the client, when I can call from my python script. I couldn't find any specific tutorials on hosting functions, with would return output back the the client. So How do I go about doing this? Here is the function I wish to host- from keras.models import load_model from PIL import Image, ImageOps import numpy as np labels= ["Banana", "Fan", "Clock","Coin","Leaf","Paper_airplane","Pen","Phone","Spoon","Tomato"] model = load_model('keras_model.h5') data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) #Here I wish to pass the image, from my python program, and recieve the prediction def RunPrediction(img): image = img size = (224, 224) image = ImageOps.fit(image, size, Image.ANTIALIAS) image_array = np.asarray(image) normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1 data[0] = normalized_image_array #And I want to recieve this output in my code prediction = model.predict(data) return prediction -
Parsing data from django backend into react component
Hi I am trying to parse JSON data from Django view into the frontend. Basically in my view, I defined the data which I want to parse and it looks like this : user_information = {'username':request.user.username, 'email':request.user.email, 'first_name':request.user.username} Then in the html, I can parse it into the javascript using json_script which looks like this: {{ user_information|json_script:'user_information' }} Then I want to call the user_information variable in React component using this script: class Form extends React.Component { constructor(props){ super(props); this.state = { user_information: null }; } componentDidMount() { this.setState({ user_information: JSON.parse(document.getElementById('user_information').textContent) }); console.log(this.state.user_information); } render () { return( <h1>{this.state.user_information}</h1> ); } } To test tis out I tried to print it in the console to see whether it is successfully parsed to the component state. But it turns out that in the console I got null. Can you guys help me what are my mistakes and how do I solve it ? -
Django Celery ORM None field
In celery task i getted my object (Order). Object contains ManyToManyField and then i call it i recived None. However when i call the same code in django shell i recived back correct list of objects. What wrong with celery task and what i can do with that? @app.task() def send_admin_email_task(): yesterday = datetime.now() - timedelta(days=1) orders = Order.objects.filter(timestamp__gte=yesterday, status=Order.StatusChoice.NEW) print(orders.first().orderItems) class OrderItem(models.Model): product = models.ForeignKey('products.Product', null=True, on_delete=models.SET_NULL) count = models.PositiveIntegerField() price = models.FloatField(default=-1) сlass Order(models.Model): orderItems = models.ManyToManyField(OrderItem) price = models.DecimalField(decimal_places=2, max_digits=10, default=0) full_name = models.CharField(max_length=200, blank=True) email = models.EmailField(blank=True) phone = models.CharField(max_length=12, blank=True) -
I need a help in django
whenever I try to add field in admin panel, I always get confused [][1] model.py from django.db import models from django.db.models.base import ModelState # Create your models here. class Course(models.Model): faculty = models.CharField(max_length=100) class Semester(models.Model): sem = models.CharField(max_length=100) faculty = models.ForeignKey(Course, on_delete=models.CASCADE) class Subject(models.Model): faculty = models.ForeignKey(Course, on_delete=models.CASCADE) sem = models.ForeignKey(Semester, on_delete=models.CASCADE) subject_name = models.CharField(max_length=100) def __str__(self): return str(self.id) which field is what? so I want every field is in clear name in admin panel [1]: https://i.stack.imgur.com/GKXNO.png -
ImportError: cannot import name 'ArticleSerializer' from 'basics.serializers'
while working with serializers in Django Shell I had to import from basics.serializers import ArticleSerializer the error I'm getting is : P.S. I'm a beginner at the rest framework of Django ImportError Traceback (most recent call last) in ----> 1 from basics.serializers import ArticleSerializer ImportError: cannot import name 'ArticleSerializer' from 'basics.serializers' (C:\Users\Sony\PycharmProjects\pythonProject\Frameworks of python\django\django_rest_framework\basics\serializers.py) the code for the serializer.py is: from rest_framework import serializer from basics.models import Article class ArticleSerializer(serializers.Serializer): title = serializers.CharField(max_length=100) author = serializers.CharField(max_length=100) email = serializers.EmailField(max_length=300) date = serializers.DateField() def create(self, validated_data): return Article.objects.create(validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.author = validated_data.get('author', instance.author) instance.email = validated_data.get('email', instance.email) instance.date = validated_data.get('date', instance.date) instance.save() return instance can someone please guide me what should be done -
Django is not loading the URL I defined
I am working on a project that generates dynamic urls, For ex. if I type 127.0.0.1:8000/newpage it generates a new model with slug newpage Earlier the project was working fine but suddenly it started to show some bugs. I am calling a URL using ajax like this (5th line): $(document).on('click', '#save', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "text:update" %}', data: { newText: $('#text-content').val(), slug: "{{ obj.slug }}", csrfmiddlewaretoken: "{{csrf_token}}", action: 'post' }, success: function (json) { if (json['status'] === 'OK') { document.getElementById('msg-box').innerText = 'TEXT SAVED'; window.removeEventListener("beforeunload", beforeUnloadListener, { capture: true }); } }, error: function (xhr, errmsg, err) { } }); }); It should load the view which I defined in the update url patterns but because of some reason it is still loading my slug view and generating a new url with slug update, I mean it shouldn't do that if I am telling it to load a specific view in URL pattern then why it is still loading slug view below is my urls.py: #Only patterns path('', home, name='home'), path('<slug:slug>/', textview, name='textview'), path('update/', update, name='update'), -
Headless wagtail - embed tags in HTML
I've setup a headless wagtail as described on https://learnwagtail.com/tutorials/how-to-enable-the-v2-api-to-create-a-headless-cms/ I embedded a Youtube video. In the API endpoint the HTML is like this: { "id": 4, "meta": { "type": "news.NewsPage", "detail_url": "http://localhost/api/v2/pages/4/", "html_url": "http://localhost/test/", "slug": "test", "first_published_at": "2021-12-05T07:32:32.896276" }, "title": "Test", "date": "2021-12-05", "intro": "", "body": "<p data-block-key=\"yj93z\"></p><embed embedtype=\"media\" url=\"https://www.youtube.com/watch?v=u9n7Cw-4_HQ\"/><p data-block-key=\"71b7p\"></p>", "main_image": null } How can get a normal Youtube embed within this HTML? Any ideas? -
How do I preserve content in database while making on going changes to my code?
How do I avoid overwriting my local database when doing a pull request from remote? further, if I use '.gitignore', will I be able to make structural changes to my DB in the future? (for example, if I want to make changes to a model) I am currently using Django with the sqlite3 DB. -
How do I host a function on a server, which I can call from my python script?
I recently made a program which runs a ML model on an image, and predicts what it is. The problem is that, including the model and the dependencies like tensorflow, caused it to be 500mb. So I was wondering if I could host a function in a server, where I would pass in my image, and it would return the output back. Here's the function I wish to host- from keras.models import load_model from PIL import Image, ImageOps import numpy as np labels= ["Banana", "Fan", "Clock","Coin","Leaf","Paper_airplane","Pen","Phone","Spoon","Tomato"] model = load_model('keras_model.h5') data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) #Here I wish to pass the image, from my python program, and recieve the prediction def RunPrediction(img): image = img size = (224, 224) image = ImageOps.fit(image, size, Image.ANTIALIAS) image_array = np.asarray(image) normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1 data[0] = normalized_image_array #And I want to recieve this output in my code prediction = model.predict(data) return prediction How do I achieve this? Thanks! -
How can I use django url <slug> as a subdomain (i.e <slug>.domain.com)?
I am quite familiar with django but there is one thing I need to do and I have no idea how. I have a generic details-view page, whose url is /<slug>/ i.e domain.com/<slug> but now I want to change that url to <slug>.domain.com instead. I want to use the slug as a subdomain but I don't have even the slightest idea how to do so. Is there anyway that I can achieve this? -
Disable button on django-comments-dab
this is how it works for me in django-comments-dab and the button is disabled, please help disable button -
Is there any way to get rid of Pylance(reportMissingModuleSource)?
I was following a Django tutorial. But I get this error on my apps.py file 'Import "django.apps" could not be resolved from source Pylance(reportMissingModuleSource)'. I am running the project inside a virtual environment and made sure I'm inside the virtual environment while working on the project. How can I get rid of this error? I am new to Django. -
How can I use double curly brases in double curly brases in Django?
<p><i class="fas fa-print mr-3"></i>{{ contact.phone2|default_if_none:'{{ contact.phone }}'}}</p> I want a value on double curly braces if_none like above. But it makes an error. How can I use it, when Django gives templage tag? -
how to create record in database for each month by participants in django
I am working on an app where a user can create a committee and the participants will pay the amount each month like this.I am quite new with coding and databases so i am little confused. class committee(models.Mode): name= ... per_amount=... and some other columns will go here... class participants(models.Model): parti_name= .. parti_committee_name = models.foreignkey(Committee) some other columns here now what I want is I want the records of each participant for each month, They can only pay once a month and then they are allow to pay next month. now I am confused where to put the month coloumn, is there gonna be a new coloumn for this or not? -
How Can I upload All types of files (videos, audios, pdfs, zip) in cloudinary in django model ? and how can i delete them?
models.py from django.db import models from cloudinary.models import CloudinaryField class File(models.Model): caption = models.TextField(blank=True) file = CloudinaryField() # trying to delete the File model and cloudinary file (error) def delete(self, *args, **kwargs): self.file.delete(*args, **kwargs) super().delete(*args, **kwargs) settings.py import cloudinary import cloudinary.uploader import cloudinary.api ... INSTALLED_APPS = [ '....', 'myapp', 'cloudinary', ] ... cloudinary.config( cloud_name = "...", api_key = "...", api_secret = "...", secure = True ) i can upload images only, when i try to upload any (video, pdf, audio, zip) it says INVALID IMAGE FILE. and sometimes file size error occurs when image size exceeds 10 mb size limit. -
Django Conditional Signals (or better solution)
I have two user types, UserTypeA and UserTypeB. I have created a CustomUser Model, and added a flag is_userA, is_userB in this model. When registering, I am successfully setting the flag for each user type correctly. I have created a model for UserTypeAProfile. When I register a new user, I can successfully create a Profile instance. The issue is that this happens for both UserTypes. I want it to only happen for the UserType that is registering. Below is the CustomUser Model. class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) is_userA = models.BooleanField(default=False) is_userB = models.BooleanField(default=False) def __str__(self): return self.email Below is the UserTypeAProfile Model class UserTypeAProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) bio = models.CharField(max_length=50, blank=True) @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: UserTypeAProfile.objects.create(user=instance) def __str__(self): return str(self.user) I have tried: @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if CustomUser.is_userA: UserTypeA.objects.create(user=instance) But it doesn't seem to work, still when I test by creating both userTypes, I get a profile instance for both types. Is there a good way to do this? Basically, when userA signs up, I want to create a profile for them with specific UserA attributes, and when userB signs up, I want to create a profile for …