Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how to make the url conditional on an if statement and dynamically change the pk
How do I have a if statement for a url and it's pk argument? I would like to run this logic in the base.html (which references the elements model) if self.fk_type = '2' {so if the current element has an fk_type of 2} open url 'project' on the record who's fk_element matches the current element's id {so imagine something like - ?url pk == self.fk_element} {i'm using self. even though the elements model has no field called fk_element as the projects model does and this model is a onetoone with the elements model. Because of this I believe project's fields can be treated as fields belonging to elements} These are the relevant models, views, urls and html models I previously had the fk_elements as a foreign key, but projects really is just an extension class elements(models.Model): fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) fk_concept = models.ForeignKey(concepts, default='1', on_delete=models.CASCADE) fk_type = models.ForeignKey(elements_types, on_delete=models.PROTECT, null=True) name = models.CharField(max_length=250) def __str__(self): return self.name class Meta: ordering = ('name', ) class projects(models.Model): fk_element = models.OneToOneField(elements, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=250, default='') description = models.TextField(default='', blank=True, null=True) notes = models.TextField(default='', blank=True, null=True) order = models.PositiveSmallIntegerField(blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ('order', ) views β¦ -
Why does the api call not go through in django?
This is the url- url(r'^admin/login/$', admin_authentication), The function has post request and accepts- username = request_body['username'] password = request_body['password'] And the postman has the body in POST format as- { "username" : "abcd", "password" : "abcd" } The error is- Page not found at /plugins/admin/login -
django rest_framework: post image file or path string to ImageField
Lets say I have this model, serializer and view: models.py class MediaFiles(models.Model): name = models.CharField(max_length=300) thumbnail = models.ImageField(upload_to=settings.UPLOAD_STORAGE_ROOT + "/%Y/%m", max_length=255, null=True, blank=True) serializers.py class MediaFilesSerializer(serializers.ModelSerializer): thumbnail = serializers.ImageField( max_length=None, use_url=False, required=False ) class Meta: model = MediaFiles fields = ('name', 'thumbnail',) views.py class MediaFilesViewSet(viewsets.ModelViewSet): queryset = MediaFiles.objects.all().order_by('name') serializer_class = MediaFilesSerializer When using a models.ImageField(...) normally it is not possible to post just the path string. The error message would be: {"thumbnail": ["No file was submitted. Check the encoding type on the form."]} Is it possible to realize a conditional post function, that takes a image file or a string? -
Filtering against query parameters, Many to many
I want to filtering against query parameters in the URL by id. For example: http://.../game/?category=1&level=1. Here are some pieces of my code: models.py class Game(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Categories, on_delete=models.CASCADE) level = models.ManyToManyField(Level) views.py class GamesListView(generics.ListAPIView): serializer_class = GamesListSerializer def get_queryset(self): queryset = Games.objects.all() category = self.request.query_params.get('category') level = self.request.query_params.get('level') if category: queryset = queryset.filter(category_id=category) How to filter the levels that are related by the relationship many to many with game? -
How do I deploy my separated Django front and back end via Heroku?
I have two Django projects, for front and back end (using DRF). i want to deploy them both in Heroku, on the same url (eg backend.website.com for the back end and website.com for front end). Then the backend would only whitelist the front. How do i do this (if it's possible) on Heroku? Would they need to be on separate dyno's? -
How do I count hits of each element in a list in Django?
So I have a page where multiple articles are listed. (To be precise, TITLES that are outlinked to the articles written on Notion template.) And I want to have a filed in my model that counts the number of clicks of each article. (I don't want to use django-hitcount library). Let me first show you my code. models.py class Article(models.Model): number = models.IntegerField(primary_key=True) title = models.CharField(max_length=20, default="") url = models.URLField(max_length=100, default="") hits = models.IntegerField(default=0) template ... <div class="col text-center"> {% for q in allArticles %} <a href="{{q.url}}"><h2 id={{q.number}}>{{q.title}}</h2></a> {% endfor %} </div> ... I was thinking of using onclick() event in JavaScript, but then passing data from JavaScript to Django seemed too challenging to me at the moment. I'd very much appreciate your help. Thanks. -
Django try/catch not working and breaking whole programm
I was working on a django web using sqlite, I changed it to postgres and suddenly this error start to appearing. ProgrammingError at /api/v1/news-source/all function lower(integer) does not exist LINE 1: ...ws_sources_newssource"."deleted" IS NULL ORDER BY LOWER("new... and I am unable to catch it. My code is class CaseInsensitiveOrderingFilter(OrderingFilter): def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) insensitive_ordering = getattr(view, 'ordering_case_insensitive_fields', ()) if ordering: new_ordering = [] for field in ordering: if field in insensitive_ordering: if field.startswith('-'): new_ordering.append(Lower(field[1:]).desc()) else: try: new_ordering.append(Lower(field).asc()) except django.db.Error as e: new_ordering.append((field).asc()) except Exception as e: print(e) new_ordering.append(field) else: new_ordering.append(field) return queryset.order_by(*new_ordering) return queryset -
Django custom form - TypeError: __init__() takes 1 positional argument but 2 were given
When I want to create my own form instead of using Django's default one, I get this error: *TypeError: init() takes 1 positional argument but 2 were given I wanted to do it by creating subclass of Django's UserCreationForm. I am very new to Django, so any help will be most appreciated. Here is my code: views.py from django.contrib.auth import login, authenticate from django.http import HttpResponse from django.shortcuts import redirect, render from SmartCookbook.modules.forms import RegisterForm def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('homepageSmartCookbookApp') else: form = RegisterForm() return render(request, 'sign/register.html', {'form': form}) urls.py (app) from django.urls import path from . import views urlpatterns = [ path('', views.homepage, name='homepageSmartCookbookApp'), path('register/', views.register, name='registerSmartCookbookApp'), ] forms.py (where I wanted to create multiple custom forms classes) from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): """Registration form class""" username = forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'})) email = forms.EmailField(forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'}), max_length=64, help_text='Enter a valid email address') password1 = forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'})) password2 = forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password Again'})) class Meta(UserCreationForm.Meta): model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', β¦ -
How to sent multiple django forms through ajax on a single page with one submit button
I've checked quite similar/other questions but I couldn't find a useful answer. My Goal My goal is to get a single page with multiple (x amount) Zurb Foundation tabs and each tab will hold a form based on a class in my Django forms.py. On the page there will be only one submit button for all the forms. In the Django views, it must save the form data of each form to its own designated model. The problem The problem I'm facing right now is that I have no clue how I'm able to retrieve each form data in the views. When I'm printing the request.POST it gives me a QueryDict with information of all the forms together. As mentioned in my goal above, I would like to save the data of each separate form to its own designated model. Hope one of you can point me in the right direction. Thanks in advance for you help and time! Code My code at the moment is: <input type="submit" id="form-button" class="button" value="Sent"> <ul class="tabs" data-tabs id="example-tabs"> <li class="tabs-title is-active"><a href="#panel-first" aria-selected="true">First form</a></li> {% if second_form %} <li class="tabs-title"><a data-tabs-target="panel-second" href="#panel-second">Second form</a></li> {% endif %} </ul> <div class="tabs-content" data-tabs-content="example-tabs"> <div class="tabs-panel is-active" β¦ -
Query a Django Many-to-Many through relationship without iteration?
I am looking to organise products within categories in a way that is specific to the selected category. A product can be part of multiple categories and so I'm using a Many-To-Many Through relationship to define them. I have the following 4 models: class Category(MPTTModel, ModelWithMetadata, SeoModel, PublishableModel): name = models.CharField(max_length=512) ... β β class Product(SeoModel, ModelWithMetadata, PublishableModel): name = models.CharField(max_length=512) category_management = models.ManyToManyField( Category, related_name="category_managed_products", through="OrderedCategoryManagedProduct", blank=True, verbose_name="Category Management", ) ... β β class OrderedCategoryManagedProduct(SortableModel): category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="cmp_products" ) product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="cmp_categories" ) added_automatically = models.BooleanField(default=False) class Meta: ordering = ["sort_order"] β def get_ordering_queryset(self): return OrderedCategoryManagedProduct.objects.all() β β class SortableModel(models.Model): sort_order = models.IntegerField(editable=False, db_index=True, null=True) β class Meta: abstract = True β def get_ordering_queryset(self): raise NotImplementedError("Unknown ordering queryset") β ... The SortableModel is from the Saleor Legacy Views application Is it possible to query a particular category and receive a queryset of the products within it in - in order - without having to iterate through all the products individually? -
How to add prefix value in model for two columns...?
I am trying to add a Prefix(CLI, CID) into the two columns in one table but its working for me only the Primary Key but other field is not generating the CID00001 like this.... this is my model.py class Prefix(models.Model): cdClientID = models.CharField(primary_key=True, editable=False, max_length=200) cdClientNumber = models.CharField(editable=False, max_length=200) class Meta: unique_together = (('cdClientID', 'cdClientNumber'),) def save(self, *args, **kwargs): if not self.cdClientID: prefix = 'ATT{}'.format('') prev_instances = self.__class__.objects.filter(cdClientID__contains=prefix) if prev_instances.exists(): last_instance_id = prev_instances.last().cdClientID[-4:] self.cdClientID = prefix + '{0:08d}'.format(int(last_instance_id) + 1) else: self.cdClientID = prefix + '{0:08d}'.format(1) super(Prefix, self).save(*args, **kwargs) here its genrating the only clientID its PK and how can i generate the clientnumber also CLN00001 with autoIncrement tnx in advance... -
Load json data with get_or_create
I am a programming self-learner and I am new to python and django and would like to optimize my code. my problematic is that I want to do a get_or_create with some loaded json data. Each dictionary entry is directly linked to my model. example: data=json.load(file) Person.objects.get_or_create( firstname=data['firstname'], surname=data['surname'], gender=data['gender'], datebirth=data['datebirth'], ) Are there anyways to optimize my code in order to automatically link the json properties to my model fields instead of typing all my properties one by one? thank you, Tibibs -
How to connect to local PostGIS (PostgreS) database using Docker compose in Django project?
I need to connect to existing db in my computer. When I create db service with postgis image, it creates a new database inside docker container. But I need to connect to my local one. Is it possible? docker-compose.yml : version: '3' services: build: ./ command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput --i rest_framework && gunicorn orion-amr.wsgi:application --bind 0.0.0.0:8000 --workers=2" ports: - "${webport}:8000" env_file: - ./.env settings.py : DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': os.environ.get('pgdatabase'), 'USER': os.environ.get('pguser'), 'PASSWORD': os.environ.get('pgpassword'), 'HOST': os.environ.get('pghostname'), 'PORT': '5432', } } .env file: pgport=5432 webport=8000 SECRET_KEY=z)mf(y#w7-_8y1)0(v*n@w@lzf)!0=g_rj5$%1w6g-t!7nbk05 pgdatabase=amr_or pgpassword=root pghostname=localhost pguser=postgres DEBUG= Now I have this error: web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "localhost" (127.0.0.1) and accepting web_1 | TCP/IP connections on port 5432? web_1 | could not connect to server: Cannot assign requested address web_1 | Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5432 -
I want to create and update UserProfile object with OneToOne User object field and create an api in Django rest framework
I'm new in Django rest framework, I tried my whole day but can't do it,I want to do full crud operation in my UserProfile Model which have a OneToOne field user, User can only update their own profile and in UserProfile create or update user shouldn't update User[username], How can i achieve it Please Help me views.py class Profile(APIView): def get(self, request, format=None): try: _profile = request.user.userprofile except ObjectDoesNotExist: _profile = { "phone": '', "image": '', } finally: content = { "first_name": request.user.first_name, "last_name": request.user.last_name, 'phone': _profile.phone, 'image': _profile.image } return Response(content, status=200) models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user_profile', on_delete=models.CASCADE) phone = models.CharField(max_length=15,default='') image = models.ImageField(upload_to='profile_image', blank=True) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username Error AttributeError at /api/ 'AnonymousUser' object has no attribute 'first_name' Request Method: GET Request URL: http://127.0.0.1:8000/api/ Django Version: 3.0.8 Exception Type: AttributeError Exception Value: 'AnonymousUser' object has no attribute 'first_name' Exception Location: C:\Users\Aleem\PycharmProjects\E-Commerce\src\e_commerce_project\api\views.py in get, line 34 Python Executable: E:\OFFICCE WORK\e-commerce\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\Aleem\\PycharmProjects\\E-Commerce\\src\\e_commerce_project', 'C:\\Users\\Aleem\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\Aleem\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\Aleem\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\Aleem\\AppData\\Local\\Programs\\Python\\Python38-32', 'E:\\OFFICCE WORK\\e-commerce', 'E:\\OFFICCE WORK\\e-commerce\\lib\\site-packages'] Server time: Thu, 23 Jul 2020 09:49:23 +0000 -
How to fetch the response from my Django view & url and console.log the response in my Django template (home.html) using Javascript
I've been trying to console.log the Json(response) from my View in my home.html template with no success. Here is my code: Views.py def Tweets_view(request, *arg, **kwargs): qs = Tweets.objects.all() for x in qs: tweet_list = { 'id': x.id, 'content': x.content } context = { 'response': tweet_list } return JsonResponse(context) urls.py from django.contrib import admin from django.urls import path from tweets.views import Tweets_view_id, Tweets_view urlpatterns = [ path('admin/', admin.site.urls), path('tweets', Tweets_view), #N.B This is the URL I'm trying to access. path('tweets/<int:tweet_id>', Tweets_view_id) ] home.html {% extends './base.html' %} {% block content% } <div id="tweets"> LOADING ... </div> <script> const tweetsElement = document.getElementById("tweets") const xhr = new XMLHttpRequest() const method = "post" const url = "/tweets" const responseType = "json" xhr.responseType = responseType xhr.open(method, url) xhr.onload = function () { const serverResponse = xhr.response var listedItems = serverResponse.response console.log(listedItems) } xhr.send() </script> {% endblock content% } my browser (Dispays nothing in the consoleenter image description here) -
Django - Media Files going on 404 in Production (Azure Storage)
Upon deploying an application to the azure app server, for media files, I am referring to the azure blob storage. I am using https://django-storages.readthedocs.io/en/latest/backends/azure.html docs. I have written these lines of code in my settings.py file. DEFAULT_FILE_STORAGE = 'index.custom_azure.AzureMediaStorage' STATICFILES_STORAGE = 'index.custom_azure.AzureStaticStorage' STATIC_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIAFILES_LOCATION}/' In the custom_azure.py file I have included my classes from storages.backends.azure_storage import AzureStorage class AzureMediaStorage(AzureStorage): account_name = 'ACCOUNT_NAME' # Must be replaced by your <storage_account_name> account_key = 'KEY' # Must be replaced by your <storage_account_key> azure_container = 'media' expiration_secs = None location = 'media' file_overwrite = False class AzureStaticStorage(AzureStorage): account_name = 'MY_STORAGE' # Must be replaced by your storage_account_name account_key = 'My_KEY' # Must be replaced by your <storage_account_key> azure_container = 'static' expiration_secs = None My urls.py file is like this. urlpatterns = [ path('',include('index.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Any help appreciated! -
Where to put my Comments views code to the view.py correctly in Django?
Guys i was following a tutorial and i cant understand how should i put my view for Comment model in my views.py. Please give me directions, i dont know where exactly i should put and how i should put the code to the view. views.py from .models import Post, Comment def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) snippet=models.CharField(max_length=100, default='Blog post') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.name} on {self.post}' forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body') And i dont know how to put below code from to the view to my code: from .models import Post, Comment from .forms import EmailPostForm, β¦ -
Caching a large dataframe in database
I was trying to cache a large pandas dataframe to using django.core.cache.backends.db.DatabaseCache backend into MySQL database. It works for 3 million items but not the bigger. Can I increase the maximum length for the cache value? Thanks in advance. import pandas as pd import numpy as np from django.core.cache import cache, caches cache.set('data', pd.DataFrame(np.random.rand(300,1000))) # It works cache.set('data', pd.DataFrame(np.random.rand(400,1000))) # It doesn't df = cache.get('data') df # It returns a dataframe with 300 rows Γ 1000 columns -
Unable to log in with provided credentials
I dont have any problem in registering new account (with token) when i tried to login i receive this error. Unable to log in with provided credentials. , thanks in advance who ever help me to this question. this is my serializers.py class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = Account fields = ['email', 'username', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True}, } def save(self): account = Account( email=self.validated_data['email'], username=self.validated_data['username'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account my views.py @api_view(['POST', ]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = 'successfully registered new user.' data['email'] = account.email data['username'] = account.username token = Token.objects.get(user=account).key data['token'] = token else: data = serializer.errors return Response(data) my settings.py INSTALLED_APPS = [ 'django_tables2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'rest_framework', 'rest_framework.authtoken', 'homepage', ] AUTH_USER_MODEL = 'homepage.Account' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } -
No module "AppName" error while running python manage.py
I am trying to follow this tutorial related to Django Rest Framework, on running python manage.py I am getting an error: File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'languages' My Project structure look like below: (DRF) β DRF tree . . βββ Pipfile βββ Pipfile.lock βββ api_example β βββ __init__.py β βββ asgi.py β βββ languages β β βββ __init__.py β β βββ admin.py β β βββ apps.py β β βββ migrations β β β βββ __init__.py β β βββ models.py β β βββ tests.py β β βββ urls.py β β βββ views.py β βββ settings.py β βββ urls.py β βββ wsgi.py βββ db.sqlite3 βββ manage.py settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'languages', ] -
create a folder in django with cmd the contain error like ---- OSError: [Errno 9] Bad file descriptor
'E:\DJANGO> django-admin startproject app' when i apply this to create a project folder the contain with the error like below. cmd prompt image to show the error -
Django not able to load a simple static page with static files
It is a simple static html file with only one image as a static file in the html. I have followed all the steps provided in the Django documentation, and the collectstatic command runs without any error. The project folder structure is as follows; settings.py file; STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') DEBUG = True home.html - File where the image is not loading; {%load static%} <!DOCTYPE html> <html > <head> <title>home.html</title> <h1>This is a test file</h1> </head> <body> <img src="{% static 'images/test.png' %}"> </body> </html> Output: I have tried the following; Restart server, rerun the collectstatic command Nothing worked out, What could be the issue? Please help me to resolve this issue. -
Custom model field in Django | Using both integerchoice and textarea
I'm trying to create a model that contains more than 50 fields. Each field has 4 other fields: IntegerChoice Reason for that choice Another IntegerChoice Reason for that choice I think that a custom model field to solve this is the best option, but i'm not sure if this is the way to go? I would be following the official documentation to implement this: https://docs.djangoproject.com/en/3.0/howto/custom-model-fields/ as mentioned I'm not 100% convinced it's the best way to go to make this code DRY? -
Code navigation lost in VScode with Django + Docker
I could not find the code definition using Ctrl + click when I use Docker + Django in my project, since source code are now in container. How could I configure my VScode to enable code navigation? -
302 status code in using postmant for request in django
hello guys i'm trying to write a restful program but i have a problem if a user uses this url : http://127.0.0.1:8000/dashboard/dsdproject/1/skills/ should redirect to another page this url work in browser but when i using in postman it returns 302 status code how can i fix it to see 200 status code and redirect to my goal page?!? i add that i try post and get request for both of them i have this condition. i become so thankful if someone know this question help me i cant find any solution with searching in google. its my postman request