Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
XMLHttpRequest doesn't send the data
I'm making a POST request from my react component to django-backend. My request goes to my server but I can't take the data I sent. The thing is I can log the status with onload on browser and I get 200 and I do get a POSTrequest in django so there is no problem with making a POSTrequest, the problem is sending data. send seems the problem here. My react component: import React, { useEffect, useState } from "react"; import { BiMeteor } from "react-icons/bi"; import { registerUser } from "../lookup"; export function RegisterComponent() { function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function registerUser(e) { e.preventDefault(); const url = "http://localhost:8000/register"; const method = "POST"; /* const data = JSON.stringify({ username, password }) */ const xhr = new XMLHttpRequest(); const csrftoken = getCookie("csrftoken"); xhr.open(method, url); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest"); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("X-CSRFToken", csrftoken); … -
drf CustomUser matching query does not exist
i'm working on mobile app with customuser. i'm trying to send otp on mail while creating user and set is_verify to false and after that user verify with otp then is_verify will set to true but if user does't verify otp add closes app then again while signup we're adding check if user exist and is_verified to true then return already exist otherwise create user and send otp again. so i'm getting error on if user doesnotexist then its showing this error: users.models.CustomUser.DoesNotExist: CustomUser matching query does not exist. and its getting this error from except customuser.doesnotexist block models.py: class CustomUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(_('first name'), max_length=50) last_name = models.CharField(_("last name"), max_length=50) email = models.EmailField(_('email address'), unique=True) mobile_number = models.CharField( _('mobile number'), max_length=12, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) user_type = models.IntegerField(_("user_type")) otp = models.CharField(_("otp"), max_length=10, default="0") is_verified = models.BooleanField(default=False) USER_TYPE_CHOICES = ( (1, 'users'), (2, 'courier'), (3, 'admin'), ) user_type = models.PositiveSmallIntegerField( choices=USER_TYPE_CHOICES, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserMananager() def __str__(self): return self.email seralizers.py: class CustomUserSerializer(serializers.ModelSerializer): profile = UserProfileSerializer(required=False) password = serializers.CharField(write_only=True, required=False) class Meta: model = CustomUser fields = ('id', 'first_name', 'last_name', 'email', 'mobile_number', 'password', 'is_active', 'user_type', 'otp', 'profile') def … -
How to store form data as draft in django
I'm working on a project that requires to store form data as a draft if the user closes the browser or leave the tab or any other case. and when the user opens the same form next time the user can see the previously entered data -
The requested resource was not found on this server. React + Django
I'm deploying my first Django + React app do a Droplet with Apache2. I've deployed some Django apps but this is my first time deploying a React app not to mention a React and Django app. When I visit the homepage I get The requested resource was not found on this server. and when I visit /admin I get the login page but without any styles. I notice in my dev tools I see 404 in the network tab. settings.py import environ ROOT_DIR = ( environ.Path(__file__) - 3 ) REACT_APP_DIR = ROOT_DIR.path("react_frontend") STATICFILES_DIRS = [ os.path.join(str(REACT_APP_DIR.path("build")), 'static'), ] STATIC_ROOT = '/srv/react-django-portfolio/react_frontend/build/static' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ str(REACT_APP_DIR.path("build")), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] sites-available/portfolio.conf <VirtualHost *:443> ServerName example.com DocumentRoot /srv/react-django-portfolio/django_backend/django_backend SSLEngine on SSLCertificateFile /etc/ssl/example.crt SSLCertificateKeyFile /etc/ssl/example.key SSLCertificateChainFile /etc/ssl/example.ca-bundle ErrorLog ${APACHE_LOG_DIR}/portfolio-error.log CustomLog ${APACHE_LOG_DIR}/portfolio-access.log combined WSGIDaemonProcess portfolio processes=2 threads=25 python-path=/srv/react-django-portfolio/django_backend WSGIProcessGroup portfolio WSGIScriptAlias / /srv/react-django-portfolio/django_backend/django_backend/wsgi.py Alias /robots.txt /srv/portfolio/static/robots.txt Alias /favicon.ico /srv/portfolio/static/favicon.ico Alias /static/ /srv/django-react-portfolio/react_frontend Alias /media/ /srv/portfolio/media/ <Directory /srv/react-django-portfolio/django_backend/django_backend> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /srv/react-django-portfolio/react_frontend/build/static> Require all granted </Directory> <Directory /srv/reat-django-portfolio/django_backend/media> Require all granted </Directory> </VirtualHost> -
Django Multitenant Single Login. after logged in it should be redirect to sub-domain
I want to know how to access a Django multitenant user in a single login(my-domain.com/login). After logging in it should be redirected to a specific tenant subdomain(tenant1.my-domain.com). Please give me a solution to that. -
How to use group by and get every record in each group?
I want to summarize all attendance records of each person every day,in my current solution, i need to get all records then use for loop, is there a better way to get the queryset like the following: class AttendanceRecord(models.Model): f_UserInfo = models.ForeignKey(to=UserInfo, on_delete=models.CASCADE) f_Device = models.ForeignKey(to=Device, on_delete=models.CASCADE) f_time = models.DateTimeField(auto_created=True) # How to group record by user and get a queryset like the following? [ {user_id1: [ {'f_Device_id': 1, 'f_time': '2020-11-11 8:00:00'}, {'f_Device_id': 1, 'f_time': '2020-11-11 18:00:00'} ]}, {user_id2: [ {'f_Device_id': 2, 'f_time': '2020-11-11 8:00:00'}, {'f_Device_id': 2, 'f_time': '2020-11-11 18:00:00'} ]}, ] -
Python Datetime Showing one day ahead date
I encountered one weird issue. I have one Django project, which uses (America/Denver) timezone by default. I got a couple of records into the database. id name date_create 1 foo Dec. 8, 2020, 6:15 p.m. 2 bar Dec. 1, 2020, 8:28 p.m. When I print the above record, it behaves weirdly. >>> print(record_one.date_create.date()) >>> Dec. 9, 2020 >>> print(record_one.date_create) >>> Dec. 8, 2020, 6:15 p.m. >>> print(record_two.date_create.date()) >>> Dec. 2, 2020 >>> print(record_one.date_create) >>> Dec. 1, 2020, 8:28 p.m. I am using python 3.5 and Django2 Django setting LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Denver' USE_I18N = True USE_L10N = True USE_TZ = True -
django with dynamic country state and city selection field in template
I want a country, state, and city selection field in my HTML. I want to use Django forms for dynamically changing state list if I change the country. and also require Django form validation. for example how can I achieve this with Django forms and models? -
django.core.exceptions.ImproperlyConfigured: The included URLconf does not appear to have any patterns in it
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'basic_app.urls' from 'C:\Users\shree\learning_users\basic_app\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. code in basic_app.url from django.urls import path from basic_app import views app_name = 'basic_app' url_patterns = [ path('register', views.register, name='register'), ] code in learning_users.url from django.contrib import admin from django.urls import path,include from basic_app import views # from django.conf.urls import url,include urlpatterns = [ path('',views.index,name='index'), path('admin/', admin.site.urls), path('basic_app/',include('basic_app.urls')), ] -
gunicorn: command not found in django app configured for docker and azure
I'm trying to deploy a pretty simple dockerized Django app to Azure. I was successfully able to push the containerized repository to Azure. When I run docker run <myloginserver>/myappname:v1, per instructions here: https://docs.microsoft.com/en-us/azure/container-registry/container-registry-get-started-azure-cli I get two errors: /usr/local/bin/init.sh: line 2: -e: command not found /usr/local/bin/init.sh: line 6: gunicorn: command not found gunicorn is installed in both my pipfile and my requirements.txt, and comes up as a satisfied requirement when I try to reinstall. How should I approach this? -
Reverse for 'add_comment' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['addComment/(?P<id>[0-9]+)/$']
Hello I am trying to add comments to a page but when I press submit I get this error: Reverse for 'add_comment' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['addComment/(?P[0-9]+)/$'] forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['response'] Form on the page <form action="{% url 'CA:add_comment' id=climb.id %}" method="POST"> {% csrf_token %} <label for ="comment"></label> <textarea class="form-control" name="comment" id = "comment" rows = "5"placeholder="Add a comment"></textarea> <br> <input type="submit" class = "btn btn-primary" value="Add Comment"> </form> models.py class Comment(models.Model): response = models.CharField(default="Blank Comment", max_length=500) username = models.ForeignKey(User,default= 1, on_delete = models.CASCADE) date = models.DateTimeField(auto_now=True) climb = models.ForeignKey(Climb, on_delete = models.CASCADE) views.py def addcomment(request, id): climb = Climb.objects.get(id=id) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.response = request.POST["response"] data.username = request.user data.climb = climb data.save() return redirect('CA:cd', id=climb.id) else: form = CommentForm() context={ "form" : form } return render(request, "climbDetail.html",context=context) urls.py path('addComment/<int:id>/', views.addcomment, name='add_comment'), I can't figure out what is going wrong. Any help would be greatly appreciated. -
How to clear an image field in django forms?
So my views look like this: class PostCreateView(CreateView): model = Post fields = ['title','content','image', 'status'] The image field currently looks like this: Is there a way to have like a button to clear the image from the field? The only way to remove the image is to do it from django admin page. -
Importing a class with only the package name?
So, I'm trying out Django and I noticed that we do something like this whenever we want to work with a model in model.py: from django.db import models and whenever we want to subclass a Model class we do something like this: class SomeModel(models.Model) I was curious to see what was in models so I looked at the django directory in the site-packages. It has a directory like this: django db models //some-other-modules so "models" is just a subpackage within the "db" subpackage. My question is how are we able to subclass Model the way I did above? We're only importing the subpackage "models" and the class "Model" must be located somewhere in one of the modules inside models, but that module isn't ever specified. Can someone explain? Let me know if I need to clarify. -
which error occurs in python when data is not found in database?
I am working on a project in python Django and there I am fetching data from a database there are some code where fetching data is related to product attributes so when the product has attribute size then I have to fetch data otherwise not so which exception class should I use in "try" "catch" and how? -
Circle progress bar using python and django
my project is about getting texts from input and counts how many words and numbers are in that text.i want to show it as percentage too. how can i make Circle progress bar in django like this here thanks -
style.css didnt update with collecstatic - AWS
I'm currently trying to update my aws static files with python manage.py collectstatic, but it won't update. Here is what it looks like header{ position: absolute; z-index: 10; width: 100%; } .header-in{ position: absolute; z-index: 10; width: 100%; } .headerContent{ margin: 10 auto; } .navbar{ margin-top: 0; padding: 20px 0; } .navbar-light .navbar-nav .nav-item .nav-link:hover, .navbar-light .navbar-nav .nav-item.active.nav-link { background:#f6e58d } .banner{ position: relative; background: url('/static/bg.jpg'); min-height: 100vh; background-size: cover; background-position: center; padding: 250px 0 250px; } .banner h2{ margin: 0; padding: 0; font-size: 2.3em; } .banner p{ margin: 1em 0 0; padding: 0; font-size: 1.2em; } Now how it should be looking header{ position: absolute; z-index: 10; width: 100%; } .header-in{ position: absolute; z-index: 10; width: 100%; } .headerContent{ margin: 10 auto; } .navbar{ margin-top: 0; padding: 20px 0; } .navbar-light .navbar-nav .nav-item .nav-link:hover, .navbar-light .navbar-nav .nav-item.active.nav-link { background:#f6e58d } .banner{ position: relative; background: url('/static/bg.jpg'); min-height: 100vh; background-size: cover; background-position: center; padding: 250px 0 250px; } .banner h2{ margin: 0; padding: 0; font-size: 2.3em; } .banner p{ margin: 1em 0 0; padding: 0; font-size: 1.2em; } .slidershow{ width: 700px; height: 400px; overflow: hidden; } .middle{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } My setting.py related to … -
Django crispy forms not accepting fields in UpdateView: .|as_crispy_field got passed an invalid or inexistent field
I need some help trouble shooting. So my problem is that the update view seems to work fine when I set field = '__all__' but when I try to specify the fields, then it provokes this error: |as_crispy_field got passed an invalid or inexistent field I'm not sure why this is happening views.py class FooUpdate(UpdateView): model = Foo fields = ['bar'] def get_success_url(self): return reverse('Foo_list', kwargs={'pk': self.object.bar.id}) foo_form.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.bar|as_crispy_field }} </form> -
Django Heroku, ValidationError at /admin ['“admin” is not a valid UUID.']
When trying to access the admin page on my Heroku deployment I keep getting this error. ValidationError at /admin ['“admin” is not a valid UUID.'] It seems to be redirecting me to a different view that uses a slug in the url, setting the slug to 'admin'. This only happens on the Heroku deployment. I think I may need to define 'admin/' in urls.py but i'm not sure how. urls.py urlpatterns = [ path('', views.homeView, name='home'), path('profile/', views.profileView, name='profile'), path('game/', views.gameView, name='game'), path('login/', views.loginView, name='login'), path('logout/', views.logoutView, name='logout'), path('register/', views.registerView, name='register'), path('info/', views.infoView, name='info'), path('mygame1v1/', views.mygame1v1View, name='mygame1v1'), path('mygameteamplay/', views.mygameteamplayView, name='mygameteamplay'), path('mygameffa/', views.mygameffaView, name='mygameffa'), path('<slug:slug>', views.gamepageView, name='gamepage') ] views.py (the view being redirected to) @login_required(login_url='/login/') def gamepageView(request, slug): game = OneVsOneGame.objects.get(player1=request.user, gameid=slug) -
HTTP GET returns undefined or everything in Ionic with Django REST filters
I'm working on an app with ionic that consumes an API built with Django REST. I have two views where I set the REST filters, but when I try to do an HTTP GET request on the ionic App, the "Residente" view returns "undefined" and the "Vigilante" view doesn't respect the filtering. I'm not sure what's going on. Here are my Django views class ResidenteView(viewsets.ModelViewSet): """ Obtiene todos los residentes existentes """ queryset = Residente.objects.all() serializer_class = ResidenteSerializer filterset_fields = ('telefono', 'codigo_acceso') class VigilanteView(viewsets.ModelViewSet): """ Obtiene todos los vigilantes existentes """ queryset = Vigilante.objects.all() serializer_class = VigilanteSerializer filterset_fields = ('usuario', 'password') Here is the code of the http requests getResidente(phone: string, code: string) { return this.http.get( this.constants.API_URL + "residentes", { telefono: phone, codigo_acceso: code }, {} ); } getVigilante(user: string, password: string) { return this.http.get( this.constants.API_URL + "vigilantes", { usuario: user, password: password }, {} ); } -
DRF url doesnt work when i add parameters
i created this API to retrive session_data based on session_key from the table django_session. i get the requested behavior with the session_key as a static field, like in the below code and this screenshot #urls.py path('session_data/',views.get_session_data,name='session_data'), #views.py @api_view(['GET'],) def get_session_data(request): session_key='pirxxzoh3rifjqch403ro8nfmkzmg972' response_content=decode_session_data(session_key) return JsonResponse(response_content,safe=False) once i change my code by adding a paramter str:session_key to urls.py and to the get_session_data, i get 404 Not found response. here is the code: @api_view(['GET'],) def get_session_data(request, session_key): #session_key='pirxxzoh3rifjqch403ro8nfmkzmg972' response_content=decode_session_data(session_key) return JsonResponse(response_content,safe=False) and for urls.py i tried both and it didnt work. path('session_data/<str:session_key>',views.get_session_data,name='session_data'), path('session_data/<str:session_key/>',views.get_session_data,name='session_data'), first_error POSTMAN_ERROR another_error thanks in advance. -
Django friend feed view
I have a custom user model extended with a one to one relationship to a Profile model, I also have a Post model. I want to create an attribute inside of Profile to store Posts of the users friends to make a recent updates feed. However I am struggling with what attribute or type of data storage to use (idk what to call it). Can anyone help? The line of code relevant is bolded in the code below. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name = 'profile', on_delete = models.CASCADE) image = models.ImageField(default = 'Default.png', upload_to = 'Profile_pics') slug = AutoSlugField(populate_from = 'user') bio = models.CharField(max_length = 255, blank = True) relationship = models.ManyToManyField('Profile', blank = True) **feed_posts = ArrayField(blank = True, default = list)** -
Django Radio buttons customize with bootstrap 4
I'm building a site in Django 2.2.13, and I need to seriously customize some radio buttons from RadioSelect in Django, here's the expected result above the current output: And here is the code in forms.py: gender = forms.MultipleChoiceField( required=True, widget=forms.RadioSelect, choices=GENDER_CHOICES ) Now in the HTML template: <div class="form-group"> <label><h4>Soy / Somos...</h4></label> <br> <div class="container"> <div class="row"> <label class="form-check form-check-inline col-5 col-md-3 card bg2"> <input class="form-check-input" type="radio" name="gender" value="option1"> <span class="form-check-label"><i class="fas fa-mars fa-2x"></i><h6>Hombre</h6></span> </label> <label class="form-check form-check-inline col-5 col-md-3 card bg2"> <input class="form-check-input" type="radio" name="gender" value="option2"> <span class="form-check-label"><i class="fas fa-venus fa-2x"></i><h6>Mujer</h6></span> </label> <label class="form-check form-check-inline col-10 col-md-3 card bg2"> <input class="form-check-input" type="radio" name="gender" value="option2"> <span class="form-check-label"><i class="fas fa-venus-mars fa-2x"></i><h6>Otro(s)</h6></span> </label> <label class="form-check form-check-inline col-10 col-md-3 card bg2"> <input class="form-check-input" type="radio" name="gender" value="option2"> <span class="form-check-label"><i class="fas fa-venus-mars fa-2x"></i><h6>Mixto</h6></span> </label> </div> </div> </div> <!-- form-group end.// --> {{ form.gender }} <hr> I'd really appreciate your help!! -
How to make donation buttons to different non-profits?
I would like to make an website where people could come and place a small donation to a non-profit of choice. Then the site would rank the givers and the organizations based on amount. Like here when people answer questions and so on. Instead of shouting at a sports game, users could make their favorite organization 'win'. After searching for donate-buttons to implement I realized there isn't any. No API's either. It would be awesome to have a donate-to-favorite-org button that looks like buy-me-a-coffee button. How could this be done in a way that no one could tamper with the money given and at the same time make the entire process transparent? I would like to use Django as a back-end. Thanks! -
How do I post the first value of a query set in HTML?
Hey guys I need to post the first value of a query set in HTML. Currently, I'm iterating through the entire query site and printing out every match but I don't want that. I'm using Django and I use the objects.get() filter which I thought only grabs one record but it is grabbing multiple. I just want it to grab the category they were just in so after they make a post, they can easily return back to that categories forum page. How do I print it out in HTML or how do I do the Django query to only get one record so I can easily just display that in HTML? Thanks! HTML: {% for query in queries %} <h4>Return to the <a href="/movies">{{query.category}}</a> Forum</h4> {% endfor %} views.py: query = NewPost.objects.get(category = category) return render(request, "network/posted.html", {"queries": query}) -
How to wait for the get request to finish in React?
I'm new to react and need to represent a JSON array in a table. The format of the array is [{"transaction_amount": 39.98, "transaction_date": 2020}, {...}]. This works when I assign this fixed data to a constant but if a request it from props, it isn't rendered. The below code doesn't work: <App transactions={this.state.transactions} /> const App = props => { const data = props.transactions; const columns = [ { title: "#", data: "id" }, { title: "Transaction Amount", data: "transaction_amount" }, { title: "Transaction Date", data: "transaction_date" }, ]; return ( <> <h5 className="mt-2 mb-4 text-center">Recent Transactions</h5> <DataTable data={data} columns={columns} /> </> ); }; but if I replace data with: const data = [{"transaction_amount": 39.98, "transaction_date": 2020}, {...}] then everything works fine. I'm guessing that the error is that the first time the page is rendered, props.transactions is empty. How can I fix that? This is the function for the get request: load() { axios.get('http://127.0.0.1:8000/api/payments?type=company',{ headers: {'Authorization': 'Token ' + sessionStorage.getItem('token')} }) .then(res => { this.setState({failed:false}); setTimeout(() => { this.setState({ transactions: res.data, loading: false }); }, 500) }) }