Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Anywhere djago
I tried to deploy a Django app with Python Anywhere. To do this I added all of the files in a zip folder I uploaded it to the Files section and I unzipped it from the bash console. But when I run the site it returns The install worked successfully! Congratulations!You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs.. But I have uploaded the views.py so what happens? Please give me a solution. Thanks. -
how long Express.js will survive against others backend frameworks?
I have been working as a freelance web developer for a long time but now a few questions are just rolling around in my head! What is the current demand for express.js? Apart from express, nodejs has many backend frameworks... eg: koa, hapi, adonis, loopback etc... then again deno & bun (for which node's existence is threatened [I think])! So will there be demand for node/express in the future among so many competitors? Note: I work with mern and also have experience with python(flask, django), in this case should I keep express as backend or go with django + react? In short, express or django which job is more! Or if you learn which one can survive in the market for the next 5-10 years? I am very depressed -
Which Tech stack should be needed to text viewer with highlight function
I'm working on a team project with friends who started web development. We are planning a website that shows users any newspaper articles on a user-specified topic every day. We want to create a website that provides features such as highlighting when a user drags a particular phrase, and writing a note next to it. Users can store articles in their own repository as they highlighted or underlined. (I understand that Microsoft Edge provides similar functionality.) In this case, I have no idea which technology stack should be used to perform the above functions, so I ask you a question. The server is about to be implemented with Django. Microsoft Edge -
NoReverseMatch: Reverse for 'delete_url' with arguments '('',)' not found. 1 pattern(s) tried: ['delete_url/(?P<web>[0-9]+)\\Z']
Hi I'm getting an error when I run my code. I am trying to create a delete function on my webpage. Thank you for your time. My code is as follows: home.html : error is in the href tag {% for web in webs_list %} <tr> <th scope="row"> {{web.url.id}} </th> <td> {{web.url.website}} <a href="{% url 'delete_url' web.id %}" > <button type="button" style="float: right;" class="btn btn-outline-danger">Delete</button> </a> <div class="space" ></div> <button type="button" style="float: right;" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#updateModal" >Update</button> </td> {% if web.status == "True" %} <td> <a class="btn btn-success">Up</a> </td> {% else %} <td> <a class="btn btn-danger">Down</a> </td> {% endif %} </tr> {% endfor %} urls.py path('delete_url/<int:web>',views.delete_url,name="delete_url"), views.py def delete_url(request,web): url = Website.objects.get(pk=web) url.delete() return redirect('monitor/home.html') -
Django Forms and Mapbox how to save data when page is refreshed
I have been struggling with this problem for a long time now and I cannot seem to find any problem similar to it with a solution. Basically the project that I am working on involves use of the Mapbox framework which displays a map of Yellowstone national park. The user is then able to click on an upload picture button which sets a boolean value either "true" or "false" for if they want to upload a picture based where on the map they click next. If this value was true and the user clicks on a spot on the map, the coordinates of the cursor is then used to place a marker with a popup containing a Django form. This form model can then be filled out the user can press submit. default map img filling out post on map img Ideally I would like the submit button to just place to filled out form within the popup and also keep the marker there. Right now whenever I hit submit, the whole page gets refreshed and the map get re-loaded and all modifications made simply disappear. The filled out form that was submitted does get added to my database though. … -
Django tenant based users
Scenerio: A global user can visit any tenant Different tenant will create different user of their own password A general user can create account in different tenant with different password Tenant superuser can create their own group with permission Using django_tenant and django_tenant_users. But can not able to do these. Need suggestion how to achieve this using django -
How can I retrieve a Word document from my Django endpoint?
I am interested in making a web application with a Vue frontend and Django backend that allows the user to upload a word document to a Django API with a configuration object to format and edit the document with python-docx. I am currently trying to download the file from the REST endpoint and keep encountering this issue. script.js:32 Error: SyntaxError: Unexpected token P in JSON at position 0 I am using fetch to make the POST request to the endpoint and I honestly think the error lies somewhere in there if not my file object handling. The application is currently without much exception handling because I just want to see if I can get this core mechanism to work so apologies on the current state of the application. script.js api call methods: { run(e) { //test data const config = { pageLimit: 9, marginSize: 1, }; const fileInputField = document.getElementById("document"); const formData = new FormData(); formData.append("config", JSON.stringify(config, null, 2)); formData.append("file", fileInputField.files[0]); fetch("http://localhost:8000/format/", { method: "POST", body: formData }) .then(response => response.blob()) .then(blob => { var a = document.createElement("a"); a.href = window.URL.createObjectURL(blob); a.download = "Test.docx"; document.body.appendChild(a) a.click(); }) .catch(error => { console.error("Error:", error); }) } }, views.py format endpoint def format(request): … -
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??