Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django GraphQL django-graphql-jwt token not working in self-signed ssl server
I'm using django-graphql-jwt for GraphQL API authentication. Deployed to ubuntu server with self-signed ssl. Here is the mutation for authentication mutation { tokenAuth(email: "example@test.com", password: "password") { token } } So I used this token for authorization. Request Header: Authorization: JWT <token> Request Body: query { me { username firstName lastName email phone } } Result: { "errors": [ { "message": "'AnonymousUser' object has no attribute 'email_verified_at'", "locations": [ { "line": 2, "column": 3 } ], "path": [ "me" ] } ], "data": { "me": null } } This is correctly working in none-secure server(http). How can I fix this issue? Regards. -
Python Django: Customize Admin Startpage as analytical Dashboard
I am currently developing a mobile app using Ionic and I am using Django Admin Interface as sort of Backend for adding and editing the content of my mobile app through a MySQL Database. I currently wish to create a custom analytical dashboard for tracking the usage of the users of my mobile app in the startpage of the Django Admin. While there are some analytical packages for tracking the usage in Django, they only function for web applications. In my case I need to gather and display aggregate data from my database (Django models & not Django models) as well for other APIs. Is there a way how can I fetch data in form of SQL queries and display them in my dashboard using Python (Django)? And how can I extend the starting page of Django Admin to a full analytical dashboard with the named functionalities? I am currently struggling with this as I am new to Django. Any help is much appreciated! -
Django. IntegrityError: NOT NULL constraint failed: MyApp_song.albums_id
For starters, I just started learning Django. I'm trying to add a new song object to my album via the form. But I don't want to manually select the album (my foreign key) that I want to add a new song to. Instead, I want the value of my foreign key to be set depending on the album I'm adding a new song from. How can i do that in Django? I tried to do it like this: views.py class SongCreate(CreateView): template_name = 'music/album_form.html' # fields = ['albums', 'file_type', 'song_title', 'audiotrack', 'is_favorite'] model = Song fields = ['file_type', 'song_title', 'audiotrack', 'is_favorite'] def form_valid(self, form): album = get_object_or_404(Album, pk=self.kwargs['pk']) form.instance.album = album return super(SongCreate, self).form_valid(form) urls.py path('music/album/<int:pk>/add', views.SongCreate.as_view(), name='song-add'), models.py class Song(models.Model): albums = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=250) audiotrack = models.FileField(upload_to='media/') is_favorite = models.BooleanField(default=False) def get_absolute_url(self): return reverse('param', kwargs={'pk': self.albums.id}) def __str__(self): return self.song_title Link to add a new album <a href="{% url 'song-add' album.id %}">Add album</a> But for some reason it doesn't work, although I thought it should help. So i'm getting this error. Maybe you know what's the problem? Thanks, any help will be appreciated! -
How do I upgrade an old Django Google App Engine application to a Second Generation Cloud SQL Instance?
I have a Django application that I wrote 5 years ago, which has been running successfully on Google App Engine - until last month when Google upgraded to Second Generation Cloud SQL. Currently, I have a settings.py file, which includes a database definition which looks like this: DATABASES = { 'default': { 'ENGINE': 'google.appengine.ext.django.backends.rdbms', 'INSTANCE': 'my-project-name:my-db-instance', 'NAME': 'my-db-name', }, Google's upgrade guide, tells me that the connection name needs to change from 'my-project-name:my-db-instance' to 'my-project-name:my-region:my-db-instance'. That's simple enough. Changing this leads me to get the error InternalError at /login/ (0, u'Not authorized to access instance: my-project-name:my-region:my-db-instance') According to this question, I need to add the prefix '/cloudsql/' to my instance name. So, I changed this (and the ENGINE specification) to give: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'INSTANCE': '/cloudsql/my-project-name:my-region:my-db-instance', 'NAME': 'my-db-name', 'USER' : 'root', 'PASSWORD': '******************', }, I uploaded the modified file to Google (using gcloud app deploy). This time I get a completely different error screen, showing: Error: Server Error The server encountered an error and could not complete your request. Please try again in 30 seconds. When I look in the Logs, I see: ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb It was pointed out … -
check if the directory name is year python [duplicate]
how can I check if the directory name is a year using python ? If I have directories called 2018, 2019, 2020, test1, test2, I want to get only directories which name is a year . in this case I want directories with name : 2018, 2019, 2020 -
Filter queryset inside a form
I have one app that holds a list of work orders, and another app that holds list of parts. class Order(models.Model): parts = models.ManyToManyField(Part, blank=True) # Assosiated parts class Part(models.Model): partnum = models.CharField(max_length=20) # Part number mwos = models.ManyToManyField('mtn.Order', blank=True) # Assosiated work orders Now i want to add a button to my DetailView for order which will open a list of parts, which i will be able to add to my order. At the moment i have a created an UpdateView for my order class AddPartView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Order form_class = AddPartForm ... and a form class AddPartForm(forms.ModelForm): class Meta: model = Order fields = ['parts', ] labels = {'parts': "Parts", } def FilterList(request): qs = Part.objects.all() search_part_query = request.GET.get('search_part') if is_valid_queryparam(search_part_query): qs = qs.filter(Q(partnum__icontains=search_part_query) | Q(descr__icontains=search_part_query) ).distinct() return qs def __init__(self, *args, **kwargs): super(AddPartForm, self).__init__(*args, **kwargs) self.fields["parts"].widget = CheckboxSelectMultiple() self.fields["parts"].queryset = self.FilterList() for this template {% block content %} <form method="GET" action="."> <div class="form-row justify-content-start"> <div class="form-group col-md align-self-center"> <div class="input-group"> <input class="form-conrol py-2 border-right-0 border" type="search" placeholder="Find part" name="search_part"> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> <button type="submit" class="btn btn-primary btn-sm btn-block">Search</button> </form> <form action="{% url 'mtn:add_part' order.id %}" … -
Context in Django HttpResponse
I happen to pass by Django documentation for TemplateResponse. (My question is for HttpResponse) Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the template and context that was provided by the view to compute the response. Here it says that response object which we get from self.client.get() which is an object of HttpResponse, does not retain the context provided by view. But when I did dir(response) I could find context there. Kindly explain me the actual meaning of documentation. -
Does using pre_save or post_save slow down overall Django project?
I need to keep track of Database records count. I was wondering if using post_save or pre_save methods slow down overall Django project's performance. Question: Does using post_save or pre_save signals slow down overall Django project's performance? -
connecting button to modal with bootstrap
I need some help connecting a button which pops up a modal to submit form. this is my html before the modal (works fine and another page is rendered after button is clicked) <div class="container my-container"> <h3> Let's get started </h3> <div class="row my-row"> <h4>1. CSV file</h4> </div> <div class="row my-row"> <h4>2. There should be only two columns</h4> </div> <div class="row my-row"> <form method="post" enctype="multipart/form-data"> {%csrf_token%} <input type="file" name="document"><br> <button type="submit"> Submit</button> </form> </div> </div> I have added the modal but I now have a couple of issues <div class="container my-container"> <div class="row my-row"> <h3> Let's get started </h3> </div> <div class="modal fade" id="demo123"> <div class="modal-dialog"> <div class="modal-content"> <button type="button" class="close" data-dismiss="modal"> <span> &times; </span> </button> <div class="modal-header"> <h2 class="modal-title"> Confirm upload </h2> </div> <div class="modal-body"> <p>this is the file name</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Confirm </button> </div> </div> </div> </div> <div class="row my-row"> <h4>1. CSV file</h4> </div> <div class="row my-row"> <h4>2. There should be only two columns titled</h4> </div> <div class="row my-row"> <form method="post" enctype="multipart/form-data"> {%csrf_token%} <input type="file" name="document"><br> <button class="btn btn-primary" data-toggle="modal" data-target="#demo123"> Submit </button> </form> </div> </div> First issue I have is the "submit" button automatically makes the upload(renders to another page). How … -
Django WAMP (Apache) mod_wsgi on Windows
Im new to Django and web development. I have completed a project in development environment and now we need to deploy it in production. I have been trying to go through the deployment process using wamp on a windows virtual machine. The details are as under: OS: Windows 10 Python: 3.7.6 Webserver: Wamp 3.2 with Apache 2.4.41 mod_wsgi ver 4.7.1 (this was downloaded pre-compiled from here Im using pycharm for the development and the default python interpreter path is of system i.e. C:\Users\User\AppData\Local\Programs\Python\Python37 which includes the installed/ extracted mod_wsgi packages in site-packages. The 'Django' package is installed however within venv at C:\Users\User\TryProject\venv\Lib\site-packages I configured my files as folows: httpd-vhosts.conf: <VirtualHost *:8080> ServerName localhost WSGIPassAuthorization On ErrorLog "C:/Users/User/TryProject/TryProject.error.log" CustomLog "C:/Users/User/TryProject/TryProject.access.log" combined #WSGIDaemonProcess TryProject python-home=C:/Users/User/TryProject/venv/Lib/site-packages #python-path=C:/Users/User/TryProject/venv/Lib/site-packages #venv/Lib/site-packages" #WSGIProcessGroup TryProject WSGIScriptAlias /mysite "C:/Users/User/TryProject/TryProject/wsgi.py" #process-group=TryProject #application-group=%{GLOBAL} WSGIApplicationGroup %{GLOBAL} <Directory "C:/Users/User/TryProject/TryProject"> <Files wsgi.py> Require all granted </Files> </Directory> httpd.conf: ... LoadFile "c:/users/user/appdata/local/programs/python/python37/python37.dll" LoadModule wsgi_module "c:/users/user/appdata/local/programs/python/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/users/user/appdata/local/programs/python/python37" ... and wsgi.py import sys from django.core.wsgi import get_wsgi_application #site.addsitedir("C:/Users/User/AppData/Local/Programs/Python/Python37/Lib/site-packages") site.addsitedir("C:/Users/User/TryProject/venv/Lib/site-packages") # Add the app's directory to the PYTHONPATH #sys.path.append('C:/Users/User/TryProject') sys.path.append('C:/Users/User/TryProject/TryProject') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TryProject.settings') application = get_wsgi_application() while the apache error log file shows this group of error on every request: [Tue Apr 07 20:18:44.672498 2020] [wsgi:error] [pid 12456:tid … -
How to post in bulk in Django-Rest-Framework with a different format
My Model : from django.db import models Create your models here. from rest_framework.exceptions import ValidationError class Results(models.Model): test_taker = models.ForeignKey('users.User', null=True, related_name='testtakerId', on_delete=models.CASCADE) question_detail = models.ForeignKey('questions_detail.Questions_detail', null=True, related_name='answersId', on_delete=models.CASCADE) test_id = models.IntegerField(null=True) answer = models.CharField(max_length=255, null=True) custom_answer = models.CharField(max_length=255, null=True) What i Want to post: { "test_taker": 1, "test_id": 1, "question": [ { "question_id": 1, "answer": 2, "custom_answer": "c1" }, { "question_id": 2, "answer": 3, "custom_answer": "c2" }, { "question_id": 3, "answer": 4, "custom_answer": "c3" }, { "question_id": 2, "answer": 1, "custom_answer": "c4" } ] } Cuurently what i am doing is: In my views.py : (I am using rest_framework_bulk) class AddResult(ListBulkCreateUpdateDestroyAPIView): lookup_field = 'pk' serializer_class = ResultsSerializer def get_queryset(self): return Results.objects.all() def perform_create(self, serializer): test_taker = self.request.data['test_taker'] test_id = self.request.data['test_id'] serializer.save(test_taker=test_taker, test_id=test_id) My Serializer: class ResultsSerializer(BulkSerializerMixin,serializers.ModelSerializer): class Meta: model = Results fields = '__all__' list_serializer_class = BulkListSerializer What is happening is it just stores 1 result and that has test_taker = 1 and test_id = 1 which it takes from the outer part of the JSON. What i want is for it to store all the records in the format of [test_taker , test_id, question_id , answer, custom_answer] Thanks in advance for positive responses. -
python-social-auth redirect to the user profile in Django
I am using the wonderful python-social-authpackage, and more precisely the social-auth-app-django version since my project is using the Django Framework. Once the user is registered/logged in via any social backend, I'd like to redirect the user to their own very user profile. I know I can set a static URL in my settings.pysuch as: SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/logged-in/' But how can I dynamically redirect the user to their profile given that I know their username/slug? If I could set variables in the settings.py it'd be something like: SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/accounts/<slug:slug>/' But of course I can't do that. Is there any way I can achieve what I want? -
NameError: name 'LoginView' is not defined
I'm installing the Openstack Stein Horizon service (dashboard) following the tutorial on the site. I encounter an error due to the Django version and fix it using this explanation Switch from django string_concat to format_lazy. The next issue that appears was AttributeError: module 'django.contrib.auth.views' has no attribute 'login', which I googled and came again as a Django version incompatibility. I followed this explanation here: AttributeError: module Django.contrib.auth.views has no attribute openstack_auth/urls.py from django.conf.urls import url from django.views import generic from openstack_auth import utils from openstack_auth import views from . import views from django.contrib.auth import views as auth_views urlpatterns = [ url(r"^login/$", LoginView.as_view(), name='login'), url(r"^logout/$", LogoutView.as_view(), name='logout'), url(r'^switch/(?P<tenant_id>[^/]+)/$', views.switch, name='switch_tenants'), url(r'^switch_services_region/(?P<region_name>[^/]+)/$', views.switch_region, name='switch_services_region'), url(r'^switch_keystone_provider/(?P<keystone_provider>[^/]+)/$', views.switch_keystone_provider, name='switch_keystone_provider') ] if utils.is_websso_enabled(): urlpatterns += [ url(r"^websso/$", views.websso, name='websso'), url(r"^error/$", generic.TemplateView.as_view(template_name="403.html")) ] apache2/error.log Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/wsgi.py", line 141, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception callback, param_dict = resolver.resolve_error_handler(500) File "/usr/local/lib/python3.6/dist-packages/django/urls/resolvers.py", line 584, in resolve_error_handler callback = getattr(self.urlconf_module, 'handler%s' % view_type, None) File "/usr/local/lib/python3.6/dist-packages/django/utils/functional.py", line 80, in … -
Localhost webpage created in django is showing wrong page source code
I am following corey schafer django course using sublime text 3. After i used bootstrap template, my home page was updated. But page named 'about' is not updated. When i use view page source, it is showing wrong source code. My html code for about page is- {% extends "blog/base.html" %} {% block content %} <h1>About Page</h1> {% endblock content %} but when i press view source code it is showing the old one- <!DOCTYPE html> <html> <head> <title>Django Blog-About</title> </head> </head> <body> <h1>About page</h1> </body> </html> My home webpage using the same template got updated, but not this one. My base html file is- <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> {% if title %} <title>Django Blog-{{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <div class="container"> {% block content %} {% endblock %} </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> -
Celery worker permission denied
To be quite honest I do not really know what I am doing ;) Recently I installed Mayan EDMS in a chroot on my NAS. So far I got it working ... at least I can login and so forth. But I cannot upload any files and I guess this has to do with celery (which I did not knew about before). Because I am in a chroot I cannot use supervisord for these celery workers and I started them from the command line. e.g. nice -n 19 /path/to/my/mayan-edms/bin/celery worker -A mayan -Ofair -l ERROR -Q statistics,tools,common_periodic,parsing,document_states,mailing,ocr -n mayan-worker-slow.@%h --concurrency=1 But this throws an error: -------------- mayan-worker-slow.@DiskStation213 v4.3.0 (rhubarb) ---- **** ----- --- * *** * -- Linux-3.2.40-armv7l-with-glibc2.17 2020-04-07 15:15:07 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: mayan:0x41cc8d00 - ** ---------- .> transport: redis://:**@127.0.0.1:6379/0 - ** ---------- .> results: redis://:**@127.0.0.1:6379/1 - *** --- * --- .> concurrency: 1 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> common_periodic exchange=common_periodic(direct) key=common_periodic .> document_states exchange=document_states(direct) key=document_states .> mailing exchange=mailing(direct) key=mailing .> ocr exchange=ocr(direct) key=ocr .> parsing exchange=parsing(direct) key=parsing .> statistics exchange=statistics(direct) key=statistics … -
how to use password field in serializers.py ..password2=serializers.Charfield(serializers.widget=PasswordInput()) doesnot work as it use
AttributeError: module 'rest_framework.serializers' has no attribute 'PasswordInput' serializer.py : from rest_framework import serializers from django.contrib.auth.models import User class SampleSerializer(serializers.ModelSerializer): password2 = serializers.CharField(widget=serializers.PasswordInput()) class Meta: model = User fields = ['username','email','password'] -
Is there any way to use tika library on pythonanywhere?
I'm working on a parsing problem and have used tika library in local system to read pdf documents. As now I'm deploying my parser on the web, I'm not allowed to use tika library on pythonanywhere server. File "/home/mubasharnazar/mysite/server.py", line 114, in read_pdf file_data = parser.from_file(file) File "/home/mubasharnazar/.virtualenvs/flaskk/lib/python3.7/site-packages/tika/parser.py", line 40, in from_file output = parse1(service, filename, serverEndpoint, headers=headers, config_path=config_path, requestOptions=requestOptions) File "/home/mubasharnazar/.virtualenvs/flaskk/lib/python3.7/site-packages/tika/tika.py", line 338, in parse1 rawResponse=rawResponse, requestOptions=requestOptions) Any solution? -
Django command running a shell script
I have an app that deletes files that have been uploaded more than one month ago. from django.core.management.base import BaseCommand, CommandError from blacklist_app.models import EntradaHistorial from datetime import datetime, timedelta import pytz, subprocess, os from blacklist.settings import BASE_DIR class Command(BaseCommand): help = "Procesa archivos en cola para ser movidos al servidor de destino acorde a la configuración" tmp = os.path.join(BASE_DIR, 'blacklist_app/tmp') excel = os.path.join(BASE_DIR, 'blacklist_app/uploaded_files/excel') json = os.path.join(BASE_DIR, 'blacklist_app/uploaded_files/json') mv = 'mv {}/{} {}' rm = 'rm {}/{}' def handle(self, *args, **options): max_date = datetime.now() + timedelta(weeks=-1) preg = "*_{}*".format(max_date.strftime('%Y%m')) #Se mueven los archivos que deben ser conservados a la carpeta temporal self.mv_and_rm(self.excel, preg) self.mv_and_rm(self.json, preg) max_date.replace(day=1, hour=0, minute=0, tzinfo=pytz.UTC) #Actualiza los valores de los archivos borrados EntradaHistorial.objects.filter(fecha__lt=max_date, archivo_borrado=False).update(archivo_borrado=True) # Mueve los archivos a la carpeta temporal, borra los archivos que deben ser borrados y # mueve de vuelta los archivos que deben ser conservados def mv_and_rm(self, dir, preg): move = self.mv.format(dir, preg, self.tmp) self.run_command(move) rm = self.rm.format(dir, '*') self.run_command(rm) move_back = self.mv.format(self.tmp, preg, dir) self.run_command(move_back) def run_command(self, command): sh = os.path.join(BASE_DIR,'blacklist_app/management/commands/run_command.sh') call = "sh {} '{}'".format(sh, command) print(subprocess.check_output(call)) In the same directory I have the script run_command.sh #!/bin/sh $1 This command should run in the crontab on the first … -
Django per-view based caching only for non-logged in users
I am working with per-view based caching that Django provides. However I want to disable cache when the user is logged in. What is the best approach to achieve this from urls.py ? https://docs.djangoproject.com/en/3.0/topics/cache/#the-per-view-cache from . import views from django.views.decorators.cache import cache_page urlpatterns = [ path('', cache_page(60 * 15)(views.HomeView)), ] -
how to get unit and price from selectable dropdown list
hi I am new in Django I am creating order app.in new order form i want to get price and unit from product table.when i select a product from dropdown list it will get price and unit from product table selected product.here is my my code model.py class Product(models.Model): product_name = models.CharField(max_length=200) unit = models.TextField() price = models.IntegerField() active = models.IntegerField(default='1') def __str__(self): return self.product_name class Order(models.Model): name = models.CharField(max_length=200) delivery_date = models.DateField(blank=True) product_id = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() unit = models.CharField(max_length=50) price = models.IntegerField() amount = models.IntegerField() view.py def new(request): if request.POST: form = OrderForm(request.POST) if form.is_valid(): if form.save(): return redirect('/', messages.success(request, 'Order was successfully created.', 'alert-success')) else: return redirect('/', messages.error(request, 'Data is not saved', 'alert-danger')) else: return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger')) else: form = OrderForm() return render(request, 'new.html', {'form': form}) form.py class OrderForm(ModelForm): product_id = forms.ModelChoiceField(queryset=Product.objects.filter(active='1'), empty_label='') delivery_date = forms.DateField(required=True) quantity = forms.IntegerField(initial=1) price = forms.IntegerField(initial=0) class Meta: model = Order fields = ['name', 'delivery_date', 'product_id', 'unit', 'quantity', 'price', 'amount'] class ProductForm(ModelForm): class Meta: model = Product fields = ['product_name', 'unit', 'price'] new.html <form class="form" role="form" action="" method="post"> {% csrf_token %} <div class="row"> <div class="col-sm-6"> <header>Customer Info</header> <div class="form-group floating-label"> {{ form.name | add_class:'form-control' … -
inputting algorithms to edit django model data
I have a Django project where users can input stings and images similar to a blog like twitter or reddit. The data will be stored in models.py. as such: class Post(models.Model): body = models.TextField(max_length=5000, null=False, blank=False) image = models.ImageField(upload_to=upload_location, null=True, blank=True) then in forms class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = ['body', 'image'] and in views: def view(request, slug): context = {} post = get_object_or_404(Post, slug=slug) context['post'] = post return render(request, 'post/post.html', context) I used Conda to write an algorithm that edits the input photos in a unique way (for example a watermark) but I'm not sure where in my Django project to try an incorporate the algorithm. Forms.py? Models.py? after the data manipulation I would want to create a second views.py so that I could have something like this: def view2(request, slug): context = {} post2 = get_object_or_404(Post2, slug=slug) context['post2'] = post2 return render(request, 'post2/post2.html', context) I was thinking I should create a form.py class roughly like the following: class EditPostForm(forms.ModelForm): class Meta: model = Post fields = ['body', 'image'] def edit(self, commit=True): post.body = self.cleaned_data['body'] post.image = self.cleaned_data['image'] #manipulate img data #output new img and then create a view.py class roughly like the following: def new_post_view(request, … -
Return ManyRelatedManager values in template
I'm new to programming so i'm sure there's an obvious simple solution to this. I have two models (in separate apps): class Order(models.Model): parts = models.ManyToManyField(Part, blank=True) class Part(models.Model): mwos = models.ManyToManyField('mtn.Order', blank=True) The problem is when i render Order in DetailView in template i can't get the queryset of associated values. If i just put {{ order.parts }} i get my_app.Part.None. And if i do this class OrderDetailView(LoginRequiredMixin, DetailView): model = Order def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['parts'] = Part.objects.filter(mwos=self.object.id) return context I get {{ parts }} rendered as empty queryset <QuerySet []>. -
Is there any way to fetch images with date specified and display according to date in django?
I am trying to create a e-newspaper app with django. I which i upload data in pdf format with date and convert the data to JPEG and save the to folder with the date specified format. I am trying to get the images for date specified only (images with particular date will be displayed on that date only ).But having no better luck with fetching the particular data. models.py class City(models.Model): cityid =models.AutoField(primary_key=True) name = models.CharField( max_length=50) class Meta: verbose_name = ("City") verbose_name_plural = ("Cities") def __str__(self): return self.name class DailyFeed(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) date =models.DateField(auto_now=False, auto_now_add=False) files = models.FileField(max_length=100) views.py def create_dailyfeed(request): folder='date/' image = 'images' if request.method == 'POST' : #Get All Files files = request.FILES.getlist('files') form = DailyFeedForm(request.POST, request.FILES) if form.is_valid(): inst = form.save(commit=False) # Add Date DAte date = inst.date #Add City DATA city = inst.city.name # Date Data date1 = date.strftime("%Y/%m/%d") folder1 = '{}/{}/{}'.format(folder,city,date1) fs = FileSystemStorage(location=folder1) media = '{}/{}/{}'.format(image,city,date1) fs1 = FileSystemStorage(location = media) for f in files: filename = fs.save(f.name, f) file_url = fs.url(filename) filename1 = fs1.save(f.name, f) file_url1 = fs1.url(filename) #media FIle DIrectory #COnvert to JPG pages = convert_from_path('{}/{}'.format(folder1,f.name), 200) for page in pages: page.save('{}/{}.jpg'.format(media,f.name[:-4]), 'JPEG') inst.save() return redirect('/', messages.success(request, 'Paper … -
Customizing Django's implicit ManyToManyField's "through" table?
I have two models which are joined through a ManyToManyField. I did not specify a through table manually, so Django created one implicitly. Can I now somehow customize that through table, specifically to alter its ___str___ function? Basically, I'm trying to override the "row title" a TabularInline admin class uses, like in these questions: Remove or edit object name in admin.TabularInline How to override the str method when rendering StackedInline field? https://groups.google.com/d/topic/django-users/d0QPIAklSug But I'd like to avoid customizing the template or creating a "relationship table" explicitly, as right now it's managed by Django. -
I cant add a django tag {% csrf_token %} to html created using format_html. The tag keeps returning as plain text
i have a table column as follows actioncolumn = tables.Column(verbose_name="action",orderable=False,empty_values=[]) def render_actioncolumn(self): edit_btn=''\ ' edit '\ '' delete_btn=''\ 'delete'\ '' return format_html('{{% csrf_token %}} ' + edit_btn +' '+ delete_btn + ' ') the tag {% csrf_token %} reurns as plain text. the extra curlies in {{% csrf_token %}} are to work around the special charcters used in strings