Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model passes wrong value
I am making a webapp with Django Framework. I am making a form for creating new "incidents" (this form is using a model called NewIncidents). I am trying to take the values under "title" from my IncidentsType table, and use them as options for a Select menu in the form. But, something weird happens: in the form, the options appear, but when you submit the form and check how it was submitted (in the admin panel), it shows the .object(n) instead of the name of the option. For example: Result of one submit : in the form showed the correct selection name, which was "Internet", but after submitting, in the admin panel, it showed IncidentsType object (3). My models: from django.db import models class NewUsers(models.Model): name = models.CharField(max_length=38) user_name = models.CharField(max_length=35) class NewIncidents(models.Model): tipo = models.CharField(max_length = 50) titulo = models.CharField(max_length = 200) resolucion = models.CharField(max_length = 300) class IncidentsType(models.Model): title = models.CharField(max_length = 200) subtitle = models.CharField(max_length = 200) description = models.CharField(max_length = 400) My form: from django import forms from django.db import models from .models import NewIncidents, IncidentsType class IncidentForm(ModelForm): incidents = IncidentsType.objects.all() eleji = [] for incident in incidents: ttype = incident.title num = str(incident) conjunto = … -
Problem to connect the django with mongodb using djongo
How i use DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'rede_social', 'HOST': 'mongodb+srv://blackwolf449:3CErLxvGLPM4rLsK@cluster0.w1ucl2e.mongodb.net/?retryWrites=true&w=majority', 'USER': 'blackwolf449', 'PASSWORD': '3CErLxvGLPM4rLsK' } } Error django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
What is the login url in django cognito jwt
I am testing django-cognito-jwt.I have configured a user pool and created a id_token from aws. I want to try and login using this token.I have set up the project but can't figure out what the login url should be.. I am running the project in local server localhost/8000/login ? -
django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution. Django for professionals book
These are my docker files getting this error while changing my engine from SQLite to PostgreSQL. Doing it for the first time following book called Django for professionals docker-compose.yml services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: dockerfile FROM python:3.9.6 #set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 #set work directory WORKDIR /code #install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ -
How to display the current value of the range input field (slider)
What you want to achieve I want to input numbers in the django form like this. Current code class Comment_movie_CreateForm (ModelForm): class Meta: model = Comment_movie fields = ('comment','stars') comment = forms.CharField (required = False, label ='comment', max_length = 1000) stars = forms.FloatField (required = False, label ='stars', widget = forms.TextInput ( attrs = {'type':'range','id':'form_homework', "class": "no_resize",'min': '0','max': '10','step': '0.1' }))) def clean (self): cleaned_data = super (). clean () return cleaned_data def clean_stars (self): stars = self.cleaned_data ['stars'] if stars! = None: if stars <0 or stars> 10: raise forms.ValidationError ("The rating input is incorrect.") return stars else: else: raise forms.ValidationError ("The rating input is incorrect.") def clean_comment (self): comment = self.cleaned_data ['comment'] if len (comment)> 1000: raise forms.ValidationError ("There are too many characters.") elif len (comment) == 0: raise forms.ValidationError ("Please enter the characters.") return comment def __init__ (self, * args, ** kwargs): super () .__ init__ (* args, ** kwargs) self.label_suffix = "" <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form }} {% if comment_tv %} <button type="submit">Edit Comment</button> <button type="submit" name="action" value="delete">Delete Comment</button> {% else %} <button type="submit">Post Comment</button> {% endif %} </form> What you want to ask I want to make a slide bar as … -
django-taggit field not saving list Initially
I am using django-taggit for tags. I want to add all other fields of the same table in tags automatically when I save the data table. I am using the postsave method but all fields value are saved in the tags table but not in the Tags field of resource table. class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(default="") Tags = TaggableManager() def tag_set(sender, instance,*arg, **kwargs): ans= array_tag(instance) # print(and) mylist = ["firmware", "download", "gsm"] instance.title='check' instance.Tags.add(*ans) post_save.connect(tag_set, sender=resource) def array_tag(instance): return [instance.title ,instance.desc,instance.size, instance.Brand.title ,instance.Model.title ,instance.Categories.title] -
Demade d'aide sur send mail django
Bonjour, j'ai voulu envoyer un e-mail avec Django mais autorisation des applications moins sécurisée n'est plus disponible sur gmail, je ne sais pas comment je peux pour envoyer un e-mail avec Django. -
Is there any way to "hook" in or modify program to download file from cloud storage and inject it into Stdin with Python?
I have a python program package I didn't write called Slither. I've installed package and there's a command I need to capture output but it only accepts a file path example slither filename.sol I want to put this behind a Django API and capture the output, modify it and return to user. The problem is I deployed app to Heroku which has ephemeral storage. I've chosen cloundary as cloud storage provider and plan to upload the file to Cloundary which is similar to AWS bucket. This seems to work except then I get a uri back like say https://mybucket.cloundary.io/mybucket The problem is slither does not accept this type of file path. I'm currently using: f"slither {'./files/'+filename} ", stderr=subprocess.STDOUT, shell=True, timeout=120, universal_newlines=True) Is there a way too hook into process or modify this so I could do something like f"slither {'https://mybucket.cloundary.io/mybucket'} ", stderr=subprocess.STDOUT, shell=True, timeout=120, universal_newlines=True) -
Django development server crashes
I noticed that the application stops responding. It spins loading, but I can't do anything. The application starts working again when I use CTRL+C in the console. Then I get a message about a broken pipe. I can't find a solution. I searched the Internet, but the threads are only for the broken pipe message. In addition, in those cases, the server was still running, while in my case it is frozen until it is restarted. The situation is with Django 3.2.3 with a SQLite database. -
Django app when deployed on Heroku using git gives error relation "auth_user" does not exist, on local server it works well
Django app deployed on Heroku using git gives below error message webpage launches but the error comes when app is trying to access database from heroku link when using app on localhost everything works well Getting error message "ProgrammingError at /signin relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user..." after app was deployed using Heroku when on local server everything works well, the error only happens on heroku when app tries to access the database. "The above exception (relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ^ ) was the direct cause of the following exception: /app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py, line 55, in inner" Have tried running migrate commands still same error. Thanks for your help -
Django import-export: Export a many-to-many relationship as though it was the base model
What I have Two models, Users and Magazines, in a many-to-many relationship via a Subscriptions table. The rough model structure is: class User(models.Model): # ... class Magazine(models.Model): subscriptions = models.ManyToManyField(User, through="Subscription") # ... class Subscription(models.Model): user = models.ForeignKey(User, ... magazine = models.ForeignKey(Magazine, ... signed_up_on = models.DateField() active = models.BooleanField() What I want Magazines have their own admin, but subscriptions don't. They're displayed as an inline in each magazine's detail view. I need to export the subscriptions, but not the magazines, via a button (or admin action) on the magazine admin page. All I need in the returned data are the user and magazine ids, as well as the other columns on the subscription table. I tried hacking this together via the options I found in the django import-export docs, but couldn't figure out a way to do this. Overriding subscription resource's get_queryset() method didn't do anything because that method is only called when the queryset is None, and the library helpfully populates the queryset ahead of time. The ManyToManyWidget also looked promising, but it concatenates every associated value into the same cell. I don't need one row per magazine with all subscriptions concatenated together, I need one row per subscription. … -
Use Javascript variable in Django Tempate
Before getting into the question, I know that there are a lot of similar questions on Stack Overflow, but from what I've seen none has produced an answer I can use -- please correct me if I'm wrong. I have a JavaScript variable that looks like this (this is in a <script> tag). var html = '<img src = "{% static "img/chesspieces/wikipedia/(I guess this is the part I'm not sure about)" %}"' I have another JavaScript variable called piece that I would like to inject like this {{piece}}, but can't since it's a JavaScript variable, and not a Django variable. A lot of answers to similar questions seem to recommend making a view and calling it every time I want to access the piece variable, but I don't think that has any chance of working in my situation, as it would lead to the Too Many Requests error. -
How to get those records which have a foreign key connected with another exact foreign key?
I build API with django & django rest framework and stuck with writing one view. See the code below: models.py class Order(models.Model): name = models.CharField(max_length=255) posted_by = models.ForeignKey(User, on_delete=models.CASCADE) class Offer(models.Model): order_related = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='offers') author = models.ForeignKey(User, on_delete=models.CASCADE) serializers.py: class OfferSerializer(serializers.ModelSerializer): class Meta: model = Offer fields = '__all__' class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' Now I need a view which return those orders, which have offers in which author = int:pk. E.g. GET /orders/3 should give all orders which have offers with author = 3 plz help me - I can write it with raw SQL but have no idea how to do it via ORM -
Using Django,I want my user when he Register ,He directly go to to create page, But when I do it ,It never go to create page .Here is my code
Views.py #For Cystomer Registration class CustomerRegistrationView(View): def get(self,request): form = CustomerRegistrationForm() return render(request,'mp/register.html',{'form':form}) def post(self,request): form = CustomerRegistrationForm(request.POST) if form.is_valid(): messages.success(request,'Congratulations Registerd Succesfuly ') form.save() success_url = reverse_lazy('profile') return render(request,'mp/register.html',{'form':form}) #For Creating Profile class ProfileCreate(LoginRequiredMixin,CreateView):#ye hogia hamara upload wala model = Profile fields = ['user_name','user_ethnicity','SelectGender','user_job','user_age','mother_additionalinfo'] success_url = reverse_lazy('profile') def form_valid(self,form): form.instance.user = self.request.user success_url = reverse_lazy('profilecreate') return super(ProfileCreate,self).form_valid(form) Urls.py #for register path('register/',views.CustomerRegistrationView.as_view(),name= 'register'), #for CreateProfile path('profilecreate/',views.ProfileCreate.as_view(),name= 'profilecreate'), Also the Important thing is that when i have not setup the Logout Function then it working,But when i steup,Then this not redirect user to another page and stay at Registration Page. -
How to serialize file field without host
I have a file field class Document(models.Model): generated_document = models.FileField( # документ, который создала Celery из шаблона upload_to='generated_files/', blank=True, null=True ) ... I am serializing this field like this class DocumentSerialize(serializers.ModelSerializer): class Meta: model = Document fields = ["generated_document", ...] I want to have this /media/generated_files/expense_contract_2022-07-17-20-02-51.pdf But I have result with host http://<HOST>/media/generated_files/expense_contract_2022-07-17-20-02-51.pdf I know about SerializerMethodField but what is the proper way to remove host in serializer? In urls.py i am using if settings.DEBUG: urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) -
NoReverseMatch as consequence of a form action
This is my urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.rando, name="rando"), path("wiki", views.index, name="index"), path("create", views.create, name="create"), path("wiki/<str:title>", views.title, name="title"), path("wiki/<str:title>/edit", views.edit, name="edit"), ] This is my views.py: def edit(request, title): if request.method=="POST": content = request.POST.get("content") util.save_entry(title, content) return redirect(f'/wiki/{title}') elif request.method=="GET": if title in util.list_entries(): ge = util.get_entry(title) return render(request, "encyclopedia/edit.html", { "title": title, "ge": ge }) else: return render(request, "encyclopedia/error.html") This is what I want to render (edit.html): {% block body %} <h1>Edit {{title}}</h1> <form action="{% url 'edit' %}" method="post"> {% csrf_token %} <textarea id="ctnt" name="content">{{ge}}</textarea> <br> <input type="submit" value="Submit"> </form> {% endblock %} When I want to send the form above with the current action it gives me: NoReverseMatch at /wiki/CSS/edit but when I remove action it doesn't display any error. Could you please tell me why this happens? Thank You -
Django Database not retrieving username/password
IMage can't be posted some reason but it returns both errors: User does not exist Username OR Password not Valid It seems Django is unable to access the database of users as well as passwords. The password consists of numbers, letters, upper/lowercase and a special character $ Below is my login function for LoginPage under views.py from django.shortcuts import render, redirect from django.contrib import messages from django.db.models import Q from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from .models import Room, Topic from .forms import RoomForm # Create your views here. # # rooms = [ # {'id':1, 'name':'Lets learn Python!'}, # {'id':2, 'name':'Design with me!'}, # {'id':3, 'name':'Front End Devs!'}, #] def loginPage(request): if request.method == 'POST': password = request.POST.get('password') username = request.POST.get('username') try: user = User.objects.get(username=username) except: messages.error(request, 'User does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Username OR Password not Valid') context = {} return render(request, 'base/login_register.html', context) The Login_Register.html page code - {% extends 'main.html' %} {% block content %} <div> <form method="POST" action=""> {% csrf_token %} <label>Username:</label> <input type="text" value="username" placeholder='Enter Username..' /> <label>Password:</label> <input type="password" value="password" placeholder='Enter … -
How can I send for new model object create in django
I want to send email if user does something and because of his action some entry is made in the db. I want to do the send email function from my models.py. Is it possible?? -
Installing django rest framework kills the server
I work on ubuntu for creating a django app. Everything went well untill i install rest_framework and add this app to allowed apps list in settings.py Once i did this server started to show internal server errors. Somebody could help on it ? -
Is it important to include status in Django?
I am working on project where I'm importing, parsing and showing JSON data on site. I wanted to ask if it's important to add in JsonResponse "status" attribute. For example: return JsonResponse({"details":"Data parsed successfully!"}, safe=False, status=200) Thanks! -
while generating pdf its give me blank pdf
need to generate byte memory but while I'm trying to save my pdf its give me blank file. enter image description here -
fix RelatedObjectDoesNotExist at /agents/ error in django
i am creating a django CRM website but i a have a problem once i want relate the User to an organisation. model.py class User(AbstractUser): pass class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE)# every USER has one profile def __str__(self): return self.user.username class Agent(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE)# every agent has one user organisation = models.ForeignKey(UserProfile,on_delete=models.CASCADE) def __str__(self): return self.user.email # create signal to listen to event in order to create a profile user once a new user is created. def post_user_created_signal(sender,instance,created,**kwargs): if created: UserProfile.objects.create(user = instance) post_save.connect(post_user_created_signal,sender=User) views.py class AgentCreateView(LoginRequiredMixin, generic.CreateView) template_name = "agent_create.html" form_class = AgentModelForm def get_success_url(self): return reverse("agents:agent-list") def form_valid(self, form): agent = form.save(commit=False) agent.organisation = self.request.user.userprofile agent.save() return super(AgentCreateView, self).form_valid(form) once the user try to create an agent this error below is displayed. RelatedObjectDoesNotExist at /agents/ User has no userprofile. Request Method: GET Request URL: http://127.0.0.1:8000/agents/ Django Version: 4.0.6 Exception Type: RelatedObjectDoesNotExist Exception Value: User has no userprofile. Exception Location: C:\Users\LT GM\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\related_descriptors.py, line 461, in get Python Executable: C:\Users\LT GM\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.4 Python Path: ['F:\DJANGO', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\win32', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\win32\lib', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\Pythonwin'] Server time: Sun, 17 Jul 2022 18:54:40 +0000 -
Django LoginView won't log in user
I have an app that is just meant to authenticate a user with Django's generic authentication views. The problem is that I can't log in a user even with the correct username and password. I keep getting an incorrect username or password error. The email and password are always simple such as, "email@email.com" and "123" as password so there's no way I'm messing up the spelling. I'm using Django's built in LoginView, a custom User model, and a custom AuthenticationForm. I've done this project before pretty much the same way with no issues but I can't find the difference between this project and my older project. This is my code. Thank you for your time. Views from .models import MyUser from .forms import MyUserLogin class Login(LoginView): template_name='loginapp/login.html' authentication_form=MyUserLogin success_url='/loginapp/home models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser class MyUser(AbstractBaseUser): fname=models.CharField(max_length=30) lname=models.CharField(max_length=30) email=models.EmailField(max_length=100, unique=True) phone=models.CharField(max_length=12) password=models.CharField(max_length=200) USERNAME_FIELD='email' forms.py from django.forms import ModelForm from django.contrib.auth.forms import AuthenticationForm from django.forms.widgets import TextInput from .models import MyUser class MyUserLogin(AuthenticationForm): class Meta: model=MyUser fields=['email', 'password'] ... login.html ... <div> <form method='post'> {% csrf_token %} <ul> <li><p>Email</p></li> <li>{{form.username}}</li><br> <!-- using "Email" as the label instead of "Username" --> <li>{{form.password.label}}</li> <li>{{form.password}}</li> </ul> <input type='submit' name='submit' class='submit' … -
How to properly implement Django form session wizard
I've been attempting to construct a multi-step form using the Django session wizard for hours, but I keep getting the error, AttributeError: 'function' object has no property 'as_view'. I'm not sure why this mistake occurred. Any ideas? views from django.shortcuts import render from formtools.wizard.views import SessionWizardView from .forms import WithdrawForm1, WithdrawForm2 class WithdrawWizard(SessionWizardView): template_name = 'withdraw.html' form_list = [WithdrawForm1, WithdrawForm2] def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] return render(self.request, 'done.html', {'data': form_data}) forms from django import forms from .models import Investment, Withdraw from .models import WithdrawStepOne, WithdrawStepTwo class WithdrawForm1(forms.ModelForm): class Meta: model = WithdrawStepOne fields = ['investment_id',] class WithdrawForm2(forms.ModelForm): class Meta: model = WithdrawStepTwo fields = [ 'proof_of_address', 'user_pic' ] urls from django.urls import path from .forms import WithdrawForm1, WithdrawForm2 from . import views urlpatterns = [ path('withdraw/', views.WithdrawWizard.as_view(), name='withdraw'), ] -
404 and 500 Errors in JSON
I am trying to fetch data from the JSON that I made but am receiving the following errors: network.js:26 POST http://127.0.0.1:8000/edit/2 404 (Not Found) network.js:18 GET http://127.0.0.1:8000/edit/2 500 (Internal Server Error) I want to fetch the objects from my Django models so that I can allow the user to edit a post which they had previously made through a Django form when the user presses the edit button. models.py class User(AbstractUser): followers = models.ManyToManyField("self", related_name="users_followers", symmetrical=False) following = models.ManyToManyField("self", related_name ="who_user_is_following", symmetrical=False) def serialize(self): return{ "followers": self.followers, "following": self.following } class Post(models.Model): post = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE, default="") likes = models.IntegerField(default=0) date_and_time = models.DateTimeField(auto_now_add=True) def serialize(self): return{ "id": self.id, "post": self.post, "user": self.user, "likes": self.likes, "date_and_time": self.date_and_time } views.py def edit(request, post_id): if request.method == "POST": edited_post = request.POST.get('post') try: post = Post.objects.get(pk=post_id) post.post = edited_post post.save() except: return JsonResponse({"error": "Editing the post did not work."}, status=404) if request.method == "GET": return JsonResponse(post.serialize()) else: return JsonResponse({"error": "Need a GET request."}, status=404) javascript document.addEventListener('DOMContentLoaded', function(){ const editButtons = document.querySelectorAll('.edit_button'); for (const button of editButtons) { id = button.value; button.addEventListener('click', () => edit_email(id)); } }); function edit_email(id){ console.log("edit button is clicked") console.log(id) document.querySelector('#post_itself').style.display = 'none'; document.querySelector('#date_and_time').style.display = 'none'; document.querySelector('#likes').style.display = …