Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How separate the data inside the model based on the user
I want to make an attendance system that prevents each user to see the attendance that some users have taken. But in my case, the attendance that the other users take can be shown by every user. How can I prevent this part? These are my codes: Models.py class ClassAttendance(models.Model):Faculty_Name = models.CharField(max_length=200, null=True, blank=True)Student_ID = models.CharField(max_length=200, null=True, blank=True)firstname = models.CharField(max_length=200, null=True, blank=True)lastname = models.CharField(max_length=200, null=True, blank=True)date = models.DateField(auto_now_add = True, null = True)time = models.TimeField(auto_now_add=True, null = True)college = models.CharField(max_length=200, null=True, blank=True)course = models.CharField(max_length=200, null=True, blank=True)year = models.CharField(max_length=200, null = True)section = models.CharField(max_length=200, null = True)subject = models.CharField(max_length=200, null = True)status = models.CharField(max_length=200, null = True, default='Absent')def __str__(self): return str(self.Student_ID + "_" + str(self.lastname) + "_" + str(self.date)+ "_" + str(self.subject)) class Faculty(models.Model): user = models.OneToOneField(User, null = True, blank = True, on_delete= models.CASCADE) firstname = models.CharField(max_length=200, null=True, blank=True) lastname = models.CharField(max_length=200, null=True, blank=True) college = models.CharField(max_length=200, null=True, choices=COLLEGE) course = models.CharField(max_length=200, null=True, choices=COURSE) year = models.CharField(max_length=200, null=True, choices=YEAR) section = models.CharField(max_length=200, null=True, choices=SECTION) subject = models.CharField(max_length=200, null=True, choices=SUBJECT) def str(self):return str(self.firstname + " " + self.lastname) class Meta:verbose_name_plural = "Faculties" I expected that after the users take attendance, they are the ones that can see that information -
Django UpdateView with reverse foreign key
I am using UpdateView, which is very cool abstraction and makes it very easy to update existing Models. I however want to include into this reverse foreign keys (kinda similar to inline admins). There is also inlineformset_factory, which helps creating this kind of reverse foreign key formsets. Of course I can handle all this manually (modelform and then each formset). But I'd like to put all those forms together and abstract this functionality into a view so that I then only specify the model, fields (same as in UpdateView), but also those reverse foreign keys. Is there a view for this or do I have to create my own? Any kind of experience with this would be appreciated. -
How to parse the "src" of image tag in Django textfield?
So I have code in my HTML template like this <div class="blog-content"> {{post.text|safe|linebreaks}} <p><img src="{{ image_dict.1.url }}" alt=""></p> </div> This above renders the image fine in HTML. My view is like this def post_detail(request, slug): post = BlogPost.objects.get(slug=slug) images = post.images.all() image_dict = {} for image in images: image_dict[image.image_order] = image.image print(image.image) return render(request, 'blog/post_detail.html', { 'post': post, 'images': images, 'image_dict': image_dict, }) Basically I'm setting it up so that I can render the images via {{image_dict.image_order.url}} But I wanna render the images as per following to associate them with each paragraph of text like so Text in Django TextField However, while the code within the template evaluates to the image url, for example say for an image with order '1' <p><img src="{{ image_dict.1.url }}" alt=""></p> becomes <p><img src="/media/images/codewithlewis.png" alt=""></p> The exact same code I typed in django's textfield (as attached in above image) remains like <p><img src="{{ image_dict.1.url }}" alt=""></p> within HTML and nothing gets rendered of course. A screen shot of this: I'm fairly new to Django but I feel like I have tried everything. How might I go about fixing this? Thank you. -
I'm getting the following error and I don't know what to do about it [closed]
since i'm new to django i don't know what to do next it'll really be helpful if somebody helped me i tried to inherit a template named 'basic.html' but at {% block css %}{% endblock %} i'm getting this error "{ expected css(css-lcurlyexpected)" -
Django testing HttpResponse
I've seen tutorials and guides about testing views which are rendering some templates, but I don't know how to use Django's testing module in case if I have views which are returning Jsons in HttpResponse? Any help will be appreciated. Thank You -
Refresh html DIv in Django
i am trying to refresh an {%extends%} page since my base.html is getting message information from whatever is happening in the python backend, it only shows the message after i refresh my page and i want to refresh it every x seconds so the alerts will show without needing to refresh my entire page. <div id="Mydiv"> {% extends 'crodlUSDT/base.html'%} </div> <script> $(document).ready(function() { function refresh() { var div = $('#Mydiv'), divHtml = div.html(); div.html(divHtml); } setInterval(function() { refresh() }, 3000); //300000 is 5minutes in ms }) </script> this is what i've found online but tested a lot of different things but none are working, is this possible ? thanks -
AttributeError: Class1 object has no attribute 'class2_set' with ManyToMany Field Django
Model : class Groupe(models.Model): name = models.CharField(max_length=255) autoAddingMail = models.CharField(max_length=255,null=True,blank=True) association = models.ForeignKey( User, limit_choices_to={'role': 'ASSOCIATION'}, null=False, on_delete=models.CASCADE, related_name='association' ) students = models.ManyToManyField( User, limit_choices_to={'role': 'STUDENT'}, related_name='students' ) events = models.ManyToManyField( Event ) class Meta: unique_together = ("name","association") REQUIRED_FIELDS = ['name','association'] def __str__(self): """ Return string representation of our user """ return self.name Unit test : groupe = event.groupe_set.get(name="name",association=association) <= works fine groupe = student.groupe_set.get(name="name",association=association) <= doesn't work The error : AttributeError: 'User' object has no attribute 'groupe_set' I don't get why student doesn't have the attribute groupe_set but event have it I have read the documentation about ManyToMany Fields but I didn't find answers. -
How to save http request to django?
I have a device that do some calculations and then i want to send it with help of request to my site: import requests params = {'data1': '47237582'} r =requests.get("http://127.0.0.1:8000/", data = params) print(r) I have a django site. How can i save the value of my request for later display? def read(request): if request.method == 'GET': msg = request.GET['data1'] And how can i save it to database? -
Django Celery Beat - Runaway Process on Ubuntu
I have celerybeat running as a service on ubuntu. Generally speaking, everything works great. I have the same setup on numerous servers. Last night, I noticed the frequency at which a certain task was firing was doubled; seemingly out of the blue. In order to troubleshoot I did a few things: cleared the redis server + celery message queues restarted the celerybeat service restarted the redis-server service When those did not change the behavior, I tried: rebooting the server stopping the celerybeat service stopping the redis-server service Even after a reboot and having all the services stopped, the task is still being triggered! I have never encountered this kind of behavior before. How can the task continue to be triggered even without a messaging service? Any help or troubleshooting ideas here would be really appreciated. Thanks in advance. -
Why Django is the best Web Framework? [closed]
Django is the Best web framework for python based aplication. I want to know why it is best for design and developing web applications? -
Creating a custom User model by extending AbstractBaseUser
I am trying to create a custom User(CustomUser) by extending AbstractBaseUser. I am trying to remove username field and use email for authentication.I have not done the first migration yet. Here is models.py from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.core.mail import send_mail from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .managers import UserManager class CustomUser(AbstractBaseUser, PermissionsMixin): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. email and password are required. Other fields are optional. """ first_name = models.CharField(_("first name"), max_length=150, blank=True) last_name = models.CharField(_("last name"), max_length=150, blank=True) email = models.EmailField(_("email address"), unique=True) is_staff = models.BooleanField( _("staff status"), default=False, help_text=_("Designates whether the user can log into this admin site."), ) is_active = models.BooleanField( _("active"), default=True, help_text=_( "Designates whether this user should be treated as active. " "Unselect this instead of deleting accounts." ), ) date_joined = models.DateTimeField(_("date joined"), default=timezone.now) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["email"] class Meta: verbose_name = _("user") verbose_name_plural = _("users") abstract = True def clean(self): super().clean() self.email = self.__class__.objects.normalize_email(self.email) def get_full_name(self): """ Return the first_name plus the last_name, with a space in between. """ full_name = "%s %s" % (self.first_name, … -
Unable to Dynamically Render Django images on templates
So I've been trying to get the images uploaded through admin interface to render on a template but for some odd reason it just wont render the images. It renders any other type of data but NOT IMAGES. From Settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') From appvew.py: class ProjectsListView(ListView): model = Projects context_object_name = 'projects' template_name = 'myportfolio/portfolio.html' appurls.py: urlpatterns =[ path('home/', views.ProjectsListView.as_view()), # path('projects/', ) ] html template: {% load static %} </head> <body> <h1><p>This is my portfolio</p></h1> {% for project in projects %} <img src="{{project.screenshot}}" alt="No image found"> {% endfor %} </body> </html> output :( : I verified an old project of mine with pretty much the same set up and it works. This one on the other hand, only renders the name of the objects on other properties but not the images -
Django model F expression divide by zero error when calculating dynamic running total and average
I am using Django 3.2 I am dynamically calculating field values for an item that can be rated. Here is a snippet of my code: self.ratings_count = F('ratings_count') + 1 self.ratings_total = F('ratings_total') + rating_value self.ratings_average = F('ratings_total') / F('ratings_count') self.last_rated = timezone.now() self.save() # Divide by zero error here (no records exist in Db) I could trivially get around this by not using F fields (as a kludge). My question is - how do I implement the desired behaviour, whilst using F expressions? -
Versioning issues about Django project creation
My Django version is 2.2.12. When I use the command django-admin startproject mysite to create a project, this project's setting.py shows me that Generated by 'django-admin startproject' using Django 1.9.13. I typed the commandsudo pip freeze|grep -i 'django' into Pycharm's terminal to check the version and it also showed 2.2. This thing puzzled me. -
FastAPI, How to save image in a directory and get the image url for further access
I am trying to receive an image file via a POST method and save this image in a directory called profile_pictures And I was able to save the uploaded image. But now my problem is Now I want to show the image in the client side via an URL. So my concern is how should I generate the URL to access the image? I am new in back-end web technology so there is lack of knowledge so any broad answer or explanation will be helpful for me, thank you This is POST method @router.put("/upload/profile-picture") async def upload_profile_picture( profile_picture: UploadFile = File(...), db: Session = Depends(get_db), token_data: schemas.TokenData = Depends(oauth2.get_current_user), ): new_query = db.query(models.User).filter(token_data.id == models.User.id) x_user_data = new_query.first() # check whther user exist or not if not x_user_data: return HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="User not found", ) # save the file and get the saved path file_name = file_utils.save_profile_picture(profile_picture) return {"profile_picture": file_name} And this is the helper method from fileinput import filename from datetime import datetime import os from fastapi import File, UploadFile def save_file_and_return_path(profile_picture: UploadFile) -> str: try: os.mkdir("profile_pictures") print(f"current directory = {os.getcwd()}") except Exception as e: print(f"Exception 1 : {e}") file_name = ( f"{os.getcwd()}/profile_pictures/{profile_picture.filename.replace(' ', '_')}" ) with open(file_name, "wb+") … -
Create @login_required like function for used form(Modelform). So that User can't access confidential url without login-by typing just url?
I know that I can use @login_required but it is only used when we store user in User But in my case I stored model in form So it is not working for me. Also my created user is not getting authenticated when I use user.is_authenticated So I need custom login_required decorator which can be use to stop anyone from accessing direct url (confidential URl which are only accessed when you Login). forms.py class usrForm(forms.ModelForm): password = forms.CharField(initial=123) class Meta: model = Person fields = ('first_name','last_name','username','email','password','position') def __init__(self, *args, **kwargs): super(usrForm,self).__init__(*args,**kwargs) self.fields['position'].empty_label = "Select" class usrChange(forms.ModelForm): class Meta: model = Person fields = ('username','password') widgets= { 'password' : forms.PasswordInput(), } class loginForm(forms.ModelForm): class Meta: model = Person fields = ('username','password') widgets= { 'password' : forms.PasswordInput(), } models.py class Position(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title class Person(models.Model): first_name = models.CharField(max_length=50,default='') last_name = models.CharField(max_length=50,default='') username = models.CharField(max_length=50,default='') password = models.CharField(max_length=50,default='') email = models.EmailField(max_length=50) position = models.ForeignKey(Position, on_delete=models.CASCADE) def __str__(self): return self.username views.py def user_list(request): context = {'user_list' : Person.objects.all()} return render(request, "usr_list.html", context) def user_chnged_list(request): form = usrForm(request.POST) if form.is_valid(): form.save() context = {'user_list' : Person.objects.all()} return render(request, "usr_list.html", context) def user_form(request, id=0): if request.method == "GET": if id ==0: … -
Using User object and AllAuth together in a Django application
My model has a User class subclassed from AbstractUser (so i am reusing all default fields of the abstractuser object). I have been using this for a while and then I thought of using all-auth django for extra functionality. We set it up and everything works as it should. However I have some confusions with the new tables these models are creating. I still have the original user table which was storing email, password and some other default information (form the Abstract user) I now have a few more account_ tables (from allauth). One of these tables, account_emailaddress also stores the email as information. Im a bit confused on why I need to store the email two times ? Once in the user table and another time in the account_emailaddress table. We can also this using a link from User to email address table (or from User model to allauth model somehow). -
Django - json.decoder.JSONDecodeError: Expecting value: line 1 column 1
I am trying to parse post request body in Django if request.method == 'POST': data = json.loads(request.body.decode()) obj = Person( name = data.get('name'), last_name = data.get('last_name'), birth_date = data.get('birth_date'), age = data.get('age') ) obj.save() I get the next error : json.decoder.JSONDecodeError: Expecting value: line 1 column 1 I tried to use data = json.loads(request.body.decode('uft-8')) but the error is same. any ideas how I can fix the problem? -
'QuerySet' object has no attribute 'pk' in "bulk_update"
I have model of Professor and need to "bulk_update". I have to do this in 2 requests from my DB. But i have exception ('QuerySet' object has no attribute 'pk'). If i use get i have another exception(get() returned more than one Professor). My model. class Professor(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) age = models.IntegerField(default=18) class Meta: indexes = [models.Index(fields=['first_name'])] My code def update_professor_first_names(first_name_updates: List[NameUpdate]): prof_id = [id for id, name in first_name_updates] prof = Professor.objects.filter(id__in=prof_id) tmp = [] for prof_id, new_first_name in first_name_updates: prof.first_name = new_first_name tmp.append(prof) Professor.objects.bulk_update(tmp, ['first_name']) Can you give me some advices about it? -
Problems with building an e-commerce platform
i am trying to make a website that allow any one create his own e-commerce website & app without any coding but ... Now almost everything is ready for me, but there are some problems that I want suggestions to solve First problem: Now the platform is creating a website for the client using django This site is made of react js How can I connect my project to sharedhost so that it will automatically send the site files to it and puts it inside a subdomain in another way Allowing the user to deploy to his site without owning hosting and the platform automatically does all this The second problem: There is another feature that I have added, which is that the platform allows the user to build his own application But it only stops when you build apk for this app It works fine localy but I don't know how it will be on the server i build the apk by let python use the command line to build an apk *Note: I am using digitalocean I hope I made it clear -
sorting messages with tag in django template
I'm receiving a list of messages, each message has a tag. It may be "info", "warning", "danger" and "spreadsheet". I need to display the first three first and then spreadsheet's but in collapsible if there are more than 3 of them. So for all messages BUT spreadsheet the template is: <div class="row banner"> <ul class="banner-message"> {% for message in messages %} <li{% if message.tags %} class="banner-message--{{ message.tags }}" {% else %} class="banner-message--info" {% endif %}> <div class="message-content"> <p>{{ message|safe }}</p> <span class="close">&times;</span></div> </li> {% endfor %} </ul> </div> For tags with "spreadsheet" tag the template is: <div class="row banner"> <ul class="banner-message"> {% for message in messages %} <li class="{% if forloop.counter >= 3 %}collapsible_content{% endif %} banner-message--info"> <div class='message-content'> <p>{{ message|safe }}</p> <span class="close">&times;</span> </div> </li> {% endfor %} {% if messages|length > 3 %} <button id="show_more" class="btn btn-secondary collapsible_button">Show all</button> {% endif %} </ul> </div> Where button is shown for spreadsheet messages if there are more then 3 of them and shows all of them on click. Problem is that I receive these messages in one array and I have no guarantee that they won't be all mixed up in different order. I need to sort them somehow with … -
Djangos multiuser table how to log in
I now have two user models, one for background users and one for regular users. Background users are associated with regular users. How do two users log in to Django without affecting each other models.py models.py class BemanUser(AbstractUser): mobile = models.CharField('手机号', max_length=255, unique=True) class consumer(models.Model) account = models.CharField(max_length=255) name = models.CharField(max_length=255) password = models.CharField(max_length=255) mobile = models.CharField(max_length=255) email = models.CharField(max_length=255) How do I get both tables to log in? Thanks -
Django session cookie is changed to "" and expiration date of 1970
I have a problem with the cookies of a session logged into a web with Django. The session is started correctly and when I send request with the session cookie, the server response overwrites the session cookie with "" and sets the expiration date to January 1, 1970. This is something that happens completely randomly. I have checked the database and the session is stored. If I change the cookie that it gives me for the one that the login should have, it is done correctly. Does anyone know what could be happening? Thank you very much in advance. -
Axios to django-backend post image fail
I'm using react frontend to communicate with Django backend through axios. For some reason, I can't post form that include image. I tested my django backend through Postman and it works well. The backend shows code 200 on the terminal as success without saving data and the frontend doesn't through error the form can post successfully if I excluded the image. Please check my code below ; form.js file import React, { useState } from 'react'; import { Helmet } from 'react-helmet'; import axios from 'axios'; import { connect } from 'react-redux'; import { setAlert } from '../actions/alert'; import './ApplicationForm.css'; import { useNavigate } from 'react-router-dom'; import ExpandLessIcon from '@mui/icons-material/ExpandLess'; import ExpandMoreIcon from '@mui/icons-material/ExpandMore'; import { IconButton } from '@mui/material'; function ApplicationForm({ setAlert }) { const [show, setShow] = useState (false); const navigate=useNavigate(); const [formData, setFormData] = useState({ pasport_number: '', first_name: '', last_name: '', passport_photo: '' }); const { pasport_number, first_name, last_name, passport_photo } = formData; const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value }); console.log (formData) const onSubmit = e => { e.preventDefault(); const config = { headers: { 'Content-Type': 'application/json' } }; axios.post(`${process.env.REACT_APP_API_URL}/api/application-form/`, { pasport_number, first_name, last_name, passport_photo }, config) .then(_res => { navigate('/'); setAlert('Application Submitted Successfully', … -
Django can't Login
I can't Login to the system. Please help me. I have default User model in admin panel. Registration works fine but can't login to the homepage. Please debug it Views.py file: def loginpage(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, "Wrong username or password") return render(request,'loginpage.html') else: return render(request,'loginpage.html') Register views here: def register(request): if request.method == "POST": fname = request.POST['fname'] lname = request.POST['lname'] username = request.POST['username'] id = request.POST['id'] email = request.POST['email'] password = request.POST['password'] if User.objects.filter(username = username).exists(): messages.error(request, "Username already exists") return redirect('/') if User.objects.filter(email = email).exists(): messages.error(request, "Email already exists") return redirect('/') if not request.POST.get('email').endswith('@northsouth.edu'): messages.error(request, "Enter valid NSU Email") return redirect('/') else: user = User.objects.create(first_name=fname, last_name=lname, username = username, id=id, email=email, password=password) user.save() if user is not None: return redirect('register') reg = request.POST.get('username') messages.info(request, 'Account created for - Mr. ' + reg) return redirect('/') else: return render (request, 'registration.html')