Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Can't Find Correct Mysqlclient
I'm trying to get mysql up on a new Django project on MacOS. I used pip to intsall it. This is the output from my second attempt so that I could show the install here: python3 -m pip install mysqlclient Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: mysqlclient in /Users/curt/Library/Python/3.7/lib/python/site-packages (1.4.6) This is my init.py file: (the stack overflow editor has dropped the underscores) import mysqlclient mysqlclient.install_as_MySQLdb() PyCharm is indicating it can't find mysqlclient on line 1 and the message "Package requirement 'mysqlclient==1.4.6' is not satisfied" is displayed. I tried adding the path shown in the pip install to $PYTONPATH to no effect. Is there somewhere else I should to be setting the location of mysqlclient? -
Retrive value list of Decimal Type without class name
when I run this query in django: list(InputDataDetailItem.objects.filter(wage_detail__wage=wage).values_list('value',flat=True)) I get : [Decimal('30.00'), Decimal('0.00'), Decimal('0.00')] but I want : [30.00,0.00,0.00] How can I do this? Thank you. -
i have list of slices of DICOM image in views.py and i want to view this image in the template using Django
i'm using function in views.py that generates list of slices of DICOM image and i need away to show this image in the front end of Django app , in any python script i can show image by matplotliiip library using for each slice : plt.imshow(slice) plt.show -
'NoneType' object is not callable in Django App
I have made a product model in django. I'm able to insert products, but now i'hanving problems to get the products. When i list the products, i get all items. But when i try get only one, the restframework is giving me this error: I'm trying to acessing the product by using this url http://localhost:4444/products/1 TypeError at /products/1 'NoneType' object is not callable Request Method: GET Request URL: http://localhost:4444/products/1 Django Version: 2.2.8 Exception Type: TypeError Exception Value: 'NoneType' object is not callable Exception Location: C:\Users\vini\Documents\VirtualEnv\mystore\lib\site-packages\rest_framework\generics.py in get_serializer, line 110 Python Executable: C:\Users\vini\Documents\VirtualEnv\mystore\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\\Users\\vini\\Documents\\GitHub\\mystore-backend', 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\Scripts\\python38.zip', 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\DLLs', 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\lib', 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\Scripts', 'c:\\users\\vini\\appdata\\local\\programs\\python\\python38\\Lib', 'c:\\users\\vini\\appdata\\local\\programs\\python\\python38\\DLLs', 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore', 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\lib\\site-packages'] Server time: Sab, 15 Fev 2020 19:41:00 +0000 Model: class Product(UGCModel): class Meta: app_label = 'product' avatar = models.ForeignKey('image.Image', related_name='product_image', on_delete=models.CASCADE) # Variable to hide in store hide = models.BooleanField(default=False) # Value of product value = models.DecimalField(max_digits=6, decimal_places=2, validators=[MinValueValidator(0)]) # Name of the product title = models.CharField(max_length=150, null=False, blank=False) # Quantity of product in stock quantity = models.IntegerField(default=0, blank=False, null=False, validators=[MinValueValidator(0)]) # Discount of the product discount = models.IntegerField(default=0, validators=[MaxValueValidator(100), MinValueValidator(0)]) # description of the product resume = models.CharField(max_length=1000, blank=True) def __str__(self): return '(Product)%s' % self.uid Url: from django.urls import path from . import … -
Django — database connections are not closed after async tests
I use Django ORM inside async code. Everything works fine and all tests pass. However, DB connections do not close properly in tests. Here is an example: from asgiref.sync import sync_to_async, async_to_sync @sync_to_async def count_books(): return Book.objects.count() class FooTest(TestCase): def setUp(self): Book.objects.create(title='Haha') def test1(self): import asyncio c = asyncio.run(count_books()) self.assertEqual(1, c) def test2(self): c = async_to_sync(count_books)() self.assertEqual(1, c) Postgres error: django.db.utils.OperationalError: database "test_mydbname" is being accessed by other users Sqlite error: sqlite3.OperationalError: database table is locked: test_mydbname I've tried swapping sync_to_async with database_sync_to_async from django-channels, but this didn't change anything. How can I fix this? -
Need Advice on building Search Filters in Django Product Search Page
I have a product search page that lists all cars. I would like to know some best practices in order to achieve searching and filtering results like in this picture below. At present, I have a working code that does the job fine. But I feel am hacking instead of following the best practice. Do I need to learn Node.js to achieve this ? or Django/CSS is enough? What is the industry's best practice? -
Adding class for django_filters return an exception " django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet."
After installing django_filters and adding a filter class return an exception. " django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet." """ class ProductFilter(django_filters.FilterSet): class Meta: model = product fields = ['price', 'category', 'location', 'tags', 'pub_date'] """ -
Combining two separate forms in one Django view?
This question have been answered before, e.g here: Proper way to handle multiple forms on one page in Django So before it gets marked as a duplicate. I'll try to explain why its different. I've got three tables, Project, ProjectUser and User. ProjectUser is a join table to indicate what users belongs to what project. I'm trying to create a view that lets users update project details (e.g. name of project), and also add users to the project (which is indicated by a dropdown that shows all available users like the standard one for models with foreign keys in the django admin panel). All works fine until I'm trying to pass an id from the views to the formclass and submit. views.py class ProjectUpdateView(UpdateView): form_class = ProjectUpdateForm second_form_class = ProjectUserAddForm template_name = 'projects/project_edit.html' success_url = reverse_lazy('projects:list') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) id_ = self.kwargs.get("id") project = Project.objects.get(id=id_) if 'form' not in context: context['form'] = self.form_class() if 'form2' not in context: team = Organization.objects.get(id=project.organization_id) context['form2'] = self.second_form_class(queryset=team) # <-- here is where I wish to pass a queryset, which fails when trying to submit form2. context['project_users'] = ProjectUser.objects.filter(project__id=project.id).select_related("project") context['team'] = Organization.objects.get(id=project.organization_id) return context def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(Project, … -
sites_query = connection.execute("SELECT domain FROM django_site") psycopg2 has no attribute execute
When I try to start gunicorn, I am getting this error: File "/home/django-project/projectfolder/settings.py", line 270, in ALLOWED_HOSTS = get_allowed_hosts(DATABASES['default']) File "/home/django-project/projectfolder/allowed_hosts.py", line 16, in get_allowed_hosts sites_query = connection.execute("SELECT domain FROM django_site") AttributeError: 'psycopg2.extensions.connection' object has no attribute 'execute from .settings import * DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'projectname_settings', 'USER': '******', 'PASSWORD': '******', 'HOST': 'localhost', 'PORT': '', } } ALLOWED_HOSTS = [ "mydomain.com", ] + get_allowed_hosts(DATABASES['default']) Allowed_hosts.py def get_allowed_hosts(db_params): connection = None if db_params['ENGINE'] == 'django.db.backends.postgresql_psycopg2': import psycopg2 connection = psycopg2.connect(user=db_params['USER'], password=db_params['PASSWORD'], host=db_params['HOST'], port=db_params['PORT'], database=db_params['NAME']) elif db_params['ENGINE'] == 'django.db.backends.sqlite3': import sqlite3 connection = sqlite3.connect(db_params['NAME']) if connection is not None: sites_query = connection.execute("SELECT domain FROM django_site") sites_result = sites_query.fetchall() sites = ["." + site[0] for site in sites_result] print("Allowed hosts") print(sites) return sites -
How to remove unused CSS from plain Django project that use Bootstrap?
How to use Purgecss in plain Django project that uses Bootstrap? No webpack etc. https://github.com/FullHuman/purgecss -
How to use discord.py library to get members in a voice channel and then display in my django site?
import discord import random from discord.ext import commands client = commands.Bot(command_prefix = '.') channel = None @client.event async def on_ready(): channel = client.get_channel(677999369642836037) async def members_list(request): curMembers = [] for member in channel.members: curMembers.append(member) return render(request, "discordTool/discordTool.html", { 'members_list': curMembers, }) client.run('my token') This is my views.py of an app that supposes to show active members in a voice channel in my django site. However this doesn't work, can anyone help me? -
Footer element keeps shrink in Django templates
I have included the bootstrap footer in to my django base template (base.html) along with pagination. When I run the django server the footer appear shrink towards the left( [1]: https://i.stack.imgur.com/1XyKN.png), then when clicks on the pagination, the footer appear normal with full width (). Base.html {% load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block head_title %} Blog {% endblock head_title %}</title> <link rel="stylesheet" href='{%static "css/base.css"%}'> <style> {% block style %} #main_nav { background-color: white; box-shadow: 5px 10px 20px -20px rgba(85, 172, 238, 1); margin-left: auto; margin-right: auto; } .navbar-toggler { color: #1c2331; } #Create_Post { border-radius: 22.5px; background-color: #ffffff; border-color: black; border-width: 2px; } #Create_Post:hover { border-color: #007bff; } #tag_button { border-radius: 22.5px; background-color: #ffffff; border-color: black; border-width: 2px; } #tag_button:hover { border-color: #007bff; } #no_results { margin-left: auto; margin-right: auto; } #pagination { margin-left: auto; margin-right: auto; } #pagination-link { font-size: 15px; padding: 6px 9px; margin-right: 6px; margin-left: 6px; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; width: 50px; height: 50px; border-style: solid; border-color: black; border-width: 2px; color: black; text-decoration: none; } #pagination-link:hover { border-color: #007bff; color: #007bff; } #main_footer{ background: linear-gradient(135deg,#2a99ef 20%,#52d9e5 80%); width:1287px; } {% endblock style %} </style> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> </head> … -
How to display an empty form and form with saved data from DB on same page using Ajax, Jquery in Django
I have created a two models Template and TempData in django, where Template stores the title of template in Template model which is related to the TempData where we can store n items. The respected modelforms for the above models are below (Template is ForeignKey to TempData) class TemplateForm(forms.ModelForm): title = forms.CharField(label='', widget=forms.TextInput(attrs={'onblur':'updateTitle()','placeholder':'Title','class':'input-no-border', 'id':'js_template_title', 'alt':'rename'})) class Meta: model = Template fields = ['title'] class TemplateDataForm(forms.ModelForm): item = forms.CharField(widget=forms.TextInput(attrs={'id':'js_temp_item'})) status = forms.ChoiceField(label='', choices=CHOICES, widget=forms.Select(attrs={'id':'status', 'class':'btn-switch switch-select switch-select-button switch-select-button:hover'})) class Meta: model = TempData fields = ['item','status'] I'm able to save the Template 'title' and related n 'items' data to DB using Ajax and Jquery, but I'm not able to display list of TempDataForm with the saved data in DB using Ajax JQuery Facing Serializing issue I'm not getting any idea in displaying the form with saved data other than the one which I have followed in this question, can you suggest me a way to do this Main objective of displaying the form with save data is allow users to update the data and choices -
How do I make media files display automatically in django using s3 as storage?
I configured my s3 settings like so: DEFAULT_FILE_STORAGE = 'Bonychicken.storage_backends.MediaStorage' AWS_STORAGE_BUCKET_NAME = 'bonychicken' AWS_S3_REGION_NAME = 'us-east-2' AWS_ACCESS_KEY_ID = '<my access key id>' AWS_SECRET_ACCESS_KEY = '<my secret access key>' AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com" AWS_QUERYSTRING_AUTH = False AWS_DEFAULT_ACL = None STATIC_URL = '/static/' MEDIAFILES_LOCATION = 'media' MEDIA_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/media/" MEDIA_ROOT = f"https://{AWS_S3_CUSTOM_DOMAIN}/media/" AWS_IS_GZIPPED = True AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } My storage class is: from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): bucket_name = 'bonychicken' location = 'media' file_overwrite = False I added storages to my installed apps and boto3 is also installed. CORS Configuration is: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> </CORSConfiguration> block public access has been turned off. IAM user has permissions to the bucket. The problem is, whenever I upload a file, it is uploaded to my s3 bucket but it doesn't show on the html page. Trying to access the image url from the source code yields: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId><random letters here></RequestId> <HostId> <random letters here> </HostId> </Error> But if I go to my bucket settings and select actions and click on make public after marking the media files, everything starts working. This means for each image uploaded, I have to mark and … -
slow connection between Djongo and mongo when
My Django project connects to mongoDB with djongo ORM and everything run fast locally. But when I try connect to the remote DB server (mongo also) that contains more data than the local one the web uploading is more slower and get sometime 504 error getway timeout. Do You know what cause this? settings.py : DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': False, 'NAME': db_name, "HOST": os.environ["DB_HOSTNAME"], "tz_aware": True, } } -
Getting ORA-00918: column ambiguously defined error which try to open django admin page after upgrading to django 3.03 from 2.0
Getting django.db.utils.DatabaseError: ORA-00918: column ambiguously defined error when I try to open Django admin page. Here is the error: raise dj_exc_value.with_traceback(traceback) from exc_value File "/venomscribe/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/venomscribe/lib/python3.6/site-packages/django/db/backends/oracle/base.py", line 514, in execute return self.cursor.execute(query, self._param_generator(params)) django.db.utils.DatabaseError: ORA-00918: column ambiguously defined query is SELECT "DJANGO_ADMIN_LOG"."ID", "DJANGO_ADMIN_LOG"."ACTION_TIME", "DJANGO_ADMIN_LOG"."USER_ID", "DJANGO_ADMIN_LOG"."CONTENT_TYPE_ID", "DJANGO_ADMIN_LOG"."OBJECT_ID", "DJANGO_ADMIN_LOG"."OBJECT_REPR", "DJANGO_ADMIN_LOG"."ACTION_FLAG", "DJANGO_ADMIN_LOG"."CHANGE_MESSAGE", "AUTH_USER"."ID", "AUTH_USER"."PASSWORD", "AUTH_USER"."LAST_LOGIN", "AUTH_USER"."IS_SUPERUSER", "AUTH_USER"."USERNAME", "AUTH_USER"."FIRST_NAME", "AUTH_USER"."LAST_NAME", "AUTH_USER"."EMAIL", "AUTH_USER"."IS_STAFF", "AUTH_USER"."IS_ACTIVE", "AUTH_USER"."DATE_JOINED", "DJANGO_CONTENT_TYPE"."ID", "DJANGO_CONTENT_TYPE"."APP_LABEL", "DJANGO_CONTENT_TYPE"."MODEL" FROM "DJANGO_ADMIN_LOG" INNER JOIN "AUTH_USER" ON ("DJANGO_ADMIN_LOG"."USER_ID" = "AUTH_USER"."ID") LEFT OUTER JOIN "DJANGO_CONTENT_TYPE" ON ("DJANGO_ADMIN_LOG"."CONTENT_TYPE_ID" = "DJANGO_CONTENT_TYPE"."ID") WHERE "DJANGO_ADMIN_LOG"."USER_ID" = :arg0 ORDER BY "DJANGO_ADMIN_LOG"."ACTION_TIME" DESC FETCH FIRST 10 ROWS ONLY -
The value of array must not be a ManyToManyField
I have a problem with my models for my django project. I'm had to use a ManyToManyField to get multiple foreign key but I don't get how it correctly works. I tried to look around the internet, google my mistake but still don't know how to resolve it. Here is the code for the model: class Framework(models.Model): name = models.CharField(max_length=200) language = models.ManyToManyField(Language) version = models.CharField(max_length=20) typeOfFramework = models.ForeignKey(TypeOfProgram, on_delete=models.CASCADE) cotationOfFramework = models.IntegerField(default = 5) additionalInformation = models.ForeignKey(web,blank=True,null=True ,default = None ,on_delete=models.CASCADE) def __str__(self): template = '{0.name} {0.version} {0.language} {0.typeOfFramework} {0.cotationOfFramework}' template.format(self) and here is the code for the admin page: class FrameworkAdmin(admin.ModelAdmin): list_display = ('name', 'language', 'version', 'typeOfFramework' ,'additionalInformation','cotationOfFramework') I got this error: (admin.E109) The value of 'list_display[1]' must not be a ManyToManyField. Can anyone help me on how to understand this and make it work? Thank you all a lot! -
Why is this Django IntegerField Select not marked as required?
I have a Django form with an IntegerField and ModelChoiceField, both of which use a Select widget. my_integer_field = forms.IntegerField(widget=widgets.Select(choices=[], attrs={'autocomplete': 'off', 'class': 'fw-select'})) my_mc_field = forms.ModelChoiceField(queryset=None, empty_label=None, widget=widgets.Select(attrs={'autocomplete': 'off', 'class': 'fw-select'})) The options are populated dynamically. I've noticed that when the form is rendered, my_integer_field is not marked as required, but my_mc_field is. What is the reason for this? I can make my_integer_field required by adding required: True to the attrs, but it was my understanding that required is the default behaviour (which my_mc_field seems to confirm). I'm using Django 3.0.2. -
python manage.py shell < script.py gives EOF error when using input()
I'm running Python3.7 I have two Python scripts: print("hi") and a = input() print(a) I can successfully run the first one in a django shell with python manage.py shell < script.py The second one gives me this error: File "<string>", line 1, in <module> EOFError: EOF when reading a line Why? This doesn't happen in the PyCharm terminal but only on the Linux CLI. -
Display image on raspberry PI
I developing a basic digital signage website for displaying different kinds of images, videos, and text files. This will be integrated with Rasberry Pi as a media player that will be connected to a monitor through HDMI. The website is already implemented and installed on the raspberry, however, I couldn't display the selected images on the monitor. Anyone who can assist or guide me through this. Thanks in advance. -
How do I create an html code with a string on python to render on django template
In my views: post_image = '<div class="images slides"></div>' console.log(document.body): <body> "<div class="images slides"</div>" </body> What I want: <body> <div class="images slides"</div> </body> -
Django - specify upload path
So I have a upload form: def upload(request): if request.method == 'POST': uploaded_file = request.FILES['file'] fs = FileSystemStorage() fs.save(uploaded_file.name, uploaded_file) return render(request, 'nas/upload.html') But I am not sure where to specify where the file gets uploaded to. I would like it to come from the currently active drive, which has an attribute Drive.path -
"<Comment: >" needs to have a value for field "id" before this many-to-many relationship can be used?
I'm new to use (many-to-many) relationship, I need to allow the users can leave the comment on the user post. this site looks like Quora or StackOverflow the user should signup to get the questions field to put his question and other users whose in site can leave there comments. so, how can I continue by adding (add) in (many-to-many) or the real question is: how can I add a comment by (many-to-many) in this code if anyone help me to complete this issue, please. views.py from django.shortcuts import render, redirect, get_list_or_404 from .forms import UserAskingForm, CommentForm from .models import UserAsking, Comment from django.contrib.auth.decorators import login_required @login_required def user_asking(request): form = UserAskingForm if request.method == 'POST': form = UserAskingForm(request.POST, instance=request.user.userprofile) if form.is_valid(): asking = form.save(commit=False) asking.title = form.cleaned_data['title'] asking.question = form.cleaned_data['question'] asking.field = form.cleaned_data['field'] asking = UserAsking.objects.create(userprofile=request.user.userprofile, title=asking.title, question=asking.question, field=asking.field) asking.save() return redirect('community:user_questions') else: form = UserAskingForm() return render(request, 'community/asking_question.html', {'form': form}) return render(request, 'community/asking_question.html', {'form': form}) @login_required def user_questions(request): all_objects = UserAsking.objects.all().order_by('-title') all_objects = get_list_or_404(all_objects) return render(request, 'community/user_questions.html', {'all_objects': all_objects}) def question_view(request, user_id): my_question = UserAsking.objects.get(pk=user_id) # question number e.g '1' for user 'medoabdin' comment_form = CommentForm if request.method == 'GET': comment_form = comment_form(request.GET) if comment_form.is_valid(): comments = comment_form.save(commit=False) … -
Create project-level permissions at project initialization
When I first run manage.py migrate on a Django project, I would like the database to be initialized with some extra permissions. I have seen here that this can be done at the app level, in the apps.py files. However the permissions I would like to have are rather related to the whole project than to one of its apps. My questions are: Is it OK to define project-level permissions, or are permissions meant to always be part on an app? If project-level permissions are fine, what would be the appropriate place to define them so that they are created at project initialization? -
List all values used in a session from a variable in Django
I did a simple search view to query based on this inputs. def search(request): try: query_x = request.GET.get('query_x') query_y = request.GET.get('query_y') points_returned = request.GET.get('points_returned') distance_condition = request.GET.get('distance_condition') object_list = Points.objects.filter( geom_point__distance_lte=('POINT({0} {1})'.format(query_x, query_y), D(km=10)) ).order_by('geom_point')[:int(points_returned)] request.session['query_x'] = query_x return render_to_response('search_results.html', {'object_list': object_list}) except KeyError: return render_to_response('home.html') This search will be used many times (probably with same values) so I want to save and list all the inputs used to do the query by the user (for query_x and query_y variables). I already achieved to get the value in template, but just the last one input appear when I put {{request.session.query_x}} in the template to see the results - I need to get all values used.