Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Query for Intermediate table in Django
Hello how are you? I want to ask you a query on intermediate tables, with a problem that I cannot solve and that I thought was not that difficult. I have a "many to many" relationship between two tables (Sample, Test) using the classes: class Sample (models.Model): tests = ChainedManyToManyField ( 'Test', horizontal = True, chained_field = 'matrix', chained_model_field = 'matrix', through = 'SampleTests' ) class Test (models.Model): test = models.CharField (max_length = 255, blank = True, null = True) class SampleTests (models.Model): test = models.ForeignKey ('Test', models.DO_NOTHING) sample = models.ForeignKey ('Sample', models.DO_NOTHING) class Meta: verbose_name = "Result" verbose_name_plural = "Results" In the Class SampleTests, I put the "verbose_name_plural =" Results "" because I plan to put one more field to put the result of each test in it. As I want to work everything in the Django admin, I configured the admin.py adding: admin.site.register (SampleTest), so in this way I can enter from the menu to this area of "Results" (SampleTest class). But when I click, it throws me this error: "django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'applications.lab.admin.SampleAdmin'>: (admin.E013) The value of 'fields' cannot include the ManyToManyField 'tests', because that field manually specifies a relationship model. … -
How do I make custom filters work in django_filters?
So I've made this custom filter in filters.py with Django-filters and when I'm submitting the "YEARCHOICE" from templates, the page refreshes but it doesn't work. I think I'm having a problem with my "year_filter_method" also I want my pagination and filter system to work together. Any help would be really appreciated. Cheers! *Note it doesn't work with or without pagination. models.py from django.db import models import datetime YEAR_CHOICES = [] for r in range(2000, (datetime.datetime.now().year + 1)): YEAR_CHOICES.append((r, r)) class Music(models.Model): Song = models.CharField(max_length=100, blank=False) Year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) def __str__(self): return self.Song filters.py import django_filters import datetime class MusicFilter(django_filters.FilterSet): YEARCHOICES = [] for r in range(2010, (datetime.datetime.now().year + 1)): YEARCHOICES.append((r, r)) year_filter = django_filters.ChoiceFilter(label="Year", choices=YEARCHOICES, method="year_filter_method") def year_filter_method(self, queryset): expression = YEARCHOICES return queryset.filter(expression) views.py def music_page(request): #pagination & filter music = Music.objects.all().order_by('-id') music_filter = MusicFilter(request.GET, queryset=music) paginator = Paginator(music, 6) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) try: music = paginator.page(page_number) except PageNotAnInteger: music = paginator.page(1) except EmptyPage: music.paginator.page(paginator.num_pages) return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter}) filters.html {% load static %} <link rel="stylesheet" href="{% static 'main/filter.css' %}" type="text/css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <div class="container"> <form method="get"> <span class="label">{{filter.form}}</span> <span class="btn-search-handler"><button id="search_btn_id" type="submit">Search</button></span> </form> </div> music.html {% … -
Specify __str__() Representation in Django Admin list_display
Not sure if this is a good way to do things (this is more of a technical question), but what if I have a Django model with __str__ function that combines several fields: def __str__(self): return f'{self.field0} {self.field1} {self.field2}' In the admin, I might have the list_display like so: list_display = ['field0', 'field1'] How do I specify this to use the object representation returned by the __str__ function? list_display = [<__str__() representation>, 'field0', 'field1'] By default, if you don't specify list_display in the admin, it'll give me what I want. Can't I have both? -
Save the data of current logged user in django
I am a newbie in django and I have a question about how I can save and show only the data of logged user - since my application is multi-tenant. my view class ProjetoCreate(CreateView): model = Projeto fields = ['nomeProjeto', 'descricao', 'dtInicio', 'deadline', 'nomeSprint', 'status', ] def get_queryset(self): logged_user = self.request.user return Projeto.objects.filter(User=logged_user) my model class Projeto(models.Model): nomeProjeto = models.CharField(max_length=20) descricao = HTMLField() dtInicio = models.DateField(auto_now=False, auto_now_add=False) deadline = models.DateField(auto_now=False, auto_now_add=False) nomeSprint = models.CharField(max_length=30) status = models.CharField(max_length=20) Thank you very much! -
Django: Uploading a CSV file to AWS S3
We have a Django application that needs to create a csv file on user demand and upload it to AWS S3. We have a function that creates an HttpResponse object response with content_type="text/csv" We have tried a number of things: boto3: s3 = boto3.client("s3") s3.put_object(Body=response.content, Bucket="my-bucket", Key="file_path_and_name.csv") This worked in my local machine, but when deployed to Google App Environment, we got an error that said boto3 could not find credentials. The AWS credentials are in our app settings file. (How would it work on my local machine if we didn't?) django-storages: We have successfully used storages to allow users to download files from this same s3 bucket, within the same app (both locally and deployed). So I thought I would give it a try: storage = S3Boto3Storage() storage.save("file_path_and_name.csv", response.content) This produced the error: AttributeError: 'bytes' object has no attribute 'seek' This is because the save method in S3Boto3Storage calls content.seek(0, os.SEEK_SET) So... Does that mean S3Boto3Storage cannot take a bytestring input file, like boto3 does? (I thought the S3Boto3Storage backend was built right on top of boto3?) I tried io.StringIO(response.content.decode("utf-8")) but I got another error that said the string needed to be encoded before it was hashed. At that … -
Trying to "pip install reportlab==3.0" and I get a crazy long error with include header <string.h>
I am trying to pip install reportlab==3.0 and I am not having any luck getting past this error. Can someone tell me what I am missing? The latest version of reportlab installs okay but I can't use that. I have tried easy_install and all versions. It seems that < 3.0 I will get the same error but with > 3.0 I am okay. I have also made sure my headers are linked. It looks like towards the end there is even some javascript errors? This has had me stumped #Attempting install of _rl_accel & pyHnj #extensions from '/private/var/folders/x6/wyq9wg250c7d7s933sp1fgtw0000gn/T/pip-build-L1Xdbd/reportlab/src/rl_addons/rl_accel' ################################################ ################################################ #Attempting install of _renderPM #extensions from '/private/var/folders/x6/wyq9wg250c7d7s933sp1fgtw0000gn/T/pip-build-L1Xdbd/reportlab/src/rl_addons/renderPM' will use package libart 2.3.12 # installing without freetype no ttf, sorry! # You need to install a static library version of the freetype2 software # If you need truetype support in renderPM # You may need to edit setup.cfg (win32) # or edit this file to access the library if it is installed ################################################ Standard T1 font curves already downloaded running install running build running build_py creating build creating build/lib.macosx-10.15-x86_64-2.7 creating build/lib.macosx-10.15-x86_64-2.7/reportlab copying src/reportlab/rl_config.py -> build/lib.macosx-10.15-x86_64-2.7/reportlab copying src/reportlab/__init__.py -> build/lib.macosx-10.15-x86_64-2.7/reportlab copying src/reportlab/rl_settings.py -> build/lib.macosx-10.15-x86_64-2.7/reportlab creating build/lib.macosx-10.15-x86_64-2.7/reportlab/graphics creating build/lib.macosx-10.15-x86_64-2.7/reportlab/graphics/charts copying src/reportlab/graphics/charts/slidebox.py -> build/lib.macosx-10.15-x86_64-2.7/reportlab/graphics/charts … -
Paramiko stdout.readlines() is too slow
I am using Paramiko in my Python & Django code to execute command. Here is my code: client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(<host>, username=<username>, password=<password>) stdin, stdout, stderr = client.exec_command("curl -X POST http://127.0.0.1:8080/predictions -T image.jpg") lines = stdout.readlines() The execution time of stdout.readlines() is 0.59 for each command. This is not acceptable time for my close-to-real time system. Could anyone give any suggestion to make reading process faster? Best. -
Python Flask and Ajax forms
trying to post a flask-wtf form through ajax. I believe I have narrowed it down to the error being in the data variable but not sure. I would like to ideally send the whole form through ajax using flask-wtf. Ajax Call <script > $(document).on('click', '#click-btn-post-comment-{{ post.id }}', function(event) { var csrf_token = "{{ csrf_token() }}"; event.preventDefault(); $.ajax({ url: "{{ url_for('create.createcommentquick', postid=post.id) }}", type: "POST", contentType: 'application/json;charset=UTF-8', data: $('subpostcommentform-{{ post.id }}').serialize() , headers: { "X-CSRFToken": csrf_token, }, success: function(data) { if (data.result == 'success') { $('div#success_post_' + data.thepostid).append(data.commentbody); return data; } else { console.log(data) } }, error: function() { }, }); event.preventDefault(); }); </script> My Form - Please note its in a loop! {% if subpostcommentform %} {% include 'common/js/post/quick_post.html' %} <div class="col-12 p-0 m-0 border-top border-dark pt-1"> <form class="p-0 m-0" method="POST" id="selectDevice" action="{{ url_for('create.createcommentquick',postid=post.id) }}" id="subpostcommentform-{{ post.id }}"> {{ subpostcommentform.csrf_token }} <div class="form-group row w-100 p-0 m-0 "> <div class="col-1 p-0 m-0"> {% if current_user.profileimage %} {% if current_user.profileimage == '' %} <img src="{{ url_for('static', filename='images/noprofile.png') }}" style="width:30px;height: 30px" > {% else %} <a href="{{ url_for('profile.main', user_name=current_user.user_name) }}"> <img alt="{{ url_for('static', filename='images/noprofile.png') }}" class="img-responsive" src="{{ url_for('common.profile_image', filename=current_user.profileimage) }}" style="width:30px;height: 30px"> </a> {% endif %} {% endif %} </div> <div class="col-9 … -
Why do I get an IntegrityError when calling Django's create_user helper function?
The current Django doc on Creating users says that the following helper function can be used to create a user: >>> from django.contrib.auth.models import User >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword') But when I run this code in the Python shell I get this error: django.db.utils.IntegrityError: null value in column "last_login" violates no-null constraint DETAIL: Failing row contains (7, <hashed password>, null, f, john, ... Is the documentation incorrect? I understand that the User object contains a required last_login field but the documentation seems to imply that this helper function will take care of populating it. -
is there a way to prevent HTML input from taking some set of values, e.g (1,4,5,6,17)
I need to have some number input that takes any number except some specific set of numbers -
The right way to declare choices for django-form
I wonder what's the best way to set choices for forms.ChoiceField in Django. I need a form which first will get the set of choices using SQL query (done with that) and then display it to the user. The problem with my solution is that I have the query in forms.py and it only updates once when I run the server. Any ideas how to make it update every time the form itself renders for the user? -
how to turn off text overflow in rest framework
HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "title": "test title two", "description": "test description two", "paragraph": "test paragraph test paragraph \r\ntest paragraph test paragraph \r\ntest paragraph test paragraph \r\ntest paragraph test paragraph \r\n\r\ntest paragraph test paragraph \r\ntest paragraph test paragraph \r\n\r\n\r\ntest paragraph test paragraph \r\ntest paragraph test paragraph \r\ntest paragraph test paragraph \r\ntest paragraph test paragraph \r\n\r\ntest paragraph test paragraph \r\ntest paragraph", "author": "admin", "date": "2020-10-19T22:31:47.719276Z" } Using APIView class to view the content. I would like the "paragraph" not to overflow the text box, is there a way I could get the result something like this. "description": "test description two", "paragraph": test paragraph test paragraph test paragraph test paragraph test paragraph test paragraph .......... ............ "author": "admin", "date": "2020-10-19T22:31:47.719276Z" -
I can't create an virtual enviroment, because i have some problems with python archives
My english is not very well, so sorry about that. Python 3.8 Hello everyone, in my journey to learn Django and Kivy, i needed the virtual enviroments. When i try to create a virtualenv for Kivy, everything went well, but with Django... I have some problems inside this files: via_app_data.py via_app_data\pip_install\base.py Yes, INSIDE this files, i not understand because my paths are in the correctly directories, everytime i try to create a virtual enviroment, this message appears: User@User-PC MINGW32 ~/plzwork $ virtualenv new_env RuntimeError: failed to build image pip because: Traceback (most recent call last): File "c:\users\user\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\via_app_data.py", line 58, in _install installer.install(creator.interpreter.version_info) File "c:\users\user\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 46, in install for name, module in self._console_scripts.items(): File "c:\users\user\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 116, in _console_scripts entry_points = self._dist_info / "entry_points.txt" File "c:\users\user\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 103, in _dist_info raise RuntimeError(msg) # pragma: no cover RuntimeError: no .dist-info at C:\Users\User\AppData\Local\pypa\virtualenv\wheel\3.8\image\1\CopyPipInstall\pip-20.2.3-py2.py3-none-any, has pip -
Django Models descending/nested query
I'm having trouble understanding how to use the table/model structure in Django to perform useful queries. What I'm trying to do is: given the primary key of a Show object, get a set of all the characters in the show. My models below: class Location(models.Model): identifier = models.CharField(max_length=200) def __str__(self): """String for representing the Model object.""" return self.identifier class Character(models.Model): identifier = models.CharField(max_length=200) def __str__(self): """String for representing the Model object.""" return self.identifier class Show(models.Model): name = models.CharField(max_length=200) shorthand = models.CharField(max_length=2, unique=True) def __str__(self): """String for representing the Model object.""" return self.shorthand class Season(models.Model): number = models.IntegerField() show = models.ForeignKey(Show, on_delete=models.SET_NULL, null=True, related_name="seasons") class Meta: unique_together = (("number", "show")) def __str__(self): """String for representing the Model object.""" return (str(self.show) + "s" + str(self.number)) class Episode(models.Model): number = models.IntegerField() season = models.ForeignKey(Season, on_delete=models.SET_NULL, null=True, related_name="episodes") class Meta: unique_together = (("number", "season")) def __str__(self): """String for representing the Model object.""" return (str(self.season) + "ep" + str(self.number)) class Scene(models.Model): number = models.IntegerField() character = models.ManyToManyField(Character, related_name="scenes") location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, related_name="scenes") episode = models.ForeignKey(Episode, on_delete=models.SET_NULL, null=True, related_name="scenes") class Meta: unique_together = (("number", "episode")) def __str__(self): """String for representing the Model object.""" return (str(self.episode) + "sc" + str(self.number)) This seems basic enough, but … -
Django: Redirect to the referring page (not the current form) when an UpdateView fails validation and is then Canceled?
My Django application allows a user to navigate to an Update Form (UpdateView) from multiple locations in the application. Currently, if the form is saved successfully I can redirect without a problem to the referring page by saving request.META.HTTP_REFERER in a hidden field in the template and retrieving it in form_valid. I can leverage the HTTP_REFERER data in MOST, but not ALL cases. One of those is the following scenario: My user navigates to the FORM A from Page X (HTTP_REFERER is set to Page X) FORM A is submitted and does not pass validation (HTTP_REFERER is now set to FORM A instead of Page X because indeed it has self-refered.) My user clicks Cancel (they are redirected back to FORM A instead of Page X) Is there a way to capture the Cancel event before it is processed and perform some logic so my user gets referred back to Page X instead of being stuck in the form? -
How to link CSS to HTML file for Email Sending in a Django Project
I trying to figure out a way to link CSS to an email html for sending. I have used inlinecss but it didn't work out due to errors in locating the CSS file in static. My question is there any way to add CSS to my HTML email other than Inlinecss In my template I have used using Inlinecss: {% load inlinecss %} {% inlinecss "/css/bootstrap.css" %} TEXT {% endinlinecss %} Here is the complete path of the CSS file: C:\Users\User\Desktop\Project\static_in_env\css\bootstrap.css After debugging I found that the reason is due to [Errno 2] No such file or directory: 'C:\\Users\\User\\Desktop\\static_root\\css\\bootstrap.css' Here is the files structure: # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(VENV_PATH, 'static_root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Any ideas to help link CSS to an email html for sending -
How can we add more than 3 authers field for a single article? in Django models
I created a magzine model in django. But their are more than three authors of a magzine. I have written below code for three authors. If I write the code of two or three author for a single magzine then it is looks somewhat good. But if I make for more than three authors then it will looks very bad. Now I am confused, Is the method that I have created is wrong? And if it is wrong then how should I write it? author_name1 = models.CharField(max_length=300, blank=True) designation1 = models.CharField(max_length=100, blank=True) author_pic1 = models.ImageField(upload_to="authorpic", blank=True) author_detail1 = models.TextField(max_length=1000, blank=true) author_name2 = models.CharField(max_length=300, blank=True) designation2 = models.CharField(max_length=100, blank=True) author_pic2 = models.ImageField(upload_to="authorpic", blank=True) author_detail2 = models.TextField(max_length=1000, blank=true) author_name3 = models.CharField(max_length=300, blank=True) designation3 = models.CharField(max_length=100, blank=True) author_pic3 = models.ImageField(upload_to="authorpic", blank=True) author_detail3 = models.TextField(max_length=1000, blank=true) -
How can i set pagination dynamically in Django Rest Framework?
I made an API endpoint using Django Rest Framework, it can be filtered according to two parameters. I'm trying to do the following: when there is no filter, it should retrieve x number of records, while when there is one or more filter, it needs to retrieve more records. So basically i need to change the pagination if there are filters. Here is what i tried: class My_View(viewsets.ModelViewSet): http_method_names = ['get'] serializer_class = My_Serializer pagination_class = StandardResultsSetPagination def get_queryset(self): valid_filters = { 'Name': 'Name', 'Date': 'Unix__gte', } filters = {valid_filters[key]: value for key, value in self.request.query_params.items() if key in valid_filters.keys()} if len(filters) == 0: pagination_class = StandardResultsSetPagination else: pagination_class = LargeResultsSetPagination queryset = My_Model.objects.filter(**filters) return queryset What this code what supposed to do is to set a standard pagination of 100 if there isn't a filter, and 200 if there are filters. This code doesn't work, the pagination will always be set to StandardResultsSetPagination, and it doesn't get changed. I think it's because get_queryset is called after the pagination is set, so it can't be set again later. Is there any way to do that? Thanks in advance! -
Error: Using the URLconf defined in mysite.urls
I am receiving an error when I open http://127.0.0.1:8000/v1/. I am following a beginner Django tutorial: https://www.youtube.com/watch?v=UxTwFMZ4r5k&ab_channel=TechWithTim I come across this error when I go to http://127.0.0.1:8000/v1/: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ [name='index'] The current path, v1, didn't match any of these. I appreciate your time to look over my code and offer any suggestions and clarification. Desktop/django_tutorial/mysite/main/views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(response): return HttpResponse("<h1>It's just David!</h1>") def v1(response): return HttpResponse("<h1>View 1!</h1>") Desktop/django_tutorial/mysite/main/urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("v1/", views.v1, name="views 1"), ] Desktop/django_tutorial/mysite/mysite/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.urls")), ] I reviewed similar issues that have been posted on this website. However, the other posts were about older Django versions. I appreciate further clarification on this issue. Thank you. -
how to install and configure postgresql and django in the same dockerfile
I need to install and configure postgresql and django in one container, I can't use docker-compose because the hosting doesn't have support for docker-compose. i try of following but I get this error This is my configure postgres in settings.py -
How can I host my Django website on a local server?
I have created a website with Django, running locally in a linux virtual machine on ip adress 192.168.0.111:8000. Now I want to make this website available for the public, hosted on my own machine. I have a webproxy (NginxProxyManager) running on my server on ip adress 192.168.0.118:7818 which handles all my other static websites. I can route my domain name https://django.example.com to 192.168.0.111:8000 in my webproxy and everything works in DEBUG = True, but i know this is not the way to do it, and DEBUG = False does not serve static files properly. How can i do this? All websites about this topic are takling about publishing to Heroku or something else, but i want to host it locally. Thank you! -
Django ".widget.attrs.update" with NO effect
I have a ModelForm with the following init method: def __init__(self, *args, **kwargs): super(FragebogenForm, self).__init__(*args, **kwargs) self.fields['birth_date'].widget.attrs.update({'type': 'date'}) This doesn't change the type attribute of the input tag, although it should according to the documentation (ctrl + f -> "Or if the field isn’t declared directly on the form"). If I change it to e.g. .widget.attrs.update({'placeholder': '12.12.1999'}) it works, the new placeholder appears on the page. Only setting the type to date does not work, but why? -
docker multi stage build fails when trying to add another package
I am trying to add additional packages to saleor but I can't get docker to build the image. I want it to work but docker saleor service fails to build and returns an error: ModuleNotFoundError: No module named 'stream_django' ERROR: Service 'saleor' failed to build : The command '/bin/sh -c SECRET_KEY=dummy STATIC_URL=${STATIC_URL} python3 manage.py collectstatic --no-input' returned a non-zero code: 1 I think the error occurs due to whatever is being compiled with the package not being copied over to the final build but I am brand new to dev and am too inexperienced to fix it. So any help would be appreciated dockerfile FROM python:3.8 as build-python RUN apt-get -y update && apt-get install -y gettext \ && apt-get clean && rm -rf /var/lib/apt/lists/* COPY pyproject.toml /app/ WORKDIR /app RUN pip install poetry RUN poetry config virtualenvs.create false RUN poetry install FROM python:3.8-slim ARG STATIC_URL ENV STATIC_URL ${STATIC_URL:-/static/} RUN groupadd -r saleor && useradd -r -g saleor saleor RUN apt-get update && apt-get install -y libxml2 libssl1.1 libcairo2 libpango-1.0-0 libpangocairo-1.0-0 libgdk-pixbuf2.0-0 shared-mime-info mime-support && apt-get clean && rm -rf /var/lib/apt/lists/* COPY . /app COPY --from=build-python /usr/local/lib/python3.8/site-packages/ /usr/local/lib/python3.8/site-packages/ COPY --from=build-python /usr/local/bin/ /usr/local/bin/ WORKDIR /app RUN SECRET_KEY=dummy STATIC_URL=${STATIC_URL} python3 manage.py collectstatic … -
Creating a form instance in aview and then saving it gives a 500 Internal Server Error
This is my current view and because of using AJAX, the array sent to the view isn't in the right format so I'm using stringify to fix all of that. The problem is that I can't change the fields value on the existing form so I decided to create a new form. if request.method == 'POST': form = SubscriberForm(request.POST) category = json.loads(request.POST.get('category')) frequency = json.loads(request.POST.get('frequency')) formNew = SubscriberForm(form['email'], form['country'], category, frequency) This doesn't seem to work and I'm just getting a 500 Internal Server Error. -
LIST VARIABLE OF DJANGO OBJECTS
Is there a way to create a list variable in javascript of Django Model objects? I have a Project Model and I have several Project objects. I'd like to create a list of those objects in javascript.