Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve Key Error Exception when accessing dictionary key inside an if statement
I'm currently developing EV calculator using python and django. I get a key error exception when trying to access a dictionary key in an if statement inside a function. To break it down, my calculator function does the following, prompts the user for four input values, wager_amount, odd1, odd2 and odd_to_bet/back_odd, based on values user has entered, the function will output expected value or ev in jinja html. Something to note is, odd_to_bet/back_odd must either be equal to odd1 or odd2, if odd_to_bet/back_odd is either not equal to odd1 or odd2, the function has an else block with a message to tell the user to Please, check the odds again for any typo error!. An example: lets say the user inputs the following values from html form wager_amount = 10 odd1 = 1.54 odd2 = 2.47 odd_to_bet/back_odd = 1.54 This works fine, i'm able to display output without issues the key error exception arises when the user inputs and submits odd_to_bet/back_odd a value not either equal to odd1 or odd2. wager_amount = 10 odd1 = 1.54 odd2 = 2.47 odd_to_bet/back_odd = 1.52 My expected output should be "Please, check the odds again for any typo error!." displayed in the html. … -
User draw rectangle on leaflet map and post the coordinates on django form
I would like to create a djagno app, which will enable users to draw a rectangle on a leafet map and post the coordinates in order to create a vector. Firtsly I have created the form.py file: from django import forms class CoordinatesForm(forms.Form): lat_max = forms.FloatField() lat_min = forms.FloatField() lon_max = forms.FloatField() lon_min = forms.FloatField() I set the post method in the views,py file: if request.method == 'POST': form = CoordinatesForm(request.POST) and I have created a leaflet map: <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <script type="text/javascript"> function map_init(map, options) { var drawnItems = new L.FeatureGroup(); map.addLayer(drawnItems); var drawControl = new L.Control.Draw({ edit: { featureGroup: drawnItems, }, draw: { circle: false, circlemarker: false, polygon: false, marker: false, polyline: false, } }); map.addControl(drawControl); } </script> {% leaflet_map "yourmap2" callback="window.map_init"%} <button type="submit">Submit</button> </form> Is there any way to submit the coordinates on click the button? -
URL and page refresh issue for Multilingual site on Django
plz help me to solve one issue. I have a Multilingual site on Django with standart internationalization framework. Settings.py MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware' ...] LANGUAGES = ( ('en', _('English')), ('ja', _('Japanese')), ) LANGUAGE_CODE = 'en' USE_I18N = True USE_L10N = True LOCALE_PATHS = ['../locale/'] All *.mo and *.po files for both languages are successfully created. main.html has a code snippet for language switching: {% get_current_language as CURRENT_LANGUAGE %} {% get_available_languages as AVAILABLE_LANGUAGES %} {% get_language_info_list for AVAILABLE_LANGUAGES as languages %} <div class="languages"> <p>{% trans "Language" %}:</p> <ul class="languages"> {% for language in languages %} <li> <a href="/{{ language.code }}/" {% if language.code == CURRENT_LANGUAGE %} class="active"{% endif %}> {{ language.name_local }} </a> </li> {% endfor %} </ul> </div> url.py urlpatterns = i18n_patterns( path('', include('mysite.urls')) ) simplified website structure main.html --page1.html --page2.html Now I can click and change the page translation, but I've faced with next issue. When I switch the language, e.g. from main/en/page1 I redirected back to the main/ja page, regardless my current location on a website structure. In other words, I'd like to stay at the same page1 when I switch the language and change only the language prefix main/en/page1 -> main/ja/page1. The best working example … -
How to change the database local to be in a cloud (Django)
I wrote a project in django framework and I use the local DataBase SQLite, and I now want to upload it to the cloud so other people who work with me can access DataBase i.e. when I create a user then that user will exist with my co-workers. Maybe someone has a guide on how to do this without modifying the DataBase so that I do not have to modify the rest of the code? -
HTML name/value button attribute not being sent via POST request to server
I am currently using HTMX and Django to process button clicks within a table that adds the selected item to a list. I have the following form code: <form action="" method="post"> {% csrf_token %} <button hx-post="{% url 'add-analysis' %}" hx-target="#analysis-list" type="submit" name="projectChoice" value="{{project.project_title}}">Add</button> </form> in my Views.py I am trying to parse the data with the following code: print(proj_name = request.POST.get("projectChoice")) This returns None however. To debug this I tried listing all of the POST requests to the server with the following: print(list(request.POST.items())) However this only returns the CSRF token, what am I doing wrong here? -
It shows, Field 'id' expected a number but got ''
When I submit then shows this error. views.py: class userINFOupdate(View): def get(self,request): userid = request.GET.get("user_up_id") username = request.GET.get('user_up_username') email = request.GET.get('user_up_email') phone = request.GET.get('user_up_phoneNumber') address = request.GET.get('user_up_address') obj = AJAXCRUD.objects.get(id=userid) print(userid) template: <input type="text" hidden name="user_up_id" id="user_hid_id" class="user_hidden_id"> -
Queryset filter to filter response that exactly contains the value as substring in django views
I have created filters that filter API responses, if the response contains at least one letter in the value as substring, I need to create a filter to filter responses that exactly contain the value as a substring in Django views. **Existing code in views.py** class UserSearchFilterAPIView(APIView): def get(self,request,*args,**kargs): queryset=Joineduserdatanew.objects.all() #Custom filter surname=self.request.query_params.get('surname',None) firstname=self.request.query_params.get('firstname',None) login=self.request.query_params.get('login',None) racfid=self.request.query_params.get('racfid',None) assignee=self.request.query_params.get('assignee',None) phonenumber=self.request.query_params.get('phonenumber',None) company_or_group=self.request.query_params.get('company_or_group',None) email=self.request.query_params.get('email',None) segment=self.request.query_params.get('segment',None) if surname: queryset=queryset.filter(surname__icontains=surname) if firstname: queryset=queryset.filter(firstname__icontains=firstname) if login: queryset=queryset.filter(login__icontains=login) if racfid: queryset=queryset.filter(racfid__icontains=racfid) if assignee: queryset=queryset.filter(assignee__icontains=assignee) if phonenumber: queryset=queryset.filter(phonenumber__icontains=phonenumber) if company_or_group: queryset=queryset.filter(company_or_group__icontains=company_or_group) if email: queryset=queryset.filter(email__icontains=email) if segment: queryset=queryset.filter(segment__icontains=segment) serializer=JoineduserdatanewSerialization(queryset,many=True) return Response(serializer.data) Example: if company_or_group is given as : "aaa" ,it returns results containing at least one 'a' but I need to filter that the company_or_group in the API response exactly containing "aaa" as a substring in that company_or_group field. -
Improperly configured error says I'll have to define env variable DJANGO_SETTINGS_Module .Please help me solving this problem
So I m just a newbie trying to learn django .. i was just trying to copy what Harry did(a youtuber who teaches code) but I got stuck right after creating the project file, the url.py file of my project keep showing me the error (django.core.exception. improperly configured request settings INSTALLED APP but settings are not config. You must either define the DJANGO_SETTINGS_MODULE or call setting config() before accessing settings.)I tried doing everything I could with the help of Google and YouTube but still not able to solve it . Can someone help me with this And it's on a mobile ide named pydroid 3. BELOW IS THE ERROR I M GETTING -
How to display extra context and form fields at the same time on django template using class based view?
I am trying to display some extra context on the page, but when I adding get_context_data method it is displayed context but not a forms fields. This is because when I click ulr that triggers view below there is get method by default or prior to forms fields? I don't understand why forms disappear when this method present in SolutionCreate view, indeed all context data displayed template {% extends "base.html" %} {% block content %} <div class="container"> <div class="row"> <div class="col-sm"> <form action="" method="POST"> <table> {% csrf_token %} {{ form.as_p }} </table> <input type="submit" class="btn btn-primary" value="Submit"> </form> </div> <div class="col-sm"> {{ context }} <h5>Problem:</h5> {% for pr in prb %} <h5>Problem: {{ pr.title }}</h5> <h6>Description</h6> <li class="list-group-item">{{ pr.description }}</li> <p> </p> <h6>Risks</h6> <li class="list-group-item">{{ pr.risks }}</li> <p> </p> <h6>Parts</h6> <li class="list-group-item">{{ pr.parts }}</li> <p> </p> <h6>Causes</h6> <li class="list-group-item">{{ pr.causes }}</li> <p> </p> <h6>Published</h6> <li class="list-group-item">{{ pr.published }}</li> <p> </p> <a href="{% url 'delete_problem' pr.pk %}" class="btn btn-warning" role="button" aria-pressed="true">Delete</a> <a href="{% url 'update_problem' pr.pk %}" class="btn btn-warning" role="button" aria-pressed="true">Update</a> <p> </p> {% endfor %} </div> </div> </div> {% endblock content %} view class SolutionCreate(CreateView): model = Solution template_name = 'analysis/create_solution.html' fields = [ 'problem', 'research', 'solutions', 'resources', 'plan', 'test' … -
Multiple Git push in one command
I've an application that requires to run git add/commit/push on each single file i'd like to push, in order to trigger a Gitlab Job on each. My problem is that git is actually taking many time to do the git push command. Here are the commands i'm using: git add myFile.json git commit myFile.json -m "commitMessage" variable1 = git rev-parse HEAD # Storing last commit hash into a variable # Pushing only one specific commit to (maybe) make it faster git push $variable1:master What i'd like to do is to make the whole process "faster". What i've thought about: Doing multiple pipeline triggers using only one git push (maybe by running the pipeline on each commit instead of each push), but it doesn't seem possible. Doing multiple pushes in one git push command, so it doesn't have to reload some of the git push init operations before each file pushed (i have no idea on what is happenning during the git push process, so that idea may be wrong) Does anyone has an idea on how to make this process faster, by using one of my ideas, or even a brand new one from you ! Thanks in advance ! -
How do i use Data from other model inside forms that is made with other model in django?
right now my template looks like this I wish to use those cards as the choices in the form that is on the right side. i am a newbie so i cant figure out how. is this possible so i could render the data from plans model in the forms that is built using my orders model. in the orders model i have used plans as a foreign key Forms.py class BuyPlanForm(forms.ModelForm): error_css_class = 'error-field' required_css_class = 'required-field' pack = forms.ModelChoiceField(Plans.objects.all(), widget=forms.RadioSelect()) class Meta(): model = Orders fields = ['pack'] my Views.py class UserBuyPlan(LoginRequiredMixin, View): template = 'plans/plan.html' success_url = reverse_lazy('home-home') def get(self, request): plans = Plans.objects.all() form = BuyPlanForm() ctx = { 'form': form, 'plans': plans, } return render(request, self.template, ctx) def post(self, request): form = BuyPlanForm(request.POST) form.instance.user = self.request.user if not form.is_valid(): ctx = {'form': form} return render(request, self.template, ctx) make = form.save() return redirect(self.success_url) my models.py class Plans(models.Model): plan_name = models.CharField(max_length=50) speed = models.IntegerField() price = models.FloatField() def __str__(self): return self.plan_name def get_deadline(): return dt.today() + timedelta(days=30) class Orders(models.Model): user = models.ForeignKey(CustomUser, primary_key=True, on_delete = models.CASCADE) pack = models.ForeignKey(Plans, on_delete = models.CASCADE) start_date = models.DateField(auto_now_add=True) end_date = models.DateField(default=get_deadline()) is_active = models.BooleanField(default=True) def __str__(self): name = str(self.user.username) return … -
Django static loaded but not used
Nginx web server serves static. Browser downloads static files but they don’t work. Why would that be? Loaded static files docker-compose volumes: django_static: services: nginx: build: context: . dockerfile: ./_nginx/Dockerfile container_name: webserver restart: unless-stopped volumes: - django_static:/app/staticfiles ports: - "80:80" - "443:443" depends_on: - backend backend: build: context: . depends_on: - postgres command: /gunicorn.sh entrypoint: /entrypoint.sh restart: always env_file: .env volumes: - django_static:/app/staticfiles ports: - "${CUSTOM_PORT}:8000" staticfiles config STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] -
How to allow .svg formated file in Wagtail images
I want to upload svg files in Wagtail images. Is it posible to do so. I used "wagtailsvg" but it generate extra table in database not the same image table. So simply I need to allow .svg formated file in images. Any siggestions? -
Problems with Django URL routing
I'm building a website, to be used in dental practices, however I'm having trouble with the URL routing. I'm wanting af URL pattern like: Denthelp/kartotek/#nameofclinic#/opretpatient. My suggestion looks like this: urls.py: path('kartotek/<str:kl_id>/', views.kartotek, name="kartotek"), path('kartotek/<str:kl_id>/opretpatient/', views.opretpatient, name="opret_patient"), Views. py: def kartotek(request, kl_id): kliniknavn = Klinik.objects.get(navn=kl_id) E_patient = kliniknavn.patient_set.all() context = { 'kliniknavn':kliniknavn, 'E_patient':E_patient} return render(request,'DentHelp/kartotek.html', context ) def opretpatient(request, kl_id): kliniknavn = Klinik.objects.get(navn=kl_id) form = PatientForm() if request.method == 'POST': form = PatientForm(request.POST) if form.is_valid(): form.save() return redirect('kartotek/<str:kl_id>/') context = {'form':form, 'kliniknavn':kliniknavn} return render(request,'DentHelp/kartotek/<str:kl_id>/opretpatient.html', context) When running code I get an OSError for the last line of code shown here. Have you guys have any advise for this to work? -
POST HTML FORM verificaton doesn't work with Django
I am currently learning Django,I connected my register FORM with my views.py, and wrote a little backend code, the problem, is that it links successfully with my .html file, and the POST elements are registering, but as I try to make a verification, (if POST_element < 10), it does nothing. Here is a part of my HTML Register FORM: <div class="limiter"> <div class="container-login100" style="background:black;"> <div class="wrap-login100"> <form action="{% url 'register' %}" method="POST" class="login100-form validate-form"> {% csrf_token %} <span class="login100-form-logo"> <i class="zmdi zmdi-landscape"></i> </span> <span class="login100-form-title p-b-34 p-t-27"> Register </span> <div class="wrap-input100 validate-input" data-validate = "Enter username"> <input class="input100" type="text" name="username" placeholder="Username"> <span class="focus-input100" data-placeholder="&#xf207;"></span> </div> Here is a part of my views.py that manages register: def register(request): if request.method=="POST": username = request.POST["username"] password = request.POST["pass"] password_confirm = request.POST["pass-confirm"] email = request.POST["mail"] if len(username) < 7: messages.error(request,"Username must be more than 10 char.") #Don't get any error else: messages.success(request,"Success") return render(request, 'users/register.html') Here is my urls.py: urlpatterns = [ path('', views.register, name='register'), path('login/', views.login, name='login') ] Thanks for your help! -
How to get data from Django Rest Framework to GoogleMaps in JS
I am trying to build web app which should get data from Django Rest Framework (using Serializer) and pass it to JavaScript and generate markers of GoogleMaps. When I fetched the data from Django API then JS return me 'Promise'. To create markers on GoogleMaps I need GeoJson object. Please for advice where is my mistake. Django serializer: class LocationList(generics.ListAPIView): model = Homes queryset = Homes.objects.all() serializer_class = LocationSerializer API url: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "type": "FeatureCollection", "features": [ { "id": 7, "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 19.2800748, 50.2004355 ] }, "properties": { "property_type": 1, "name": "Zagłoby", "surface": 140.0, "price": 5600000.0, "home_number": "11", "street": "Zagłoby", "post_code": "43-600", "city": "Jaworzno", "country": "Polska", "lat_maps": 50.2004355, "lng_maps": 19.2800748, "add_date": "2022-04-17T15:05:18.274352Z", "active": 2 } }, My JS code: var endpoint = 'api/location' async function getLocalization() { try { const response = await fetch(endpoint); return await response.json(); } catch (error) { console.log(error); } } async function renderLocalization() { let address = await getLocalization(); return address }; function initMap() { // The location of Uluru const uluru = { lat: -25.344, lng: 131.031 }; // The map, centered at Uluru const map = new google.maps.Map(document.getElementById("map"), … -
Getting a Bad Request when making a POST request in djangorestframework
I'm getting the following error when I try to make a POST request to the server; "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" The request is successful when I POST null content or input in a dictionary, i.e {"content": "Hello world"}. Any kind of help in trying to debug this issue will be greatly appreciated My views.py @api_view(['POST']) @permission_classes([IsAuthenticated]) def tweet_create_view(request, *args, **kwargs): serializer = TweetCreateSerializer(content=request.data) if serializer.is_valid(raise_exception=True): serializer.save(user=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My serializers.py class TweetCreateSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField(read_only=True) class Meta: model = Tweet fields = ['id', 'content', 'likes',] def get_likes(self, obj): return obj.likes.count() def validate_content(self, value): if len(value) > MAX_TWEET_LENGTH: raise serializers.ValidationError("This tweet is too long") return value -
Django query annotate after filter doesn't work correctly
I have two models that are related using a m2m relationship through an intermediate model. The relation field is called participants. When I do this: chats = Chat.objects.annotate(Count("participants")).filter(participants=user) chats.get(pk=11).participants__count It will return 2; which is correct. But when I do this: chats = Chat.objects.filter(participants=user).annotate(Count("participants")) chats.get(pk=11).participants__count It will return 1. And not only for this object for all of the objects in the queryset. What's wrong? what am I doing wrong? I need to annotate a filtered queryset. -
How does "alternates" in the Django site framework work?
I am struggling to get the "alternates" attribute to work in the Django sitemap framework. class StaticViewSitemap(sitemaps.Sitemap): priority = 0.5 changefreq = 'daily' i18n = True alternates = True def items(self): return ['index', 'about'] def location(self, item): return reverse(item) The documentation appears to suggest the above i.e. setting i18n and alternates to True. But when I do that, my sitemap is literally a plain test string like this: http://127.0.0.1:8000/en/daily0.5http://127.0.0.1:8000/en/about/daily0.5http://127.0.0.1:8000/es/daily0.5http://127.0.0.1:8000/es/about/daily0.5 Whereas it should look like so: <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>http://127.0.0.1:8000/</loc> <changefreq>daily</changefreq> <priority>0.5</priority> </url> <url> <loc>http://127.0.0.1:8000/about/</loc> <changefreq>daily</changefreq> <priority>0.5</priority> </url> </urlset> There are two issues: It doesn't have the correct formatting. What am I doing wrong here? I don't want the 'en' language prefix for the default language. How do I remove this? -
Submit form post from another view with input field
I am relatively new to Django and I'm making a small "social" project. It basically consists of user profiles, and on those profiles you can post "comments". I have a view that displays the comments each user has, and a separate view that allows you to post comments. This works as expected. The problem I am facing right now is the following. - I have an < input type=text > field in the view to view comments, and I want to be able to post a comment from there and have it saved in the database. I have tried grabbing the post kwargs in the form, but I couldn't get it to work correctly nonetheless have it save automatically. How can I get this done? Here is the code that I have so far. Comments view: class CommentsView(auth_mixins.LoginRequiredMixin, views.ListView): model = ProfileComments template_name = 'comments/comments_view.html' paginate_by = 5 def get_queryset(self): receiver = PROFILE_MODEL.objects.get(pk=self.kwargs['pk']) if receiver: return self.model.objects.filter(receiver=receiver) return None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) receiver = PROFILE_MODEL.objects.get(pk=self.kwargs['pk']) if receiver: context.update({ 'receiver': receiver }) return context View to post comments: class CreateCommentView(auth_mixins.LoginRequiredMixin, views.CreateView): form_class = CommentsForm template_name = 'comments/post_comment.html' @staticmethod def get_profile_model_by_pk(pk): return PROFILE_MODEL.objects.get(pk=pk) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['author'] … -
how to display notification before two days from start date and display notfication on end date using django?
from django.shortcuts import render from app.models import maintenance def notification(request): time_obj = maintenance.time_obj before_two_days = time_obj - datetime.timedelta(days=2) today = datetime.date.today() print('before_two_days',before_two_days) print('today',today) if before_two_days > today: msg = maintenance(start_date=maintenance.start_date,msg = f"Your site will be under construction on {before_two_days}",is_seen=False) msg.save() else: msg = maintenance(end_date=maintenance.end_date,msg = f"Your site will be reopen on {maintenance.end_date}",is_seen=False) msg.save() return render(request,'site.html') -
Can any one help me with import-export-django problem in django
Model.py class Order(models.Model): customerID = models.CharField(max_length=300, blank=True, null=True) osm_bol = models.CharField(max_length=300, blank=True, null=True) ..... ..... def __str__(self): return self.customerID Resouces.py class NewOrders(resources.ModelResource): osm_bol = Field(attribute='osm_bol', column_name='Client Track ID') class Meta: model = Order fields = ('osm_bol') Exel Sheet Column This is the Column that i want to import in my model Problem the problem is i have the column name "Client Track ID" but in my model the name of attribute is "osm_bol" for the same field. when i import the file it shows nothing in "osm_bol" field. i mean its shows empty field. how can i fix it? -
Django template language how to fix
Hi I'm trying to build a simple django app but I can't get index.html file to recognise the variables created in views.py. Nothing I do seems to work. Does it have to be configured somehow in settings.py perhaps? index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p>Hello world {{ name }}</p> </body> </html> views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): context = {'name' : 'Peter'} return render(request, 'index.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] Whatever I try, the browser just doesn't recognise anything in the {{}}. It just leaves it blank. I seem to have tried everything. Please help, I'm tearing my hair out. Thanks -
How to get notification when new Article is added to Website?
I have multiple blogging websites made in WordPress. I want to make a website, by which when I add some article on any of these websites, I have to get a notification on website that a new article is added to a particular website. How can I make such a website in Django? -
Can I write posts for a personal Django blog website in static html files?
I'm pretty new to Django and have been experimenting making my own personal blog. General question I get that I can specify my blog post structure in models.py and use the admin site to write my blogs. However, what if I want to write my blogs in raw HTML files stored in, e.g. my-website/blog/posts/<list-of-html-blogs> and then have those files uploaded into the data base and shown on the website. Is there are a standard way of doing this? My initial approach is to create a Python function that reads in the HTML files as strings and uploads those files into the database manually, i.e. using something like blog.models.Post(title=my_title, content=html_as_string). Whenever I'd write a new blog, I'd then call this function to upload a specific html file. However, I have found very little online about whether this is the correct approach. Django blog overview If helpful, I'm showing below what my blog's models.py and views.py currently looks like. models.py from django.db import models STATUS = ( (0, "draft"), (1, "published") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True, null=True) date = models.DateTimeField() content = models.TextField(blank=True) status = models.IntegerField(choices=STATUS, default=0) class Meta(object): ordering = ["-date"] def __str__(self): return self.title …