Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I show model field values in HTML page, in Django for this particular case?
I need to display the details of the user on the profilepage. But in the following situation, I am unable to render phone number and flag(attributes of SpecialUser model) on my profile page. I was asked to implement an extended model for the User model in Django auth for an application. I introduced 2 new fields i.e, phonenumber(charfield), flag(booleanfield). My form is able to take both the inputs. But I couldn't render these values again into my HTML file. Could someone help me out! models.py # accounts.models.py from django.db import models from django.contrib.auth.models import User class SpecialUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) flag = models.BooleanField(verbose_name="Special User", default=False) phonenumber = models.CharField(max_length=10, verbose_name="phonenumber") def __str__(self): return self.user.username forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import SpecialUser class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] class SuperUserForm(forms.ModelForm): class Meta: model = SpecialUser fields = ["flag", "phonenumber"] views.py from accounts.models import SpecialUser from django.shortcuts import render, redirect from .forms import RegisterForm, SuperUserForm from django.contrib import messages from django.contrib.auth.models import auth def register(request): if request.method == 'POST': form = RegisterForm(request.POST) sp_form = SuperUserForm(request.POST) if form.is_valid() and sp_form.is_valid(): user = form.save() … -
Deploying Django Postgres to Heroku with modules
I'm having three problems setting up Django to deploy to Heroku. The first one is defining the DATABASE, the second one is using modules for production and deployment and the third one is how Heroku knows which module to run I have all my code on Github and I'm using remote deployment (if that might help). The structure of the project is the following: | |- app1 | |- src | settings |- base.py |- development.py |- production.py The development.py file looks like this from .base import * SECRET_KEY = config("SECRET_KEY") DEBUG = config("DEBUG", cast=bool) ALLOWED_HOSTS = config("ALLOWED_HOSTS", cast=lambda v: [s.strip() for s in v.split(',')]) DATABASE = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'your db name', 'USER': 'your username', 'PASSWORD': 'password', 'HOST': 'Computer's IP', 'PORT': '6122', } } production.py from .base import * DEBUG = False import dj_database_url DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) The Heroku is not detecting my productction setup. Any idea how can I accomplish this? -
__str__ returned non-string (type NoneType) because the field is null
I'm getting this error in my model PedidoPizzaThrough: __str__ returned non-string (type NoneType) I assume it's maybe because the fields are null for now but I added the else "" and nothing changes. How do I fix this? My model is like this: class Pizzas(models.Model): nombre = models.CharField(max_length=100, unique=True) cant = models.IntegerField(default=0) def __str__(self): return self.nombre class Pedido(models.Model): fecha = models.DateField(auto_now_add=True) email = models.EmailField(max_length=200, null=True) telefono = models.IntegerField(null=True) pizzas = models.ManyToManyField('Pizzas', through='PedidoPizzaThrough', related_name='pedidos') cantidad = models.IntegerField(default=0) def __str__(self): return self.email class PedidoPizzaThrough(models.Model): pizza = models.ForeignKey(Pizzas, on_delete=models.PROTECT) pedido = models.ForeignKey(Pedido, on_delete=models.PROTECT) cantidad = models.IntegerField() def __str__(self): return str(self.pizza) if str(self.pizza) else "" -
Django ModelForm not showing in template
I am trying to create a form that enables the user to input his email, whenever a product is out of stock, through a bootstrap modal. However, the form {{ form.as_p }} is not showing on the template (see picture below). Furthermore, I'm not sure how to pass in the Product.id and Product.name so that its visible along with the email, whenever a user clicks submit, on the Django Admin side? models.py class ReminderEmail(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) remindemail = models.CharField(max_length=200, null=True) def __str__(self): return self.email forms.py from django import forms from .models import ReminderEmail class EmailForm(forms.ModelForm): class Meta: model = ReminderEmail fields = [ 'remindemail' ] views.py from django.shortcuts import render from django.http import JsonResponse import json import datetime from .models import * from .forms import * def email_remind_view(request): form = EmailForm(request.POST or None) if form.is_valid(): form.save() context = { 'form' : form } return render(request, "store.html", context) store.html <div id="stockModal" class="modal fade" role="dialog"> <div class="modal-dialog modal-dialog-centered"> <!-- Modal content--> <div class="modal-content"> <form> <div id="modalheader" class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">This product is Out of Stock</h5> </div> <div id="modalbody" class="modal-body"> <p>Enter your email to be reminded whenever this product goes back in stock.</p> </div> <div class="modal-footer"> … -
How can I order by a method in django REST?
I have a simple model like the following: class Category(models.Model): """Class to represent the category of an Item. Like plants, bikes...""" name = models.TextField() description = models.TextField(null=True) color = models.TextField(null=True) parent_category = models.ForeignKey( 'self', on_delete=models.SET_NULL, null=True, ) class Meta: # pylint: disable=too-few-public-methods """Class to represent metadata of the object.""" # ordering = ['category_name'] <------- I WOULD LIKE THIS SORTING ordering = ['parent_category__name', 'name'] def category_name(self): """String for representing the Model object.""" if self.parent_category: return str(self.parent_category.category_name() + " -> " + self.name) I have not been able to find a solution to sort by a method inside the model like the example that is commented out in the example model. The results that the two filters I'm using in different steps don't give mt the results I want- If I have: Music/Guitar Music/Piano Music Books It will return: Music/Guitar Music/Piano Books Music And what I need is: Books Music Music/Guitar Music/Piano It would also be ok to have this in the serializer or be able to choosse the sorting with the parameters in the REST query, but I have not been able to make this work in any possibility. -
Django custom order_by algorithm
I want to create a formula for trending posts. I've done this so far: def hot(request): posts = Post.objects.all() for post in posts: likes = int(post.likes) views = int(post.blog_view) rep = int(post.author.profile.reputation) d0 = timezone.now() d1 = post.date_posted days = (d0 - d1).days trending_score = (3/(1+days**(1/3)))*(0.5*views+0.25*rep+2.5*likes) The formula is at trending_score variable, and each time, it returns a number for its trending score. The higher the trending_score, the more trending it is. Now I want to implement this in django using order_by, or something else: def hot(request): posts = Post.objects.all() for post in posts: likes = int(post.likes) views = int(post.blog_view) rep = int(post.author.profile.reputation) d0 = timezone.now() d1 = post.date_posted days = (d0 - d1).days trending_score = (3/(1+days**(1/3)))*(0.5*views+0.25*rep+2.5*likes) context = { Post.objects.all().order_by(-trending_score) } return render(request, 'blog/popularity.html', context) I obviously knew this wasn't going to work, because I put trending_score in the for loop and context is outside of it, so it wasn't going to work. The error was:Invalid order_by arguments: [-21.75] But I have no idea how else I can do this. Any help in doing this will be appreciated. -
DRF : parameter in custom permission class with function based views
I use Django Rest Framework to build my API and it works fine. I use function based views to manage my endpoints. It works well too but I'm trying to add a custom permission class and putting parameters with it do not work. An example of one of my endpoints : @api_view(http_method_names=["GET"]) @permission_classes([IsAuthenticated]) def team_kanban(request): """ List all Helpdesk Teams with kanban fields. """ teams = HelpdeskTeam.objects.all() return Response(HelpdeskTeamKanbanSerializer(teams, many=True).data) It works without any problem. But when I try to do : @api_view(http_method_names=["GET"]) @permission_classes([IsAuthenticated, HasPermission("view_helpdeskteam")]) def team_kanban(request): """ List all Helpdesk Teams with kanban fields. """ teams = HelpdeskTeam.objects.all() return Response(HelpdeskTeamKanbanSerializer(teams, many=True).data) with this custom permission class : from rest_framework import permissions class HasPermission(permissions.BasePermission): """ Allows access only to users who have the appropriate permission. """ permission_codename = "" def __init__(self, permission_codename): super().__init__() self.permission_codename = permission_codename def has_permission(self, request, view): return request.user.has_permission(self.permission_codename) It doesn't work. The full error is : Traceback (most recent call last): File "C:\Program Files\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Program Files\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Program Files\Python37\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Program Files\Python37\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Program … -
Can you use HTML Input Tags in place of Django form templates?
I have had a basic login form working and styles with CSS. I have tried to update this with Tailwind to improve the design of my application. However, to apply this styling, input tags are required, is there a way to use Input tags to authenticate a user as opposed to using the form templates provided by Django? i.e: {{ form.as_p }}. -
Django Channels and Google Cloud Run + Redis Instance
please can someone help me as I am having an issue installing channels on cloud run? I have everything up and running (Cloud run, VPC Connector, Redis Instance...etc) But I can't get WebSocket to connect and I don't know why it keeps failing. Thanks in advance. -
What is the best way to generate video thumbnails?
I am creating an application with Vue.js and Django. I am getting a list of videos from AWS S3 and I am displaying it in the frontend. Now I need to create thumbnails for these videos? I want to know what is the best practice to generate the thumbnails? Should I: Should I generate thumbnails on the frontend side each time it receives videos? Should I generate thumbnails on the backend side each time videos are requested? Should I generate thumbnails on the backend and save them in the storage and then send them when the videos are requested? Currently, I am finding solutions on how to generate thumbnails on the frontend or how to save them but no one is discussing which is the best way to do it. -
How do I fix the makemigrations command error?
I'm using python 3.8 and django 3.1.7 at first my models.py was like this: from django.db import models class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text when I issued the "python manage.py makemigrations learning_logs" it worked fine. But when I changed my code to: from django.db import models class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..." it gave me this error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/okab/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/okab/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/okab/.local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/okab/.local/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/okab/.local/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen … -
Inline Formsets with other Inline Formsets nested in Django
I'm developing a Django App and I have encountered a problem that I can't resolve. I have some models like the following: class A(models.Model): property_a = models.CharField() class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) property_b = models.CharField() class C(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) property_c = models.CharField() class D(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) property_d = models.CharField() There could be other models like C and D (that have the foreignKey to B). The goal is to be able to add or remove (dynamically) B objects from A (and I was able to do that) and add or remove C,D, and if present other models related to B dynamically. This last operation is my problem, because I didn't find a way to create nested inline formsets. Below I will show the code that solved the first thing: def create_scenario(request, pk): global current_extra a = A.objects.get(pk=pk) if request.method == "POST": if "add" in request.POST.keys(): current_extra += 1 elif "del" in request.POST.keys(): current_extra -= 1 BInlineFormSet = inlineformset_factory(A, B, fields=('f1', 'f2', 'f3', 'f4'), extra=current_extra) formset = BInlineFormSet(instance=a) if request.method == "POST": if "add" not in request.POST.keys() and "del" not in request.POST.keys(): formset = BInlineFormSet(request.POST, request.FILES, instance=a) if formset.is_valid(): a.save() formset.save() return HttpResponse("Done " + str(a)) else: … -
'RelatedManager' object is not iterable typeerror
I want to get all profiles that the user is following and display them in separate div with(img, name,email). I can get the total number of 'following', however, I'm not able to iterate throw following and display user by user. Exception Value: 'RelatedManager' object is not iterable Any help is appreciated! dashboard: <p>{{ user.following.count }}</p> {% for guest in user.following %} <div class="container-videos-card"> <div class="videos-card-details"> <h4 class = "container-videos-card-title">{{ guest.email }}</h4> </div> </div> {% endfor %} model: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null = False) username = models.CharField(max_length=264, null = True, blank = True) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') full_name = models.CharField(max_length=264,null = True, blank = True) username = models.CharField(max_length=264, null = True, blank = True) profile_picture = models.ImageField(upload_to='profile_pictures/%Y/%m/%d/', blank = True) class Follow(models.Model): follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower") following = models.ForeignKey(User, on_delete=models.CASCADE, related_name="following") -
Django and multi tenancy which applications must be shared and which ones must be public
I'm working on a small project using Django, and I just installed Django-tenants, I would like to know which applications must be shared and which ones must be public this is my settings. NB : user application it's a for custom user model SHARED_APPS = [ 'django_tenants', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # My applications 'contact', 'list', 'users', # custom user model 'task', #3rd Part application 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth', 'rest_auth.registration', 'webpack_loader', 'corsheaders', 'customer', ] TENANT_APPS = [ 'django_tenants', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', ] -
Share and notification from flutter app with django backend
A have a website built with python/django, and i made rest api for this project. Also i made a flutter app that uses this api. My problem is (1): i need a button inside a flutter app that share a link of a product, and when someone press it, it will redirect it to open the product inside the app (not webview). Another problem is (2):i need to send notification from my django backend to the flutter app users. I will be so grateful to you guys. -
Why posting data in login form is not redirecting me to dashboard?
Guys I have made a bootstrap login whose data I'm checking at views.py def login(request): if request.method=="POST": email=request.POST.get('email') password=request.POST.get('password') if email=="cool@c.com" and password=="567": return redirect('dashboard') else: context="Provide Valid Credentials" return render(request."login.html",context -
Azure Pipelines on Django app: Psycopg2 fails to initialize for unit tests
I'm having issues setting up a small pipeline for my Django app. Here's the yaml configuration: trigger: - main pool: vmImage: ubuntu-latest strategy: matrix: Python39: PYTHON_VERSION: '3.9' maxParallel: 2 steps: - task: UsePythonVersion@0 inputs: versionSpec: '$(PYTHON_VERSION)' architecture: 'x64' - task: DownloadSecureFile@1 name: dotEnv inputs: secureFile: '.env' - task: PythonScript@0 displayName: 'Export project path' inputs: scriptSource: 'inline' script: | """Search all subdirectories for `manage.py`.""" from glob import iglob from os import path # Python >= 3.5 manage_py = next(iglob(path.join('**', 'manage.py'), recursive=True), None) if not manage_py: raise SystemExit('Could not find a Django project') project_location = path.dirname(path.abspath(manage_py)) print('Found Django project in', project_location) print('##vso[task.setvariable variable=projectRoot]{}'.format(project_location)) - task: CopyFiles@2 displayName: 'Add .env file' inputs: SourceFolder: '$(Agent.TempDirectory)' Contents: '.env' TargetFolder: '$(projectRoot)' - script: | python -m pip install --upgrade pip setuptools wheel pipenv pipenv install unittest-xml-reporting displayName: 'Install prerequisites' - script: python -m pipenv lock -r > requirements.txt displayName: 'Create requirements.txt from Pipfile' - script: pipenv install displayName: 'Install requirements' - script: | pushd '$(projectRoot)' pipenv run python manage.py test --testrunner xmlrunner.extra.djangotestrunner.XMLTestRunner --no-input displayName: 'Run tests' - task: PublishTestResults@2 inputs: testResultsFiles: "**/TEST-*.xml" testRunTitle: 'Python $(PYTHON_VERSION)' condition: succeededOrFailed() The problem happens when the Run tests script starts as Django can't create a test database, but the error … -
Django | Migrations on splitted settings.py
I recently decided to change my settings.py file into a directory called settings for a better structure of de project. The directory containts the following files: _ _ init _ _.py base.py local.py production.py Also, different databases are used for local settings and production settings, I was wondering on how to run migrations either for the local database or the production database given that my settings are splitted. Here is the code inside _ _ init _ _.py from .base import * try: from .local import * live = False except ImportError: live = True if live: from .production import * Inside local.py you can find the SECRET_KEY, INSTALLED_APPS, MIDDLEWARE, TEMPLATES, etc. Whereas local.py and production.py contain DEBUG, ALLOWED_HOSTS, DATABASES, and stuff about static and media files. There are plenty of articles on splitting settings.py for local and production settings, however none of them have information about the migrations. -
Django __str__ returned non-string (type NoneType) when trying to delete
I get this error: __str__ returned non-string (type NoneType) , but ONLY if the user is created through a HTTP Post Request. If I create the user through the normal Django Admin Panel I can delete the user. I also tried to print every type of the HTTP Post income and get this: <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'int'> <class 'int'> <class 'str'> So every field is a str or an integer. What could be the problem? -
E: npm unable to locate assets
I'm making a Web App with Django + Python + React Js and I was finishing it but when I run npm run dev this error appears: ‼ 「copy-webpack-plugin」: unable to locate 'app\assets' at 'C:\Users\msi\music_project\frontend\app\assets' asset main.js 670 bytes [compared for emit] (name: main) asset index.html 231 bytes [compared for emit] WARNING in unable to locate 'app\assets' at 'C:\Users\msi\music_project\frontend\app\assets' ERROR in main Module not found: Error: Can't resolve './app/game/index.js' in 'C:\Users\msi\music_project\frontend' resolve './app/game/index.js' in 'C:\Users\msi\music_project\frontend' using description file: C:\Users\msi\music_project\frontend\package.json (relative path: .) Field 'browser' doesn't contain a valid alias configuration using description file: C:\Users\msi\music_project\frontend\package.json (relative path: ./app/game/index.js) no extension Does somebody know how to fix this? -
The default django admin causes lot of problems
As I'm new to Django so I'm going to ask a stupid question on how to use Django features of session , cookies without using default django admin , I mean deleting it and creating everything new. Any help or suggestion will be appreciated! -
Ternary operator within a Dajngo query not working
Am tring to use a ternary operator in a django custom query but it throws an exception, below is my sample code : key = 'person' if data['type'] is 'Person' else 'business' cp_entity = data['entity'].get_or_create( customer_profile=customer_profile, **{key: self} ) This is the error thrown : TypeError: get_or_create() got an unexpected keyword argument 'person' am I missing something ? -
How to take boolean field input from HTML into my Django model?
I have used Django forms for creating users and I extended the default User model by adding a boolean field, so I defined a new form for it. But I couldn't take input from HTML form to this boolean field. Shall I change my HTML form code? Following are my code samples: models.py # accounts.models.py from django.db import models from django.contrib.auth.models import User class SpecialUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) flag = models.BooleanField() def __str__(self): return self.title forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms.widgets import CheckboxInput from .models import SpecialUser class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] class SuperUserForm(forms.ModelForm): class Meta: model = SpecialUser fields = ['flag'] widgets = { 'flag': CheckboxInput(attrs={'class': 'flag'}), } views.py def register(request): if request.method == 'POST': form = RegisterForm(request.POST) sp_form = SuperUserForm(request.POST) if form.is_valid() and sp_form.is_valid(): user = form.save() sp_form = sp_form.save(commit=False) sp_form.user = user sp_form.save() messages.success(request, 'Account created!') return redirect('login') else: form = RegisterForm() sp_form = SuperUserForm() messages.warning(request, 'Your account cannot be created.') return render(request, 'register.html', {'form': form}) HTML form code: <form method="post" class="form-group"> {% csrf_token %} {{ form|crispy }} <label for="flag">Special User: </label> <input id="flag" class="flag" type="checkbox" … -
Is there a way for me to pass to my view a context passed on to my template?
I processed a DataFrame that I then passed on to my template as a context. I then used a form to move on to the next view. Is there a way to pass my DataFrame from the template on to the next view? Here is my views code: def clean(request): #processing on df return render(request, 'clean.html', {'conf': conf, 'num': newnum, 'df': df, 'corr': correl, 'target': nametar}) and here is my template that redirects to the correlation/ view: {% extends 'base.html' %} {% load static %} {% block content %} <p> {{num}} lines were dropped. Your dataset is now clean</p> Here are the correlations of the features with the {{target}}, select the ones you want to drop. <br> It is advised to delete the ones below 5% but you can keep them if necessary. <form action = '{%url 'correlation'%}' method = "post"> {% csrf_token %} {% for key, value in corr.items%} {%if value != 1%} <input type = 'checkbox'>{{key}}- {{value}} <br> {%endif%} {% endfor %} </select> <p> Click the Next button to move on to the next phase "Transformation" </p> <button type='submit' name='btn' id='btn' class='btn' >Next</button> </form> {% endblock %} How can I pass my df from here to my view … -
How do I pass data from <layout> in <template> to a method in my export default in Vue?
I'm trying to collect the text from a text input in HTML to the methods section of my Vue file but can't seem to figure it out. I've spent a couple hours researching v-model and messing around with it but, I was either doing it wrong or it doesn't do what I thought it did. Here's my code: <template> <div id="app"> <Layout> <input id="queryBox" placeholder="Enter your SQL query here." size="60"/> <br> <input type="submit" v-on:click="logSomething()"> </Layout> </div> </template> <script> export default { data: () => { return { queryText: "" } }, methods: { logSomething() { console.log(this.queryBox) } } } </script> I'm trying to send whatever the user inputs into queryBox to the logSomething() method upon the click of the submit button. Thanks in advance for any help!