Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Many-to-many relationship as JSON
Suppose I have have a model consisting of facilities that have employees which work on certain days of the week. #models.py class Weekday: name = models.CharField() # 'Monday', 'Tuesday', etc. class Facility: name = models.CharField() class Employee: name = models.CharField() employer = models.ForeignKey(Facility) # e.g. works on Mondays and Tuesdays weekdays = models.ManyToManyField(Weekday) Now I want my TemplateView to generate a JSON that lists the employees of a given facility by the days of the week. This needs to be JSON because a weekly calendar shall be rendered by javascript. # views.py class CareFacility(DetailView): model = Facility def get_context_data(self): return { 'week_plan_json': ? } The JSON may be something like: [ { 'model': 'Weekday', 'name': 'Monday', 'employees': [ { 'model': 'Employee', 'name': 'John' }, { 'model': 'Employee', 'name': 'Ida' } ] }, { 'model': 'Weekday', 'name': 'Tuesday', 'employees': [ { 'model': 'Employee', 'name': 'John' } ] }, { # Wednesday # etc... } ] The exact format may be different, but I am wondering how to combine the three models in a way that they are grouped by Weekday -
How to pass " # " in url of django site
I have site with django as backened , and i have a url pattern like this in mu urls.py path('api/getnews/home/post/<str:titleInUrl>', getnews.getSpecificHomeNews , name='getspecificHomenews') , Now when I pass Normal Strings in my url like this , things go well api/getnews/home/post/Petrol,%20diesel%20prices%20are%20rising%20but%20why%20govt%20does%20not%20look%20worried But , When i pass anything with '#' symbol in it , Python make it a comment api/getnews/home/post/#MeToo:%20What%20Priya%20Ramani%20said%20after%20acquittal%20in%20MJ%20Akbar%20defamation%20case and I am not able to get my string after the # symbol Anyone Knows , How to get rid of it Thanks in Advance -
there is an error in django-summernote image. I don't know why
enter code here from django_summernote.widgets import SummernoteWidget ,SummernoteInplaceWidget class PostForm(forms.ModelForm): content = forms.CharField(widget=SummernoteWidget( attrs={ 'iframe':False, 'attachment_filesize_limit': 10 * 1024 * 1024, 'summernote': {'width': '100%', 'height': '450px'} })) class Meta: model = Post fields = ('title','hook_text','content','head_image','category') enter image description here enter image description here When I post with big size picture. the image is always have absolute size. It doesn't reduce the size following the browser size. -
Site cannot be reached with Nginx ,Gunicorn , django on aws ec2
I have followed this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 to setup my django app on ec2 but it is not accessible. When I hit the url it says that site cannot be reached. I did ssh to my ec2 instance and uses the curl command it shows me the html page but withot it says connection cannot be established.enter image description here -
request.FILES is always empty
When I try to post a Django form containing a file field, the file field is being passed as part of the request.POST rather than request.FILES (which is empty). This throws a MultiValueDictKeyError on submitting the form. Form html <form class="form-horizontal" action="{% url 'drinkConf' %}" method="post" enctype="multipart/form-data" > {% csrf_token %} <!-- Text input--> <label class="col-md-4 control-label" for="date">Date</label> <div class="col-md-4"> <input id="date" name="date" type="text" placeholder="" class="form-control input-md" required=""> </div> <!-- Textarea --> <label class="col-md-4 control-label" for="notes">Notes</label> <div class="col-md-4"> <textarea class="form-control" id="notes" name="notes"></textarea> </div> <!-- Multiple Radios (inline) --> <label class="col-md-4 control-label" for="rating">Rating</label> <div class="col-md-4"> <label class="radio-inline" for="rating-0"> <input type="radio" name="rating" id="rating-0" value=1 checked="checked"> 1 </label> <label class="radio-inline" for="rating-1"> <input type="radio" name="rating" id="rating-1" value=2> 2 </label> <label class="radio-inline" for="rating-2"> <input type="radio" name="rating" id="rating-2" value=3> 3 </label> <label class="radio-inline" for="rating-3"> <input type="radio" name="rating" id="rating-3" value=4> 4 </label> <label class="radio-inline" for="rating-4"> <input type="radio" name="rating" id="rating-4" value=5> 5 </label> </div> <label class="form-label" for="image">Upload an image</label> <input type="file" class="form-control" id="image" name="image" /> <!-- Button (Double) --> <label class="col-md-4 control-label" for="Submit"></label> <div class="col-md-8"> <input class="btn btn-success" type="submit" value="Submit" /> <button id="Cancel" name="Cancel" class="btn btn-inverse">Cancel</button> </div> </div> </form> My view @login_required def DrinkBeerConfirm(request): if request.method == 'POST': if request.POST['date']: cellar_id = request.session['cellar'] #Get cellar record ID cellarEntry … -
Heroku deploy failed: Couldn't import Django. Are you sure it's installed?
I am trying to deploy my Python app to Heroku. I am using pipenv. I have defined Pipfile: ... [packages] django = "*" ... I defined Procfile: release: python manage.py migrate web: gunicorn scrapper.wsgi clock: python scrapper/scheduler.py I also added config variable for settings: DJANGO_SETTINGS_MODULE: scrapper.settings When i push my changes to Heroku, deply fails with the following error: File "manage.py", line 17, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
django cripsy form installed failed
My django Version >> 3.1.6 Python version >> 3.8.6 Error >> while installing in virtual env pipenv install django-cripsy-forms Could not find a version that satisfies the requirement django-cripsy-forms ERROR: No matching distribution found for django-cripsy-forms I am new in django please which version of django|python i have to insall -
django get values from datetimefield
class Transaction(models.Model): start = models.DateTimeField(default=timezone.now) I've a model like this. I want to extract date, year from start variable. When I try start.year(), I'm seeing this error Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'DateTimeField' object has no attribute 'year'``` -
How to check if the cookie exist or not and allow the authority to the particular page on the basis of it?
I am creating an authorisation with custom middleware in Django where I save the token in cookie, now I want to check if the cookie is valid or not if it's valid then allow the user to access the page or else should redirect to login page. this is my login method in views.py where I get the token and set it to cookie def loginPage(request): form = AuthenticationForm() if request.method == 'POST': print("login........") username = request.POST.get('username') password = request.POST.get('password') bearerTokenResponse = requests.post( 'http://localhost:8000/auth/login', json={"email": username, "password": password}) print(bearerTokenResponse) code = bearerTokenResponse.json()['code'] # Check if the code is 200 it's successfully get the token if code == 200: token = bearerTokenResponse.json()['token'] print(token) response = HttpResponse("Cookie Set") # Render the home page(patients) response = render(request, 'dashboard.html') # Set the cookie with key name 'core-api' response.set_cookie('core-api', token, max_age=3600) # expire in 1 hour return response return render(request, 'login.html', {'form': form}) # Get the cookie with the key name 'core-api' def getcookie(request): s = request.COOKIES['core-api'] return HttpResponse(s) and the middleware from django.conf import settings class LoginMiddleware: def __init__(self, get_response): #print(get_response) pass def __call__(self, request): #response = self.get_response(request) pass #return response def process_view(self, request, view_func, *view_args, **view_kargs): pass def process_exception(self, request, exception): pass def … -
How to use filters on Foreignkey Fields in Django Rest Framework
In the below class 'dep' is a Foreign Key field associated with Employee model. Views.py class Sample(ListAPIView) queryset=Employee.Objects.all() serializer_class = EmployeeSerializer filter_backends = [SearchFilter] search_fields = ['dep'] Models.py class Employee(models.Model): FirstName=models.CharField(max_length=30) LastName = models.CharField(max_length=30) Salary = models.FloatField() Email = models.CharField(max_length=35) Dep =models.Foreignkey(Department) but when I pass dep has a filter to the endpt , it throws Related Field got invalid lookup: icontains Error. -
How can i serve media and static files in production (aws ec2) of django project which is there on aws s3?
While I am running my project locally it is properly serving the static and media files from AWS s3 but when it is hosted on ec2 through Nginx it is serving the files from local static files? How can I fix the issue? -
'Page not found error' while creating rest-api using django rest framework
I declared the URL pattern correctly, but I get 'Page Not Found error' if I go to the 'localhost:8000/rest' URL. here is the code snippet - from myspace import views from rest_framework import routers from rest_api import views as rest_api_views router = routers.DefaultRouter() router.register(r'post', rest_api_views.GetEntryViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('rest/',include('rest_framework.urls', namespace='rest_framework')), path('', include('myspace.urls')), ] -
Add more classes to my forms' attrs in my Django app
So I have a form in Django and I render in in a HTML file. I have widgets in my form with a class named 'form-control'. What I want is to add more than one class to it, because I want to add the 'is-invalid' class to check the validation and show feedback with colors to the user as I would do in a normal form class in HTML. The problem is that I have tried adding the class but it won't work. My form.py: class WordForm(forms.Form): Word1 = forms.CharField(required = True, label= 'Word1', widget= forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter First Word' })) Word2 = forms.CharField(required = True, label= 'Word2', widget= forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Second Word' })) Word3 = forms.CharField(required = True, label= 'Word3', widget= forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Third Word' })) Result = forms.CharField(label= 'Result', required=False, widget= forms.TextInput(attrs={'class': 'form-control', 'readonly': 'True'})) My form.html <div class="form-group"> <div class="inputs "> <form method="post" class="needs-validation" novalidate> {% csrf_token %} <h2>Inputs</h2> {{ form.as_p }} </form> </div> As you can see, I have the {{form.as_p}} there, so I can't add classes to the inputs normally. How do I do it? Help is much appreciated -
Django and materialized views
I have connected my Postgres ddbb with django. With inspectdb I have brought all my tables to models.py. However, I can't find any command for bringing my materialized views to models.py I have tryed: python manage.py inspectdb --database=name_ddbb --include-views But it only gives me the views, not the materialized views. How can I add automatically the materialized views to django? Thanks! -
Django: Change root url in application
I have a working application/system (Python 3.9, Django 3.1) on my server. Now I need to move it to another server with an alias. From this www.myserver.com to this www.otherserver.com/myapp. In Apache2 config I have line WSGIScriptAlias /myapp /path/to/myapp/wsgi.py. But now I have a problem with all links in app, e.g. link from index page to catalog page redirects to www.otherserver.com/catalog but I need www.otherserver.com/myapp/catalog. Is there any feature in Django? Is it possible to set just some global variable in settings.py? Do I need to edit all the links in the templates? What is the best solution? -
Django advanced searching
I was hoping that somebody could give me advice on what i'm trying to do. I have created a search engine for my application but i would like to take it to the next level. Here's my current query method : def search(self, query=None) : qs = self if query is not None : qs = qs.filter(Q(name__icontains=query) | Q(tags__name__icontains=query)).distinct() return qs I would also like to return objects with similar names. For example, if i have an object named "Children" and the query is "Child", the search won't return my object. Is there to compare the number of similar charcaters. I hope that you understand my question, considering how terrible my english is. Thanks for your help -
Django how to get one result using slicing queryset
I have to fetch the usernames of my authors' posts Here the views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.forms import inlineformset_factory from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.utils import timezone from .forms import CreateUserForm from .models import Post from .forms import PostForm def counter(request): authors = Post.objects.values_list('author', 'title') authors_id = Post.objects.values_list('author') authors_name = User.objects.get(id=authors_id) context = {'authors':authors, 'authors_name':authors_name} return render(request, 'account/counter.html', {'authors': authors}) My models.py is: from django.db import models from django.conf import settings from django.utils import timezone # Create your models here. class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title And here my forms.py: from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from .models import Post class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2','user_permissions','is_staff','date_joined'] class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'text', 'author'] Now the problem is that on 'authors_id' I have this Error: The QuerySet value for an exact lookup must be limited to one result using … -
is there anyway i can replace the number by input in the code to variable in django?
I am writing the code like this for now. But what i want is to replace the 0.00024 to variable. {{'Total (USD)'}} {{order.initial_total | times: 0.00024 | integer}}$ -
how to transfer context from a view to another or even make it global
I would like to use profile_form.instance.class_key in other views or make it a global variable.THe profile_form.instance.class_key variable only works on the register view('home.html' template).How can I make it work in other templates too? views.py def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data = request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile_form.instance.class_key = request.user.class_key profile = profile_form.save(commit=False) profile.user = user profile.save() registered = True return redirect('/login/') else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'home.html', {'user_form': user_form, 'profile_form':profile_form, 'registered' : registered}) I defined the forms and the models. forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) repeat_password = forms.CharField(widget=forms.PasswordInput()) def clean_username(self): username = self.cleaned_data['username'] if User.objects.filter(username=username).exists(): raise forms.ValidationError("username already exists") return username def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise forms.ValidationError("Email already exists") return email def clean(self): data = self.cleaned_data password = self.cleaned_data.get('password') repeat_password = self.cleaned_data.get('repeat_password') if repeat_password != password: raise forms.ValidationError("Passwords don't match") class Meta(): model = User fields = ('username', 'email', 'password','repeat_password') class UserProfileInfoForm(forms.ModelForm): DEMO_CHOICES = ( ('empty', 'empty'), ('11A', '11A'), ('11B', '11B'), ) security_key = forms.CharField(max_length=6) class_key = forms.ChoiceField(choices=DEMO_CHOICES,required=True) def clean(self): security_key = self.cleaned_data.get('security_key') class_key = self.cleaned_data.get('class_key') if security_key == 'a45id8' and class_key == '11A' : … -
How is postgis treating coordinates sent with different SRID
I am running a django application and I am using the PostGis extension for my db. I am trying to understand better what happens under the hood when I send coordinates, especially because I am working with different coordinate systems which translate to different SRIDs. My question is threefold: Is django/postgis handling the transformation when creating a Point or Polygon in the DB. Can I query it back using a different SRID Is it advisable to use the default SRID=4326 Let's say I have a model like this (note I am setting the standard SRID=4326): class MyModel(models.Model): name = models.CharField( max_length=120, ) point = models.PointField( srid=4326, ) polygon = models.PolygonField( srid=4326, ) Now I am sending different coordinates and polygons with different SRIDS. I am reading here in the django docs that: Moreover, if the GEOSGeometry is in a different coordinate system (has a different SRID value) than that of the field, then it will be implicitly transformed into the SRID of the model’s field, using the spatial database’s transform procedure So if I understand this correctly, this mean that when I am sending an API request like this: data = { "name": "name" "point": "SRID=2345;POLYGON ((12.223242267 280.123144553))" "polygon": "SRID=5432;POLYGON … -
Wow Slider is not showing data from database as a slider
I am creating an E-Commerce site using Django and Django Rest API. In front end I am using an E-commerce template created using Bootstrap 3 framework. There is a Wow Slider Version 2 in the website, where product is showing from database using ajax. When I use plain HTML the slider is showing product horizontally in a row but when I use product from database all the product is showing vertically, one after another not as a row. My code : <div class="block-top-categori"> <div class="title-of-section">Hot Categories</div> <div id="HotCategoriesList" class="owl-carousel nav-style2" data-nav="true" data-autoplay="false" data-dots="true" data-loop="true" data-margin="20" data- responsive='{"0":{"items":1},"480":{"items":2},"640":{"items":3},"768": {"items":2},"992":{"items":4}}'> </div> </div> <script> var xhttp2 = new XMLHttpRequest(); xhttp2.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var AllHotCategoriesList = JSON.parse(this.responseText); var HotCategoriesList = document.getElementById("HotCategoriesList"); var AllHotCategoriesListLength = (AllHotCategoriesList.length); for (i = 0; i < 6; i++) { HotCategoriesList.innerHTML += `<div class="block-top-categori-item"> <a href=""><img src="{% static 'images/home5/h3.jpg' %}" alt="h3"></a> <div class="block-top-categori-title">Shoes Sport</div> </div>` } } }; xhttp2.open("GET", "{% url 'ListAddCategory' %}", true); xhttp2.setRequestHeader("content-Type", "application/json"); xhttp2.send(); </script> -
ModuleNotFoundError: No module named MY_APP problems with django web deployed with Heroku
I deployed my Django web site with Heroku but there's an application error. I can run this in local server with "heroku local" also in virtual env with "python manage.py runserver" and the site has been deployed. I've made requirements.txt , runtime.txt and Pacfile too. I see error messages when I command 'heroku logs --tail' 2021-02-16T20:26:35.823862+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-02-16T20:26:35.823862+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-02-16T20:26:35.823863+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked 2021-02-16T20:26:35.823863+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2021-02-16T20:26:35.823863+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-02-16T20:26:35.823864+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-02-16T20:26:35.823864+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked 2021-02-16T20:26:35.823864+00:00 app[web.1]: ModuleNotFoundError: No module named 'portfolio' 2021-02-16T20:26:35.824001+00:00 app[web.1]: [2021-02-16 20:26:35 +0000] [8] [INFO] Worker exiting (pid: 8) 2021-02-16T20:26:35.856818+00:00 app[web.1]: [2021-02-16 20:26:35 +0000] [4] [INFO] Shutting down: Master 2021-02-16T20:26:35.856905+00:00 app[web.1]: [2021-02-16 20:26:35 +0000] [4] [INFO] Reason: Worker failed to boot. 2021-02-16T20:26:35.918015+00:00 heroku[web.1]: Process exited with status 3 2021-02-16T20:26:35.980096+00:00 heroku[web.1]: State changed from starting to crashed 2021-02-16T20:26:36.601488+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=poianakim.herokuapp.com request_id=93a834d5-7212-499d-9f98-f02936bc7459 fwd="95.239.217.192" dyno= connect= service= status=503 bytes= protocol=https 2021-02-16T20:26:37.057729+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=poianakim.herokuapp.com request_id=34840aae-ab2d-49d5-8143-df2f0d30d8bf … -
A large number of problems with react, django, django rest and axios
I am going through a very good course about setting up an e-shop, but I have reached the stage, where I am not that much sure, what is the exact purpose of the code, which I have written. (especially the async function in HomeScreen.js) We are using React and Django. My issue is related to the homepage or HomeScreen.js file, which was working fine, when I was loading the products from the static products.json file, but later on in the course, we had to switch this and load the products from an api using django-rest and axios and my problem now is, that I am not able to load the products to the HomeScreen.js and all I see is a blank page with the header instead of a full page. I am running the react server through the npm start command, but also tried to run the django server, It gives me this error - OSError: [WinError 123]. Please let me know, if You can see some solution these problems. Thank You very much for any help in advance. The page looks like this - And it should look like this - When I am looking to my console, I … -
Django serializer won't save to database
im making small rest api that takes ip address then sends it to ipstack and saves returned data do database. The problem is my data is not saving when calling serializer.save. I'm sure that this is some small issue but i spend soo much time looking at this code that i don't see anything Don't mind if the data from ip isn't correct here I've changed it let's start with the models.py class Location(models.Model): ip = models.CharField(max_length=15) type = models.CharField(max_length=6) latitude = models.DecimalField(max_digits=10, decimal_places=8) longitude = models.DecimalField(max_digits=10,decimal_places=0) continent_code = models.CharField(max_length=2) continent_name = models.CharField(max_length=20) country_code = models.CharField(max_length=10) country_name = models.CharField(max_length=70) region_code = models.CharField(max_length=10) region_name = models.CharField(max_length=50) city = models.CharField(max_length=100) zip = models.CharField(max_length=10) def __str__(self): return str(self.ip) serializer from rest_framework import serializers from .models import * class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location exclude = ['id'] vievws ip = '89.64.124.126' if ip: try: data = location_search.get_location(ip) if data is None: return Response(status=status.HTTP_400_BAD_REQUEST,) except: return Response("Our services are temporarily unavailable", status=503,) serializer = self.serializer_class(data=data) print(serializer) print(serializer.is_valid()) if serializer.is_valid(): serializer.save() return Response("Data was successfully added", status=status.HTTP_201_CREATED,) else: return Response("Database error occurred, try again later",status=status.HTTP_500_INTERNAL_SERVER_ERROR,) this is what i get when printing LocationSerializer(data={'ip': '89.64.124.126', 'type': 'ipv4', 'continent_code': 'EU', 'continent_name': 'Europe', 'country_code': 'PL', 'country_name': 'Poland', 'region_code': … -
Building a Dashboard App with Django Rest framework
I'm trying to create a charts dashboard with Django REST framework in the backend and Reactjs in the front end. This would be my second django project. I'm connected to my Postgres database table and can produce it whole in JSON using APIview. I've explored Django-rest, but the demos and examples doesn't show how to consume postgres data and return prepared data using RESTful APIs. How do I edit my views.py file to write SQL queries within my Django project? I want to have 4 different dash app instances linking different url paths. Below is an example of how dash renders tinyurl.com/195nnyts from rest_framework.response import Response from rest_framework.views import APIView from .models import superstore from .serializers import storeSerializer class storeList(APIView): def get(self, request): item = superstore.objects.all()[:100] serializer = storeSerializer(item, many=True) return Response(serializer.data)