Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django pymongo search bar error need guidance / tutorial
i m new to all this, still learning, i have been successfully able to display table view in django from mongodb. Now another task for me is to create search bar using mongodb What i have done so far created the mongodb_connection.py to establish connection using pymongo from pymongo import MongoClient def mongosearch(title=""): connection = MongoClient('localhost',27017) db = connection.djangodb collection = db.spiderCollection title = collection.find() for title in titles: pprint.pprint() created view and importing method from mongodb_connection as follows: from django.shortcuts import render from .mongodb_connection import mongosearch # Create your views here. def search_index(request): results = [] title_term = "" search_term = title_term if request.GET.get('title'): title_term = request.GET.get('title') search_term = title_term results = mongosearch(title=title_term) print(results) context={ 'results':results, 'count':len(results), 'search_term':search_term } return render(request, 'search.html', context) then modified the urls from django.urls import path, include from . import views from django.conf.urls import url app_name = 'searchapp' urlpatterns=[ path('',views.search_index, name='search_view'), ] created html page under apps/templates <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!--{% load staticfiles %} --> <!doctype html> <html> <nav class="navbar navbar-light bg-light"> <form class="form-inline" action="{% url 'searchapp:search_results' %}" method="get"> <input class="form-control mr-sm-2" type="search" placeholder="Title" aria-label="Title" name = 'title' value = ""> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </nav> <!-- <form action="{% … -
How to save multiple records with different foreign key and values django?
I would like to echo students to enter each students marks against the students something like how the form should look like. my model.py class Mark(models.Model): date_created = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete = models.SET_NULL, blank=True, null=True,) child = models.ForeignKey(Student, on_delete = models.CASCADE,) subject = models.ForeignKey(Subject, on_delete = models.CASCADE,) marks_class = models.ForeignKey(Classe, on_delete = models.CASCADE,) stream = models.ForeignKey(Stream, on_delete = models.CASCADE,) term = models.ForeignKey(Term, on_delete = models.CASCADE,) exam_set = models.ForeignKey(ExamSet, on_delete = models.CASCADE,) year = models.IntegerField(default=current_year, validators=[MinValueValidator(2020), max_value_current_year]) marks = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) I selected the students for entering marks like this students = ClassInformation.objects.filter(year_of_registration=year, current_class=marks_class, stream=stream).order_by('child') I assigned other values like The values are first selected if form.is_valid(): form.instance.subject = subject form.instance.marks_class = marks_class form.instance.stream = stream form.instance.year = year form.instance.term = term form.save() return redirect('choose-subject') now the challenge is assigning the student and the marks to the form for all the students selected I followed something from here but the answer seem not there yet. How to assign a value to a django form field in the template? -
Django passing 2 parameter from HTML template to views function
I want to pass 2 parameters to my view function, in order to delete specific record from table. There is M2M connection on which i want to work so I have to pass 2 parameters for 2 different objects. Model: class Products(models.Model): name = models.CharField(max_length=50) price = models.DecimalField(max_digits=100, decimal_places=2, blank=True) class Meals(models.Model): name = models.CharField(max_length=40) ingredient = models.ManyToManyField(Products, related_name="products") views: def remove_ingredient(request, pk, name): meal = Meals.objects.get(pk=pk) prod = Products.objects.get(name=name) meal.ingredient.remove(prod) return HttpResponse(status=204) url patterns: urlpatterns = [ path("meal_detail/<int:pk>/",MealDetailView.as_view(), name="meal_detail" ), path("meal_detail/<int:pk>/", remove_ingredient, name="remove_ingredient") ] HTML template: <a class="hyperlink-off" href="{% url 'remove_ingredient' pk=object.pk name=ingredient.name %}"> Remove </a> As you can see I want to pass 2 arguments from HTML templateto my function (primary key of Meal and name of product which i want to remove from Meals.ingredient). But in the same time URL pattern is receiving 2 arguments and its trying to generate link to website based on both of them when it needs just one. I tried even to force function to stay at the same page by passing HttpResponse(status=204). How can i exclude one of arguments passed from HTML to urls.py or is there any other way to pass variables to views function from html tempalte? -
How to set up the Django tag for django-google-analytics-app?
SUMMARY I am installing django-google-analytics-app following the instructions in this link https://pypi.org/project/django-google-analytics-app/ . For the pages I am interested in doing the tracking I am including analytics.html in their templates in the body section as essentially shown below: <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> {% include "analytics.html" %} </body> </html> where analytics.html only has the lines instructed in the link: {% load google_analytics_tags %} <div style="display:none"> <img src="{% google_analytics %}" width="0" height="0" /> </div> THE PROBLEM This is disturbing the styling of my pages. THE QUESTION How am I meant to include the tracking in the templates/pages I want to do so? -
Django custom model manager
If we have model like class SomeModel(models.Model): field_1 = models.IntegerField() field_2 = models.IntegerField() and in every query for a given value if we have to check against both the fields, is it possible to simplify the redundancy (field_1=value, field_2=value) using a custom Manager ? SomeModel.objects.filter(field_1=value, field_2=value) SomeModel.objects.filter(field_1=value, field_2=value).count() -
How to create an Django ordered list
I have the following model: class Instrument(MPTTModel): name = models.CharField(max_length=100, null=True, blank=True) category = models.CharField(max_length=100, null=True, blank=True) The table looks like this: name | category | --------------------- violin | string | viola | string | flute | woodwind | oboe | woodwind | trumpet| brass | I would like to output in my template an ordered list like: String: Violin Viola Woodwind: flute oboe Brass: trumpet Is there an easy way to display this once I have query the Instrument object? -
How to keep track of users who are not logged in Django?
I am writing a simple e-commerce web app with Django. I want Anonymous Users (unregistered guests) to still be able to add items to their cart and proceed to checkout without having to register or log in. I am having trouble figuring out how to actually keep track of them (according to best practices/with security in mind), if these types of users don't have an identifiable username/id that Django provides. Concretely, suppose I have these models: class Shirt(models.Model): """Represents the type of item I am selling.""" ... class OrderItem(models.Model): """Represents an individual entry in an Order.""" user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) item = models.ForeignKey(Shirt, on_delete=models.CASCADE) quantity = models.IntegerField('Quantity', default=1) class Order(models.Model): """Represents an order, i.e. a 'collection' of entries.""" user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) When I work with logged in users, my models' fields get populated with corresponding user objects (that logic is already implemented with the help of request.user). Of course, that doesn't work with unregistered people. I have already read some info on django sessions and cookies, but I am not quite sure I get how to make it all work in a nice and clean way. I am just starting out with web development (and Django, … -
Count the number of keys in a postgres json field using a django query
Here is a stripped down definition of the table: import django.contrib.postgres.fields as pg_fields class MyTable(models.Model): data = pg_fields.JSONField() I would like to write the below as a pure Django query instead of writing the raw sql: MyTable.objects.raw(""" SELECT id, (SELECT COUNT(*) FROM jsonb_object_keys(data)) AS val FROM myapp_mytable ORDER BY val """) (use of from django.db.models.expressions import RawSQL is acceptable within an annotation if required) -
Serializer Does not return all the values to the View in Django Rest Framework
I am very new to Python and Django Rest Framework. I have been following a tutorial and did everything as mentioned in the tutorial. But it seems like I am missing something. Below is the code I have written - I am using python 3.6.9, Django - 2.1.7 and Django rest framework - 3.9.1 and pyJwt - 1.7.1 Models.py import jwt from django.db import models from django.conf import settings from datetime import datetime, timedelta from django.contrib.auth.models import PermissionsMixin,BaseUserManager,AbstractBaseUser class UserManager(BaseUserManager): def create_user(self,username, email, password=None): user = self.model(username=username,email=self.normalize_email(email)) user.set_password(password) user.save() return user def create_superuser(self, username, email, password = None): user = self.create_user(username, email, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser,PermissionsMixin): username = models.CharField(db_index = True, unique=True, max_length=255) email = models.EmailField(db_index=True, unique= True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email def get_full_name(self): return self.username def get_short_name(self): return self.username def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id':self.pk, 'exp':int(dt.strftime('%s')), 'email':self.email },settings.SECRET_KEY,algorithm='HS256') return token.decode('utf-8') @property def token(self): return self._generate_jwt_token() My Serializers.py from rest_framework import serializers from .models import User from django.contrib.auth import authenticate class RegistrationSerializer(serializers.ModelSerializer): password = serializers.CharField(min_length=8,max_length=128,write_only=True) token … -
What is a good tech stack for creating a basic restaurant management system web app?
I am working on a project for school and struggling to come up with a good, hopefully free, tech stack for a web app that acts as a management system for a restaurant. We want to use Python as the language. A stack I came up with is: Django, Apache, Python, and PostgreSQL. This is entirely new to me. Is there a way to use Azure and Python to make a web app like this? Thank you so much. -
Webpack not finding file
I'm recently following a tutorial on using webpack with Django and for the life of me the local host just can't find my bundle file This is what the console shows when I inspect on my local host: GET http://127.0.0.1:8000/static/bundles/bundle.js net::ERR_ABORTED 404 (Not Found) But I do have a directory called static in my project root directory, and a bundles directory inside, and a bundle.js file inside. I don't understand why the local host just couldn't find my file This is part of my tree: ├── static │ └── bundles │ └── bundle.js ├── templates │ ├── base.html │ ├── components │ │ ├── game │ │ │ └── game.html │ │ └── lobby │ │ ├── LobbyBase.jsx │ │ ├── index.jsx │ │ └── lobby.html │ ├── home.html │ ├── login.html │ └── register.html ├── webpack-stats.json └── webpack.config.js As you can see there's a static file, a bundle file inside, and the bundle.js inside. This is the Django setting code I have: STATIC_URL = '/static/' WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), }, } Any help will be appreciated! Thank you so much -
Passing request.user as hiddeninput while using html form in Django/Ajax
Is there a way to prepopulate request.user while using html forms in Django. My purpose is I want to create a photologue extended gallery with a User Foreignkey. class GalleryExtended(models.Model): # Link back to Photologue's Gallery model. gallery = models.OneToOneField(Gallery, related_name='extended', on_delete=models.CASCADE,) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="galleries",default=1,on_delete=models.CASCADE) I use Class Based Views/Ajax to create my Gallery class AjaxableResponseMixin: """ Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def form_invalid(self, form): response = super().form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): # We make sure to call the parent's form_valid() method because # it might do some processing (in the case of CreateView, it will # call form.save() for example). form.instance.slug = slugify(form.instance.title) form.instance.user = self.request.user print(form.instance.user) response = super().form_valid(form) if self.request.is_ajax(): data = { 'pk': self.object.pk, 'status': 'ok' } return JsonResponse(data) else: return response class GalleryCreateView(AjaxableResponseMixin, CreateView): model = GalleryExtended form_class = GalleryExtendedModelForm success_url = reverse_lazy('profiles:photos') I tried to initialize form: class GalleryExtendedModelForm(forms.ModelForm): class Meta: model=GalleryExtended fields = ["user"] def __init__(self, *args, **kwargs): super(GalleryExtendedModelForm, self).__init__(*args, **kwargs) self.fields['user'] = request.user self.fields['user'].widget = HiddenInput() and in my template: <form class="form-group label-floating" id="album-create-form" method="post" enctype="multipart/form-data"> {% csrf_token %} <label class="control-label">{% … -
Looking for resource or an advanced Tutorial on consuming Api's with Django
I am a product/project manager who is new to django and programming in general but I've now built a few sites in django using the standard website setup with models and a database backend. Every online tutorial and book i've bought has you build your website like this. However, I want to build a frontend that uses the Jira api which will show limited data to my clients about tasks and progress of their projects. I also want this to be a place for them to submit bugs/issues while testing their product. My plan was to use django's built in authentication/authorization to protect the site and get all other information directly from jiras api without using a database(except for users and misc django needs) I have found some very basic information on configuring the Api connection using the requests library and listing the basic data. I have so many questions but cant find anything on best practices, how the structure of the site should be, should I build out models that do not actually have a DB backend? Should I store all the information in sessions or cache? I have had the most issues with needing variables from previous views … -
How To Send Data from template in my request Django
I want to Send My Section Name From Drop Menu in Template (ex:Heart) to my views.py as object from Section Model def SectDetails(request): if request.method=='GET': sec_name=request.GET['section_name'] context={ 'section':Section.objects.get(section_name=sec_name) } return render(request,'hospital_system/sectiondetails.html',context) else: return render(request,'hospital_system/home.html') then my template <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> {% for sec in sections %} <a method='GET' class="dropdown-item" href="{% url 'Hosp-SectDetails' %}">{{sec.section_name}}</a> {% endfor %} </div> -
How to display string representation of a context object in Jinja2?
I have a property on a model: @property def model_name(self): """Return the model name.""" return self._meta.verbose_name In Django templates I display this simply by passing context['model_attr'] = self.model and then displaying {{ model_attr.model_name in the template. However in Jinja2 this results in <property object at 0x7f789aba52c0>. How do I display the str representation of the object? -
How to set ordering and number of items for each item in filter list?
How to set ordering and number of items for each item in filter list? class Category(models.Model): category = models.CharField(max_length = 20) Class Question(TimeStampedModel): category = models.ForeignKey(Category, related_name='question_set', on_delete=models.CASCADE) question = models.TextField(_('Question Text')) Category.objects.filter(category__in=['Sport', 'History']).values_list('question_set',flat=True).order_by('?')[:3] <QuerySet [6, 7, 3]> I need result like: <QuerySet [1, 3, 2, 7, 11, 9]> -
Django Admin, track value of change with LogEntry
Atm I got LogEntry on for my admin changes, this however only show the time for the change, the user making the change and what field that was changed. Is there a way to also add the value of the field that was changed? For example I have the following model: class Organization(models.Model): name = models.CharField(_('Organisationsnamn'), max_length=255) license_credits = models.DecimalField(_('Antal tillgängliga licenser'), max_digits=5, decimal_places=2, default=Decimal('0')) Atm if I change the license_credits in the history with the built in function I see "Changed license_credits". what I want is to have Changed license_credits from YY to ZZ" -
annotate sum of annotated values in related model
I have these models: class Product(..): category = ForeignKey('InputCategory... class InputCategory(MPTTModel): route_to = ForeignKey('RoutingCategory... class RoutingCategory(MPTTModel): pass So InputCategory has many Products and RoutingCategory has many InputCategory objects. I can annotate product_count for an InputCategory: InputCategory.objects.annotate(product_count=Count('products')) But I need to have product_count annotated to the RoutingCategory. How can I do that? I tried to modify Manager for InputCategory and do this: RoutingCategory.objects.annotate(product_count=Sum('input_categories__product_count')) But it says: FieldError: Unsupported lookup 'product_count' for AutoField or join on the field not permitted. Obviously I should have override related Manager. Do you know how to do that? -
Jquery blur method is not performing any action with form data of the django
I'm developing Checklist app with Django in which I'm trying to create a template with title and checklist items, for title I'm using the Jquery Ajax for storing the title in the DB with the help of model form. Here is the JS and AJAX code I'm using to pass data to view <script type="text/javascript"> $(document).on("blur","#js_template_title", function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'{% url "checklist" %}', data:{ title:$('#js_template_title').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), action:'post', }, success: function(response){ $("#js_template_title").val(data['title']); }, error: function(xhr,errmsg,err){ console.log(xhr.status+":"+xhr.responseText); } }); }); </script> The below is the HTML snip for form, the ID "js_template_title" which I'm using in JS is explicitly added in the Forms with the widgets help <form method='post' id='js-title-form' class="form-inline p-1 m-1"> <div class="form-row"> <div class="col"> {% csrf_token %} {{temp_form|crispy}} </div> <div class="col"> <input class="" type="image" src="{% static 'components/tick.jpg' %}" alt="submit" width="30" height="30"> </div> </div> </form> temp_form --> Code from browser The problem is the code works well with submit action but when I comment out the input submit action and enable the blur it's not working. Suggest me with the appropriate action which can be used to save the title name to DB when the focus is out of the text field -
Django hosting on sharedhost
We are in the process of deploying a new Django web app to production. For testing purposes, we were using a small and cheap unmanaged VPS, but for production, we would like to concentrate on the web app, rather than spending time on managing server, which left us with sharedhosting or managed VPS as alternatives for production. As a startup, we don’t want to spend unnecessary extra money on managed VPS solution, so we want to try shared hosting for now and update to VPS later when needed. But we are concerned about Django on sharedhost since some shared hosting providers (e.g. A2hosting) claim that it is possible to host Django on sharedhost but they don’t provide any support for any issues that may arise during deployment or in-production running. We are aware of the common pitfalls of shared hosting when compared to VPS. But are there Django/python specific issues that makes shared hosts problematic for Django apps? Can shared hosting based Django app be reliable enough for a web page that only expect a maximum of a thousand visitors per day? The business logic inside the app is also not complex, so CPU time is also not our main … -
django form validation not working on mobile devices
I created a form which looks like this class SignUp(forms.Form): username = forms.CharField(min_length=3, max_length=25, strip=True, required=True, validators = [validate_username,]) password = forms.CharField(min_length=8, max_length=64, widget=forms.PasswordInput, required=True) first_name = forms.CharField(min_length=2, max_length=50, required=True, strip=True) last_name = forms.CharField(min_length=2, max_length=50, required=True, strip=True) email = forms.EmailField(required=True, validators = [validate_email,]) hidden = forms.CharField(widget=forms.HiddenInput, required=False) data = forms.CharField(widget=forms.HiddenInput, required=False) and my form looks like this <form class="login-form" method="post"> {% csrf_token %} <div class="input-block"> {{ form.first_name.label }} {{ form.first_name }} </div> <div class="input-block"> {{ form.last_name.label }} {{ form.last_name }} </div> <div class="input-block"> {{ form.email.label }} {{ form.email }} </div> <div class="input-block"> {{ form.username.label }} {{ form.username }} </div> <div class="input-block"> {{ form.password.label }} {{ form.password }} </div> <input class="submit" type="submit"> </form> On desktop it's working fine but when I tried it on mobile device it redirects me to the same page. The form is filled and password field is blank ofcourse. And the account is not created. Initially I thought there's something wrong with the form and it's not posting but that was not the case. Turns out post is being sent but for some reason the form is not considered valid by forms.Form.is_valid(). I tried googling because I thought there's no way that someone hasn't encountered this before … -
inline radio buttons with crispy
I've seen a few posts with the same questions but unfortunately none of the answers have worked. I'm using Django Crispy Fields and I am trying to display my radio buttons horizontally. I use the helper layout to add the inline option to the radio buttons but it doesn't seem to affect the result when I render my fields as crispy_fields. Here is the code for my form: from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout from crispy_forms.bootstrap import InlineRadios, Div CHOICES = [ (1, 'Strongly Disagree'), (2, 'Disagree'), (3, 'Neutral'), (4, 'Agree'), (5, 'Strongly Agree'), ] class SelfKnowledgeAndAttitudeForm(forms.Form): def __init__(self, *args, **kwargs): from itertools import chain language = kwargs.pop('language', None) super().__init__(*args, **kwargs) self_knowledge = asmodels.SelfKnowledgeIndicator.objects.all() attitude = asmodels.AttitudeIndicator.objects.all() result_list = list(chain(self_knowledge, attitude)) for item in result_list: if type(item) == asmodels.SelfKnowledgeIndicator: field_name = 'sf-%s' % item.id else: field_name = 'at-%s' % item.id if language.lower() == 'english': description = item.description_english else: description = item.description_chinese self.fields[field_name] = forms.ChoiceField(label=description, required=True, widget=forms.RadioSelect, choices=CHOICES) self.helper = FormHelper() self.helper.layout = Layout( InlineRadios(field_name) ) -
python import from symbolic linked script
I have python script which inport module from directly below itself. settings --|-- base.py manage.py |-- init.py Normally for this case . I can import settings.base. However in my case manage.py is symbolic link. settings ------------------------------------------|-- base.py manage.py -> /var/www/html/myapp/shared/manage.py |-- init.py I exec manage.py in the same directly. but It shows the error No module named 'settings.base' Is it impossible to use symbolic for this case?? Or is there any workaround?? -
django form with jquery and ajax
While i am posting here, i actually see again what i am about to ask. I hope my title is correct because i am kind of new to django. Situation is, i have content posting form with tags field. User needs to fill out tags field -with at most 5 tags- at first and then be able to see similar posts with same tag or tags. Then continues if he still likes to post new content. In other words, like here on Stackoverflow, but not title oriented. The question is, if there is a sample code or any tutorial available for this case -for both Jquery and Ajax side- or if it is done some other way. Many thanks in advance. -
Extended a third party app in Django (django-organizations)
I'm, trying out django-organizaitons (https://django-organizations.readthedocs.io/en/latest/) and so far it's really handy - however, I wish to extend the basic model by adding another field to a model. The app does provide abstraction classes, but I'm losing some of the core functionality of django-organizations by doing so (e.g email invitations). What's the easiest / best way to simply extend a model and adding another field to that model? I've got something like this going on: from organizations.abstract import (AbstractOrganization, AbstractOrganizationUser, AbstractOrganizationOwner) class Project(AbstractOrganization): name = models.CharField(max_length=100, default="") project_owner = models.ForeignKey( "accounts.User", on_delete=models.CASCADE) class ProjectUser(AbstractOrganizationUser): # this is a field that I wish to add to the out-of-the-box solution user_hour_cost = models.DecimalField(max_digits=6, decimal_places=2, default=0) class ProjectOwner(AbstractOrganizationOwner): pass This works fine, as is, but now.. the invitation functionality is gone