Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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') -
Django: Access context data in POST and GET
I am very new to Django and I cannot work out how to access context data within a POST request so I don't have to repeat myself. I believe that POST runs before get_context_data, but again unsure of what exactly to do here. The page displays some data using a default of 30 days. Then on the page there is a form to override that value, which is passed back to the POST method to then re-render the page. Example of page. views.py model = Producer template_name = 'producer_detail3.html' def get_queryset(self, **kwargs): #-date_check means to descending order based on that column return Producer.objects.filter(owner_name__exact=self.kwargs['pk'],metasnapshot_date=date(1980, 1, 1)) # Update context with more information def get_context_data(self, **kwargs): # Call the base implementation first to get the context context = super().get_context_data(**kwargs) # Cannot update context here as you are accessing existing producer object context data. # Create any data and add it to the context how_many_days = self.kwargs['days'] # get DAYS from URL. KWARGS are passed in from the get request context['day_filter'] = reverse('results:producer_detail', args=[self.kwargs['pk'], '300']) context['results'] = Results.objects.all().filter(owner_name__exact=self.kwargs['pk']).order_by('-date_check') context['chains_json_count'] = Results.objects.filter(owner_name__exact=self.kwargs['pk'],chains_json=True,date_check__gte=datetime.now()-timedelta(days=how_many_days)).count() return context def post(self, request, **kwargs): day_filter = int(request.POST.get('day_filter')) producer = Producer.objects.get(owner_name__exact=kwargs['pk'],metasnapshot_date=date(1980, 1, 1)) # Using reverse we create a URL to … -
How to add a rich text field in django?
how do i add a rich text field in django that would have to the option to add a Code Sample just like stack overflow text editor -
Getting 405 http error in POST on Django, the is problem in the urls?
Getting 405 status after using POST method in this django aplication #urls """Configuracoes de URL dos Resultados das Buscas https://docs.djangoproject.com/en/3.1/topics/http/urls/ """ from django.conf.urls import url from django.urls import path from . views import BuscaHorarios, AgendaHorario app_name = "agendamento" urlpatterns = [ url(r'^(?P<prestadorservicosid>[0-9]+)(?:/(?P<unidadeid>[0-9]+))/$', AgendaHorario.as_view(), name='horarios', ), url('/', AgendaHorario.as_view(), name="agenda_horario"), ] I think the problem occurs over here, but i'm not sure ##forms from django.forms import Form, CharField, EmailField, EmailInput, TextInput class AgendaHorarioForm(Form): nome_paciente = CharField(required=True, widget=TextInput( attrs={'placeholder': 'Digite seu nome completo', 'class': 'form-control', 'label_tag': 'Nome do paciente'})) email_paciente = EmailField(widget=EmailInput(attrs={'placeholder': 'Digite seu e-mail', 'class': 'form-control', 'label_tag': 'E-mail'})) telefone_paciente = CharField(required=True, widget=TextInput( attrs={'placeholder': 'Digite seu telefone com DDD', 'data-mask': '(00) 00000-0000', 'class': 'form-control', 'label_tag': 'Telefone com DDD'})) views class AgendaHorario(View): form_class_agenda = AgendaHorarioForm paciente = {} prestadorunidade = None prestadorservicos = None servicoregioes = None agenda_service = None horario_marcado = None def get_context_data(self, **kwargs): print('a') context = super().get_context_data(**kwargs) context['prestadorunidade'] = self.prestadorunidade context['prestadorservicos'] = self.prestadorservicos context['horario_marcado'] = self.horario_marcado context['paciente'] = self.paciente print('a') return context def post(self, *args, **kwargs): print('b') if self.request.is_ajax and self.request.method == "POST": form = self.form_class_agenda(self.request.POST) if form.is_valid(): post_data = form.cleaned_data self.paciente['nome'] = post_data['nome_paciente'] self.paciente['email'] = post_data['email_paciente'] self.paciente['telefone'] = post_data['telefone_paciente'] lista_unidades = list(cache.get('PrestadorUnidades', PrestadorUnidades.objects.values())) unidadeid = int(self.request.POST.get('prestadorunidadeid')) self.prestadorunidade = [item for … -
django admin, instance save issue
On django admin (list or change view), I would like to do the following: When somes fields are checked, the instance of the model could not be modified anymore. I tried to override model save: if self.is_prepared is False: if self.A and self.B: self.is_prepared = True super(MyModel, self).save(*args, **kwargs) But in the admin page (list or change view), on a 'is_prepared == True' instance I could still change all field of the instance. Seems like the admin is not using the model save. My admin looks like this: form = MyForm def save_model(self, request, obj, form, change): """ Force form to use model save """ if obj.is_prepared is False: obj.save() -
Second Order SQL Injection
def find_or_create_bp(bp_metadata): """ Returns a BusinessProcess, creating a new one if not found. """ bp_id = bp_metadata['id'] bp_name = bp_metadata['name'] bp_matches = BusinessProcess.objects.filter( bp_id=bp_id, bp_name=bp_name ).order_by('-id') if bp_matches: bp = bp_matches[0] else: bp = BusinessProcess( bp_id=bp_id, bp_name=bp_name ) bp.save() print("BusinessProcess created: " + bp_name) return bp Method find_or_create_bp at line 42 of project/api/src/monitoring_backend/monitoring_app/management/commands/migrate_watchitemconfigs.py gets database data from the filter element. This element’s value then flows through the code without being properly sanitized or validated, and is eventually used in a database query in method find_or_create_step at line 64 of project/api/src/monitoring_backend/monitoring_app/management/commands/migrate_watchitemconfigs.py. This may enable an Second-Order SQL Injection attack. -
Django reload - ajax GET after POST does not get latest database model instances
This question has been posted in different ways already but I can't get it to work.. I don't use AJAX yet in my script but I should use it as my database update is not visible in my application. Only when I restart the application, I can see the change. Can someone help me? I currently have this: .html {% block content %} <form id="post-setting-form" class="card" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="card-body"> <h3 class="card-title">Update Mail Settings</h3> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="form-label">Send Emails:</label> <p></p> <input type="radio" name="update_type" value="manual" {% if view.manualSetting %}checked {%endif%}> Manual {% if view.manualSetting is 1 %} ( Current setting ) {% else %} {% endif %}</input> <p></p> <input type="radio" name="update_type" value="auto" {% if view.autoSetting %}checked {%endif%}> Automated {% if view.autoSetting is 1 %} ( Current setting ) {% else %} {% endif %}</input> <p></p> <button type="submit" class="btn btn-primary">Update</button> </div> </div> </div> </div> </form> {% endblock %} .views class AutoSendView(generic.TemplateView): template_name = 'core/mailbox/autoSendMail.html' context_object_name = 'autosend' extra_context = {"mailbox_page": "active"} model = AutoSendMail.objects.get(pk=1) model.save() model.reload model.refresh_from_db() autoSetting = int(model.auto == True) manualSetting = int(model.manual == True) def post(self, request, *args, **kwargs): id_ = self.kwargs.get("pk") logger.info("testestest") update_type = self.request.POST.get('update_type') logger.info(update_type) if update_type == 'manual': …