Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Java rest client framework for Django QuerySet syntax
There are a bunch of public rest APIs built with Django which expose Django's QuerySet filtering and field selecting features For example: https://api.hubapi.com/content/api/v2/pages?hapikey=demo&translated_from_id__is_null&name__icontains=test&order=created&property=id&property=name&property=current_state&property=translated_content where: &name__icontains=test means case insensitive lookup by the field name which value contains subsgtring test &translated_from_id__is_null means that field translated_from_id is not null &property=id&property=name&property=current_state means that only these declared properties should be returned Other examples: https://www.ebi.ac.uk/chembl/api/data/molecule?molecule_properties__full_mwt__range=200,500 https://www.ebi.ac.uk/chembl/api/data/molecule?molecule_chembl_id__in=CHEMBL25,CHEMBL941,CHEMBL1000 Is there any Java framework which provides high-level abstractions above this query syntax? -
Python/Django Saving m2m with Through
The code below is stripped down to illustrate the issue. While there are things that you may want to say "why would you do this anyway", there is probably a reason in the larger context :) Here is my view: class SubmissionCreate(CreateView): model = Submission fields = '__all__' template_name_suffix = '_create_form' success_url = '/' Here is the relevant models.py code: def custom_filename(instance, filename): author = instance.publishers[0] return 'papers/{0}.pdf'.format(author.pseudonum) class Submission(models.Model): name = models.CharField( max_length=200, blank=False ) upload = models.FileField( blank=True, upload_to=custom_filename ) publishers = models.ManyToManyField( 'Publisher', blank=False, related_name='publisher_of', through='SubmissionPublisher' ) class Publisher(models.Model): user = models.ForeignKey( User, blank=False, on_delete=models.CASCADE ) pseudonym = models.CharField( max_length=200, blank=False ) class SubmissionPublisher(models.Model): publisher = models.ForeignKey( 'Publisher', blank=False, on_delete=models.CASCADE ) submission = models.ForeignKey( 'Submission', blank=False, on_delete=models.CASCADE ) The problem is in the custom_filename, because I need the first publisher from the instance to generate the filename. The Submission is not yet saved when the SubmissionPublisher needs it to be saved. What would the best way to do this be. Hopefully I have made sense here. Thanks for any help! -
how does django channels knows that a client has disconnected?
I fear that a client loses connection abruptly and get disconnected without leaving any info to the backend. If this happens, will the socket keep active? -
Django-filters is it possible to skip values that aren't a choice in the filter?
I want to filter events by who hosts them in my API. NOTE: Hosts do not have their own tables. They are just a field on an event. I want to be able to send multiple values and grab all their events. So for instance if I query like this api/events?host=ashley&host=bob, it will return both bob's and ashley's events. But if a user enters in another name that doesn't have an event, I'd still like it to return the other hosts events. Is that possible, to skip non existent choices? I've been using the django-filter AllValuesMultipleFilter function to filter all the hosts. Is there a way to skip over a choice if it doesn't exist? class EventFilter(dr_filters.FilterSet): after_start_date = dr_filters.DateTimeFilter(field_name="start_date", lookup_expr="gte") before_end_date = dr_filters.DateTimeFilter(field_name="end_date", lookup_expr="lte") category = dr_filters.AllValuesFilter(field_name="categories__name") venue = dr_filters.AllValuesFilter(field_name="venue__name") status = dr_filters.AllValuesMultipleFilter(field_name="event_status") host = dr_filters.AllValuesMultipleFilter(field_name="host") class Meta: model = Event fields = ( "after_start_date", "before_end_date", "internal_only", "category", "venue", "status", "host" ) # Define ViewSets class EventViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = EventSerializer filter_backends = (filters.SearchFilter, dr_filters.DjangoFilterBackend,) filter_class = EventFilter search_fields = ("name",) ordering_fields = ("name", "start_date", "venue",) def get_queryset(self): qs = Event.objects.filter(start_date__gte=timezone.now()) qs = qs.order_by("start_date") return qs { "host": [ "Select a valid choice. emma is not one of the available … -
Dynamically Adding a Field to Django modelformset ManagementForm data is missing or has been tampered with
In my app, I have to dynamically add a field to the modelformset in the init method of the custom modelformset by extending BaseModelFormSet. class BaseInvoiceFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): excluded_fields = kwargs.pop('excluded_fields', None) super(BaseInvoiceFormSet, self).__init__(*args,**kwargs) for form in self.forms: form.fields.update({'min_unit_share': forms.IntegerField(validators = [validate_positive,] ) }) form.fields.move_to_end('min_unit_share', last=False) # Note that self.fields is an ordereddict. To move an item to the front of an ordered dict in Python 3.0+ I get Exception Type: ValidationError Exception Value: ['ManagementForm data is missing or has been tampered with'] When I comment out the dynamically added field, the error goes away. So, the post method of the class view calls the init method as expected. But, for some reason it thinks that I am changing the ManagementForm data. The question is how to get around or resolve this issue. Is there a way to pop out the added field before calling super(BaseInvoiceFormSet, self).init(*args,**kwargs) Note that it seems all the modelformset data is passed through using *args. It is sitting at args[0] and I could not pop the additional field using args[0].pop('min_unit_share') Also, to make things simple, in my template, I use: {% for form in formset %} {{ form.as_p }} {% endfor %} Any … -
Select users with common answers to questions
I have four models including the CustomUser table. class Question(models.Model): question = models.CharField(max_length=140) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') answer = models.CharField(max_length=70) class Response(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) Each question has multiple answers but each user can only pick one answer to each question. Each user can answer multiple questions. How do I select a list of users with a nested list of their common answers to a reference user with just the ORM? I can think of a hacky solution of retrieving the list of common answers and then a python loop to increment the count for each user but I would like to confine it to the ORM as I need to append this to a parent serializer (UserSerializer -> ResponseSerializer). -
Getting Request method 'GET' not supported - Python
So I've been trying to request an API using the following endpoint: http://viatorapi.viator.com/service/search/products?destId=684&apiKey=98765687***** Using the following python code: import requests import json resp_1 = requests.get("http://viatorapi.viator.com/service/search/products?destId=684&apiKey=98765687*****") res = resp_1.json() print(res) But I keep getting a Request method 'GET' not supported error even when I try the request directly from the browser. I've been looking at the documentation for a while now and it's says that It's supposed to be a POST request. Here: https://docs.viator.com/partner-api/affiliate/technical/#tag/Product-services/paths/~1search~1products/post Any ideas on why this is happening and how to fix this? -
How to receive a zip file from a HTTP response
Context Summarizing, I have an app that sends some file or JSON to a Django server, the server then process the file and create a new zip file. This zip file have to return to the app. I'm trying to do this with a POST request only, returning the file as a response. I was able to download the file as a response with Postman and I can also see the response I want inside one of the HttpErrorResponse attributes. I also found an answer that was able to do the same, but in Java. Some informations App: made with Ionic v4 | Server: Django 2.24 Front side attempts Main request method: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json', }), requestType: 'application/octet-stream' }; this.http.post("http://127.0.0.1:8000/converter2/", file, httpOptions) .pipe( finalize(() => { loader.dismiss(); }) ) .subscribe(data => { console.log(data['body']); }, error => { console.log(error); console.log(error.error.text) }); Attempts: With the method above I receive this error: Error number 1 -> SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse I'm receiving this error because the http response, by default, is trying to parse the response. I read the documentation of HttpClient, but don't say much about receiving … -
foreign key mismatch - "app_uploadedfiles" referencing "app_uploadedfile"
This question doesn't answer to my problem. Here are my classes: class Person(BaseModel): user = models.OneToOneField(User, related_name='person', on_delete=models.CASCADE) class UploadedFiles(BaseModel): person = models.ForeignKey(Person, null=True, blank=True, default=None, related_name='uploaded_files', on_delete=models.CASCADE) common_directory = models.CharField(max_length=200, default=None, null=True, blank=True) tarball_file = models.ForeignKey(UploadedFile, null=True, blank=True, related_name='tarball_file', default=None, on_delete=models.CASCADE) class UploadedFile(BaseModel): description = models.CharField(max_length=200, default=None, null=True, blank=True,) original_file = models.CharField(max_length=200, default=None, null=True, blank=True,) uploaded_file = models.FileField(default=None, null=True, blank=True,) When, in my code I do this: UploadedFiles.objects.create(person=self.request.user.person) I get this error: sqlite3.OperationalError: foreign key mismatch - "app_uploadedfiles" referencing "app_uploadedfile" Any idea how to solve this? -
Is it possible to override LoginView in function based views, not as a class?
I understand that in order to override from django.contrib.auth.views.LoginView one has to use a subclass Class(LoginView) in views.py. However, in my views.py I only have views declared with def my_view(request) In old versions of Django I could just do from django.contrib.auth.views import login, logout def login_user(request): result = login(request=request, template_name='Market/pages/login.html') return result What's the modern Django equivalent of this? The documentation has this example, that forces me rewrite the whole username/password logic into my view: from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid login' error message. ... How can I use a view function (not class!) and still have the automatic managing of the submitted request? -
Django - DoesNotExist at /accounts/signup/ - Membership matching query does not exist
I followed a tutorial on how to deploy django2 on pythonanywhere and than I just added the components from my own app. Everything worked fine in development, but after deployment I cant sign in and all media elements are gone. Traceback: Django Version: 2.2.4 Python Version: 3.6.6 Installed Applications: ['todo', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'qsessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'allauth', 'allauth.account', 'allauth.socialaccount', 'courses', 'memberships', 'star_ratings', 'avatar', 'home', 'online_users', 'django.contrib.sites'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'qsessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'online_users.middleware.OnlineNowMiddleware'] File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in dispatch 214. return super(SignupView, self).dispatch(request, *args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in dispatch 80. **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in dispatch 192. **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 97. return handler(request, *args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in post 103. response = self.form_valid(form) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in form_valid 230. self.user = form.save(self.request) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/forms.py" in save 404. adapter.save_user(request, user, self) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/adapter.py" in save_user 243. user.save() File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/auth/base_user.py" in save 66. super().save(*args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/db/models/base.py" in … -
Django User Registration View -- Best Practice
I need user registration to only be open to users that I approve and I want to minimize the amount of info that users have to input. My current solution is to create a uuid for each user in the django admin (via a unique model that contains other relevant information). Once I have done that I send the user a 'registration link' in the form of: www.oursite.com/accounts/register?c={companyID}&ac={accessCode} Then I use my view to capture those url query parameters and use them to verify create a new user: company = None access_code = None def register(request): # www.lunica.com/accounts/register?c={companyID}&ac={accessCode} global company global access_code initial = {} if request.GET: initial = request.GET.copy() company = initial['c'] access_code = initial['ac'] if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] if password == password2: if get_user_model().objects.filter(email=email).exists(): messages.error(request, 'Email is already in use') return redirect('register') else: print(company) if Customer.objects.filter(customer_id=company).exists(): company_access_code = Customer.objects.filter( customer_id=company).values_list( 'access_code', flat=True)[0] if uuid.UUID(str(company_access_code)) == uuid.UUID( str(access_code)): try: company_obj = Customer.objects.get(customer_id=company) except Customer.DoesNotExist: company_obj = None if company_obj != None: user = get_user_model().objects.create_user( email=email, password=password, name=name, customer=company_obj ) auth.login(request, user) messages.success(request, 'You are now logged in') return redirect('index') else: messages.error(request, 'Admin Error (3): Please contact admin.') … -
OperationalError at /admin/news/article/ no such column: news_article.reporter_id
Models.py from django.db import models from django.utils import timezone class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=255, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Reporter(models.Model): full_name = models.CharField(max_length=70, db_index=True) def __str__(self): return self.full_name class Article(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) category = models.ForeignKey(Category, related_name='article', on_delete=models.CASCADE) reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) headline = models.CharField(max_length=200) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='article/%Y/%m/%d', blank=True) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.headline I am getting this error while running this code. django.db.utils.IntegrityError: The row in table 'news_article' with primary key '1' has an invalid foreign key: news_article.reporter_id contains a value 'reporter_id' that does not have a corresponding value in auth_user.id. admin.py from django.contrib import admin from .models import Category, Article, Reporter # Register your models here. @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ['name', 'slug'] prepopulated_fields = {'slug': ('name',)} @admin.register(Reporter) class ReporterAdmin(admin.ModelAdmin): list_display = ['full_name'] @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ['headline', 'slug', 'reporter', 'created', 'updated'] list_filter = ['headline', 'created', 'updated'] prepopulated_fields = {'slug': ('headline',)} -
How are the directories of a Django Project tree referred to?
Assume you have a directory where you keep all your Django projects: $HOME/Programming/Django_Projects If you in this directory call django-admin startproject blog you'll end up with the following director tree: $HOME/Programming/Django_Projects/blog $HOME/Programming/Django_Projects/blog/blog What's the first blog and whats blog/blog? -
How to customize template in django-oscar?
i want to customize django-oscar template according to my requirement , when i modified the checkout page, i had been encoutred with this error : TemplateSyntaxError at /checkout/thank-you/ Invalid block tag on line 132: 'oscar_thumbnail', expected 'endwith'. Did you forget to register or load this tag? this my settings.py : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), OSCAR_MAIN_TEMPLATE_DIR ] , # 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.contrib.messages.context_processors.messages', 'oscar.apps.search.context_processors.search_form', 'oscar.apps.promotions.context_processors.promotions', 'oscar.apps.checkout.context_processors.checkout', 'oscar.apps.customer.notifications.context_processors.notifications', 'oscar.core.context_processors.metadata', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], }, }, ] how i can register the templatetag into my custom template in django-oscar? -
Serialize nested models as a keyed JSON object in Django
I have a Django model that has many=True nesting, and I'd like to serializer the nested objects (in Django Rest Framework) as an object instead of a list (which is the default in DRF). Adding many=True serializes things as a list. class PostSerializer(serializers.ModelSerializer): votes = VoteSerializer(many=True) Instead of rendering the votes as a list of objects: [... posts: [{id: 123, user: A}, {id: 456, user: B}, ....] I'd like to render votes as a list of objects keyed by id: [... posts: {123: {user: A}, 456: {user: B}}, ...] -
django models and migrations are not affecting project
I have been stuck on trying to alter a column of one my models. I am able to makemigrations and migrate successfully, and the migration file accurately describes the changes. The problem is that when i try to run my webapp, I get errors from a model schema from before. For example I have a column key. It used to be an integer with null = False. Now i have made a migration changing this key column to a TextField with null = True. The migration file shows the change and models accurately depicts this as well. Now I am getting errors saying that null value in column "key" violates not-null constraint My project is connected to a postgresql backend and this particular model doesn't have a postgres table connected to it. What I have tried: I have tried to delete all migration files in my project and try to start from scratch, but it seems as though it is still using an old schema and have no idea why that is. This is what shows in my migration commands: $ python3.6 manage.py makemigrations kpi Migrations for 'kpi': kpi/migrations/0001_initial.py - Create model Bug - Create model Epic - Create model … -
how to save video and use it like I do with an image
I'm using django and I'm just wondering how to use video. <video class="video-fluid" style="max-width:100%; height: auto;" autoplay loop muted> <source src="https://mdbootstrap.com/img/video/Tropical.mp4" type="video/mp4" /> </video> how do I save video in my directory? where do I save it? in the media folder? and use static to call it like I do with images? -
Django: Form ModelMultipleChoiceField with annotated queryset
I´m trying to make a multiple choice field in a form. Instead of using the full queryset I want to annotate some values. The annotation productos_incluir = ProductosBase.objects\ .filter((Q(region__region__icontains="Argentina") | Q(region__region__icontains="Todas")) & Q(estatus_contenido__id__gt=2))\ .values("marca__marca", "producto", "packaging").annotate(variantes=Sum("producto"))\ .order_by("marca__marca", "producto", "packaging") The form field productos = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=productos_incluir, required=False) The view <div>{{ filter_form.productos }}</div> The result I get the list displayed in the view but I get the "Label" next to the checkbox like this: {'marca__marca': 'Cramer', 'producto': 'Cutter - Shark', 'packaging': 'Bolsa individual', 'variantes': 0.0} My desire What I want is to be able to show the labels without the field info. I guess it has to do with the queryset type change when annotating, but I can´t find how to show this. Cramer | Cutter - Shark Bolsa | individual Thanks in advance! -
redirect to API login page and get back token
I am amateur in web programming and I don't know if my question is stupish: I'm developing an app that uses an API (Trello API) to work and I don't know how to redirect user to Trello login page and and get back token to run my app using his/her account Trello Authorization manual: https://developers.trello.com/page/authorization -
Upload image whit Selenium and Python on Ubuntu 18.04
I have a problem... This is my code: upimage = ActionChains(webdriver).move_to_element( webdriver.find_element_by_class_name("button")) print ('open') sleep(5) upimage.send_keys("/home/user/Image/2.jpg") print ('selected') sleep(5) it open popup for choose file and print "open" after if print "selected" but not select and load any image!!! Whats' wrong? EDIT 1: I try with: upimage.send_keys("/home/user/Image/2.jpg").perform() no effect! -
MultiValueDictKeyError: 'content'
i'm going to make the todo list using django...i did some code...but it throws an multiplevaluekeyerror i tried c = request.POST.get('content', False) but it gives always as False value views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .models import TodoItem # Create your views here. def home(request): return render(request, 'home.html') def work(request): all_todo_items = TodoItem.objects.all() return render(request, 'work.html', {'all_items': all_todo_items}) def addTodo(request): c = request.POST['content'] new_item = TodoItem(content = c) new_item.save() return HttpResponseRedirect('/work/') def deleteTodo(request, todo_id): item_to_delete = TodoItem.objects.get(id=todo_id) item_to_delete.delete() return HttpResponseRedirect('/work/') work.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <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"> <link rel="stylesheet" type="text/css" href="{% static 'css/work.css' %}"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous"> <link rel="icon" href="{% static 'images/list.png' %}" type="image/png"> <title>Tasks</title> </head> <body> <div class="container justify-content-center wrap1"> <div class="text-center heading"> <p><u>write your everyday task here!!!<u></p> </div> </div> <ul style="list-style: none; color: #1b0573; font-weight: bold;" class="text-center"> {% for todo_item in all_items %} <li> <div class="row"> <div class="col-sm-6"> {{ todo_item.content }} </div> <div class="col-sm-2"> {{ todo_item.date_created }} </div> <div class="col-sm-1"> <form action="/deleteTodo/{{ todo_item.id }}" method="post" style="display: inline;"> {% csrf_token %} <div class="form-group"> <button class="btn btn-outline-danger"><i class="fas fa-trash"></i></button> </div> </form> </div> </li> {% endfor %} </ul> <div class="container"> … -
Data not being saved by form in Django
I have this form in Django: class MyForm(forms.ModelForm): key = forms.CharField() secret = forms.CharField() class Meta: model = MyModel fields = ("key", "secret") def save(self, commit=True): send = super(MyForm self).save(commit=False) if commit: send.save() return send And its model: class MyModel(models.Model): key = models.CharField(max_length=200) secret = models.CharField(max_length=200) def save(self): # ALL the signature super(MyModel, self).save() This is the view: def MyView(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): send = form.save(commit=False) send.save() messages.success(request, f"Success") else: form = MyForm() return render(request, "main/template.html", context={"form":form}) URL: path("MyView/", views.MyView, name="MyView"), The problem i keep having, is that the data submitted to the form is not being saved on my Database. When i use the form everything works, i don't get any errors, i get a Success from Django, but nothing happens on my DB. The only errors i'm getting are the following: [2019-08-02 18:22:38,279] log: WARNING - Not Found: /template/... And on Chrome: GET http://127.0.0.1:8000/apis/... 404 (Not Found) -
Automatically filled form in class-based view
I want to automatically fill some form in class-based view and save in database. post function in my view def post(self, request, *args, **kwargs): form_2 = self.form_class_2(self.request.POST) if form_2.is_valid(): keyword = form_2.cleaned_data['keyword'] books = self.search(keyword) if books: for book in books: title = self.add_title(book) form = self.form_class(initial={"title": title, }) if form.is_valid(): form.save() else: return HttpResponseRedirect(reverse_lazy('add_books')) return HttpResponseRedirect(reverse_lazy('import_books')) else: return HttpResponseRedirect(reverse_lazy('index_books')) return reverse_lazy('import_books') Basically I have 2 forms. form 2 is used to input value which is used as argument in my search function. then this search function return .json, then i took some value from this .json and assign to "title" then this title is my input data for form. And everything works fine until part with validation. My form isn't valid but when I print my form before validation part I see that my initial data is in form as expected. -
django can't run exiftool himself
I'm using exiftool in django project but it's seem can't run it . i dont know how i can found why because not any error hapen when i call process is using exiftool . but i think its about permission of users . when i run exiftool -j <image> in terminal all going well and i can see correct result but when i use below code to use exiftool in project ,the result shown me django can't run exiftool : cmd_get_meta = 'exiftool -j "{filename}"'.format(filename=absolute_file_path) process = subprocess.Popen(cmd_get_meta, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) raw_result = process.communicate() meta = json.loads(str(raw_result[0], 'utf-8'))[0] the error is : File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None so obvious that exiftool -j "{filename}" is not running by django. for more information i should tell this problem appear after i updated exiftool and i'm sure code is correct. django are running by uWSGi and here is user that running exiftool and uwsgi by : $ ps aux | grep uwsgi backend 1243 0.0 0.0 14224 988 pts/9 S+ 14:52 0:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn uwsgi www-data 20469 0.0 0.7 222664 63984 ? S 2018 32:55 /usr/bin/uwsgi --ini /usr/share/uwsgi/conf/default.ini --ini /etc/uwsgi/apps-enabled/hamclassy.ini …