Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use a action decorator for update?
I need to update my endpoint using a action decorator. What is better way to make a action for update? I have two serializers: class GarageViewSet(viewsets.ModelViewSet): queryset = Garage.objects.all() serializer_class = GarageSerializer model = Garage class CarViewSet(RestrictedQuerysetMixin, viewsets.ModelViewSet): queryset = Car.objects.all() serializer_class = CarSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ('color', 'model') model = Car I need to receive a list payload by "car" and update the "garage" by a action. I'm trying something like this: class GarageViewSet(viewsets.ModelViewSet): queryset = Garage.objects.all() serializer_class = GarageSerializer model = Garage @action(detail=True, methods=['put']) def update_car(self, request): queryset = Car.objects.create() serializer = CarSerializer(queryset, many=True) return Response(serializer.data) payload example: { "fuel": 2, "model": 2, "color": null, } Some idea for action update?? -
Authenticating deployed django app with mod_wsgi
I have my django app deployed on Apache using mod_wsgi and cannot get pass the login page. I am using the admin credentials from when i created the app and doesn't recognize it, when deployed. It works fine on my workstation computer when running but it seems that i need to add some logic to make it so apache knows to let me through. I have looked at this https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/apache-auth/ But it doesn't help, For the wsgi.py file the only thing that it adds in the example is an import. Can someone supply me with an example or explanation of how this works? -
select_for_update throws TransactionManagementError within atomic block
I'm not super familiar with django but why i'm getting TransactionManagementError when within in atomic block. with transaction.atomic(): product = Products.objects.select_for_update().filter(id=product_id).values().first() product.available_count = product.available_count - 1 product.save() -
Djano rest - 'NoneType' object has no attribute '_meta'
I have implemented custom user module in my django rest app. The migrations and all were done successfully. But when I try to open the users page in my browser. I receives the following error in debug console 'NoneType' object has no attribute '_meta' My user model file is as follows: from __future__ import unicode_literals from django.db import models from django.core.mail import send_mail from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ from .managers import UserManager class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name for the user. ''' return self.first_name def email_user(self, subject, message, from_email=None, **kwargs): ''' Sends an email to this User. ''' send_mail(subject, message, from_email, [self.email], **kwargs) and my serializers file is as follows: from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth.hashers … -
Django File convert/upload progress bar
I am creating a web app in django and it convert a certain file and display a output. I want to add progress bar when file is converting. Is anyone help me to do that. -
Django: Incorrect type. Expected pk value, received str
I am using Django Rest Framework to performing get() and post() to an existing database. The Database doesn't have an 'id' field. It has composite primary keys for all the tables and I cannot modify the schema of the tables. The get() with postman works as expected, however, facing issues with post(). I have nested foreign key relations between three models. Issues: 1. With browsable API, when I click on the link provided in the UI, it throws error - (1054, "Unknown column 'test_suite.id' in 'field list'") [Traceback attached below] The post() with frontman also throws error given below. models.py class TestSuiteModel(models.Model): team_name = models.ForeignKey(TeamModel, on_delete=models.DO_NOTHING, db_column='team_name') template_name = models.ForeignKey(EmailTemplatesModel, on_delete=models.DO_NOTHING, db_column='template_name') suite_name = models.CharField(max_length=100) # Other Fields class Meta: managed = False db_table = 'test_suite' unique_together = (('team_name', 'suite_name'),) class TestCaseModel(models.Model): team_name = models.ForeignKey(TestSuiteModel, on_delete=models.DO_NOTHING, db_column='team_name') suite_name = models.ForeignKey(TestSuiteModel, on_delete=models.DO_NOTHING, db_column='suite_name') test_type = models.ForeignKey(TestCaseTypeModel, on_delete=models.DO_NOTHING) # Other Fields class Meta: managed = False db_table = 'test_case' unique_together = (('team_name', 'suite_name', 'case_name'),) class TeamModel(models.Model): team_name = models.CharField(primary_key=True, max_length=30) description = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'team' class TestCaseTypeModel(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=200, blank=True, null=True) class Meta: managed = False db_table … -
Stripe-iOS backend method in Django to create ephemeral key?
I've been following Standard iOS Integration Guide of Stripe for my iOS app, which uses a backend written in Python-Django, to issue an ephemeral key. This is the function I came up with in my views.py: import stripe stripe.api_key = "sk_test_Xf1yJ9qESRcCliM9iLoRmCIW" def issue_key(request): if request.method == 'POST': api_version = request.POST.get('api_version') customerId = request.session['customerId'] key = stripe.EphemeralKey.create(customer=customerId, api_version=api_version) return JsonResponse({'key': key}) else: return redirect("home:feed") In my iOS app, I copied all the files from stripe-ios Standard Integration and filled in stripePublishableKey and backendBaseURL accordingly. I'm also successfully creating a Stripe customer when a new user registers to my app, through Firebase Cloud Functions. However, when CheckoutViewController loads, I get "Response status code was unacceptable: 404" error. Assuming this error occurs while returning a JSON response from my backend, what is the correct code for the above method? Or am I missing something else on the Swift side? Any suggestion or feedback will be welcomed and greatly appreciated. Thank you. -
Django - redirect reverse() with slug and kwargs
project URLS.py path('<slug:slug>/', include('orgs.urls')), app URLS.py path('donate/', views.org_site_view, name='org_donate', kwargs=dict(page='donate')), Which looks like : mysite.org/samporg/donate Where samporg is the slug variable. I am trying to redirect to a Success Page using the same Donate View 'org_donate' . In view I have tried : return redirect(reverse('org_donate', slug='samporg', kwargs={'page': 'donate_success'})) return redirect(reverse('org_donate', kwargs={'page':'donate_success'})) return redirect('org_donate', slug='samporg', kwargs={'page':'donate_success'}) return redirect('org_donate', kwargs={'slug':'samporg','page':'donate_success'}) None work. All throw Argument or Reverse errors Reverse for 'org_donate' with keyword arguments '{'kwargs': {'slug': 'samporg', 'page': 'donate_success'}}' not found. 1 pattern(s) tried: ['(?P<slug>[-a-zA-Z0-9_]+)\\/donate\\/$'] -
Django DetailView raise 404 not found error in real server
I use Django 2.1, Python 3.5 and MySql (MariaDB 10). All things in localhost is correct, but in real server, DetailView raise 404 error. Please help me. My view code is: class Blog_detail(DetailView): model = Post template_name = 'detail.html' and my url pattern is: path('blog/<str:slug>/', views.Blog_detail.as_view(), name='detail'), My connection is: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydb', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', # 'PORT': '3306', 'OPTIONS': { 'charset': 'utf8' }, } DetailView result only in Latin URI work correctly, but in utf-8 or Unicode URI raise 404 error. -
How to trigger custom python code when a valid django form is saved in the database
Django newbie here, I created a simple form following this tutorial, and my form correctly saves the data in my Postgres connected local database. I was wondering, how can I trigger a function, whenever a valid form is saved into the database? The code I want to run is a simple function which is written in a python file, and it does some processing on the latest data given by the first form. I want it to run only when a valid form data is saved and was wondering if django signal trigger is my way to go. Feel free to ask for any further clarification. Here is my code : views.py from django.shortcuts import render from django.http import HttpResponse from .forms import auditform, ClientAuditForm from django.db.models.signals import post_save from . import rocode # def auditingfun(request): # return HttpResponse('Auditing form works') # # Create your views here. def auditingfun(request): if request.method == 'POST': forminput = auditform(request.POST) if forminput.is_valid(): Name = forminput.cleaned_data['Name'] Origin = forminput.cleaned_data['Origin'] ClientAddress = forminput.cleaned_data['ClientAddress'] DispatchType = forminput.cleaned_data['DispatchType'] ETA = forminput.cleaned_data['ETA'] GSTIN = forminput.cleaned_data['GSTIN'] # print(GSTIN,Name,Origin,Destination,MaterialType,Preference,ClientAddress,DispatchType,ETA) forminput = auditform(request.POST) return render(request, 'auditing/auditform.html', {'forminput': forminput} ) forms.py from django import forms from .models import auditModel class auditform(forms.Form): Origin = … -
OperationalError: sub-select returns 2 columns - expected 1 in Django QuerySet
There are two models a Price model and Service model. I'm trying to find the Services that have the most collected prices based on a user input query (called the entry_query). The first line (1) get the price objects that the user queries (this works). Then, line 2 (2) returns a QS with the service_code and counts of the services that have a price from a company. Then, it brings on line (3) where it gives an error (see below). (1) Price_objs = Price_filter.filter(entry_query) (2) objs_filter=Price_objs.values_list('service__code').annotate(service_count=Count('service__code')).order_by('-service_count') (3) serv_obj = Service.objects.filter(price__in = objs_filter).distinct() Here is what line (2) outputs: <QuerySet [('36430', 62), ('86003', 28), ('87149', 28), ('83516', 23), ('86317', 20), ('94640', 19), ('73502', 18), ('86658', 14), ('73721', 13), ('87070', 13), ('76942', 12), ('87081', 12), ('73560', 11), ('87798', 11), ('36415', 10), ('74177', 10), ('99211', 10), ('73100', 9), ('73221', 9), ('74176', 9), '...(remaining elements truncated)...']> Here is the error that I get with line (3): django.db.utils.OperationalError: sub-select returns 2 columns - expected 1 -
Django template - "Template" object has no attribute "split"
I am using jinja2 to render a template in django: Template settings: TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ] }, }, {"BACKEND": "django.template.backends.jinja2.Jinja2", "DIRS": ["utils/"]}, ] Calling code: html_template = get_template("email/contact/contact.html") #completes successfully - template definitely found html_message = render_to_string(html_template, context) This gives the error: AttributeError: 'Template' object has no attribute 'split' Googling this only shows solutions for: AttributeError: 'NoneType' object has no attribute 'split' Which suggests that the template is not found. This is not the case here. -
To process post body json sent via ajax in Django
$.ajax({ 'url' : "http://localhost:7090/"+ 'manageApp', 'type': 'POST', 'dataType' : 'jsonp', "headers": { "content-type": "application/json" }, "processData": false, "data": "{\n\t\"symbolicName\" :\"org.lorainelab.igb.protannot\",\n\t\"action\" : \"getInfo\"\n}", "async": true, 'crossDomain':true, 'success': function() { callback(false); }, 'error': function() { callback(false); } }); } This is the code in js file inside django framework. I want to make an post request to an application ruuning locally which parse the json request body and returns json response. manageApp(payload) JsonObject body = new JsonParser().parse(payload).getAsJsonObject(); But the payload i am receiving is callback=jQuery111109410441669038576_1553268399194&{%22symbolicName%22:%22org.lorainelab.igb.protannot%22,%22action%22:%22getInfo%22}&_=1553268399195 which the gson parser is not able to parse and thus giving jsonmalformed exception. I want the payload to be, { "symbolicName" :"org.lorainelab.igb.protannot", "action" : "getInfo" } The application processes json response properly when I do a post request using POSTMAN. P.S I am using NANOHttpd to get the json body from request, Map<String, String> requestParams = new HashMap<>(); try { session.parseBody(requestParams); } catch (IOException ioe) { } catch (ResponseException re) { } pluginManagerService.manageApp(session.getQueryParameterString()); -
Django no such table: django_site after deleting migrations and database
I tried to change an app name. This didnt work and so I tried to change it back. This didnt work either and I deleted all migrations and my db.sqlite. Now whenever I try makemigrations or migrate I get this error: django.db.utils.OperationalError: no such table: django_site I tried these answers but they didnt help me: No such table as django_site, Django 1.5.4: no such table: django_site in admin/ I really dont know what to do. Maybe someone can help me. -
Truncate the length of model serializer with many=True in Django
So in my project, I have a model Chat with many Messages. I want to have ChatSerializer with MessageSerializer inside and many=True. However, I only want to include the last 50 Message models. class MessageSerializer(serializers.ModelSerializer): class Meta(object): model = Message fields = '__all__' class ChatSerializer(serializers.ModelSerializer): messages = MessageSerializer(many=True) class Meta: model = Chat fields = '__all__' Is there anything I can add to the messages = MessageSerializer(many=True) to make it only return the latest 50 messages? Thanks! -
django-rest-auth: What is the email verification for?
I might misunderstand something. django-rest-auth provides RegisterView and an email is supposed to be sent to the user's email after user sign up. However, I've noticed the user is registered with is_active=True even before the user confirm the email. Then, what is the email verification for? Do I have to override something and create the user with is_active=False when the user register with a site? And if so, how can I achieve it properly? I'm having trouble with it. Here is what I did. urls.py path('api/v1/rest-auth/registration/', include('rest_auth.registration.urls')), serializers.py from rest_auth.registration.serializers import RegisterSerializer class CustomRegistrationSerializer(RegisterSerializer): def save(self, request): user = super(CustomRegistrationSerializer, self).save(request) user.is_active = False return user settings.py REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'appname.serializers.CustomRegistrationSerializer', } and here is an error I encountered. File "rest_auth/registration/views.py", line 46, in dispatch return super(RegisterView, self).dispatch(*args, **kwargs) File "/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "rest_framework/generics.py", line 192, in post return self.create(request, *args, **kwargs) File "rest_auth/registration/views.py", line 65, in create user = self.perform_create(serializer) File "rest_auth/registration/views.py", line 81, in perform_create None) File "allauth/account/utils.py", line 183, in complete_signup signal_kwargs=signal_kwargs) File "/allauth/account/utils.py", line 133, in perform_login return adapter.respond_user_inactive(request, user) File … -
Django Media fie auto delete
When I upload an image through Django administrator and I delete the image file again, why the image does not delete in directory '/medai' I want when i delete an image file, it should be deleted automatically from even directory, not only My model: class ImageForExtractText(models.Model): image = models.FileField() And setting: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media") What should I do to make it happen, when deleting the image file from Django administration, it should delete from both Django administration and directory -
Django Timeline Graph
I'm trying to display a timeline graph in my Django app. Unfortunately, I'm with some problems finding the correct package to do this type of graph: TimeLine Graph My goal is to display some time intervals on one line and make them clickable to a view sending the interval id. Thanks in advance. -
Django is not saving form to datebase
I got the problem with form that is not saving to the datebase. views.py ... @login_required def create_task(request): if request.method == 'POST': form = CreateTaskForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('index') else: form = CreateTaskForm() context = {'form': form} return render(request, 'tasks/task_form.html', context) ... forms.py from django import forms from .models import Task class CreateTaskForm(forms.ModelForm): class Meta: model = Task fields = ( 'name', 'end_date', 'description', ) Is it the problem with a create_task view or CreateTaskForm? -
TypeError: __str__ returned non-string (type NoneType) With Django third party package Models
I installed the django_message package into my django app using django 2.0 and while it works on my development machine, it throws the following errors on production. TypeError: __str__ returned non-string (type NoneType) [22/Mar/2019 15:08:12] ERROR [django.request:118] Internal Server Error: /admin/django_messages/message/ Traceback (most recent call last): File "/opt/site_env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/opt/site_env/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/site_env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/site_env/lib/python3.6/site-packages/django/contrib/admin/options.py", line 574, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/opt/site_env/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/opt/site_env/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/opt/site_env/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 223, in inner return view(request, *args, **kwargs) File "/opt/site_env/lib/python3.6/site-packages/django/utils/decorators.py", line 62, in _wrapper return bound_func(*args, **kwargs) File "/opt/site_env/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/opt/site_env/lib/python3.6/site-packages/django/utils/decorators.py", line 58, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/opt/site_env/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1570, in changelist_view cl = self.get_changelist_instance(request) File "/opt/site_env/lib/python3.6/site-packages/django/contrib/admin/options.py", line 705, in get_changelist_instance self, File "/opt/site_env/lib/python3.6/site-packages/django/contrib/admin/views/main.py", line 76, in __init__ self.queryset = self.get_queryset(request) File "/opt/site_env/lib/python3.6/site-packages/django/contrib/admin/views/main.py", line 320, in get_queryset filters_use_distinct) = self.get_filters(request) File "/opt/site_env/lib/python3.6/site-packages/django/contrib/admin/views/main.py", line 130, in get_filters self.model, self.model_admin, field_path=field_path File "/opt/site_env/lib/python3.6/site-packages/django/contrib/admin/filters.py", line 157, in create return list_filter_class(field, request, params, … -
Reverse for 'todo-user' with arguments '('',)' not found. 1 pattern(s) tried
I am trying to add an user when clicking on a link but I have the following error : Reverse for 'todo-user' with arguments '('',)' not found. 1 pattern(s) tried: ['todo/(?P[^/]+)/$'] My views.py def todo_user(request, todo_id): todo.username.add(request.user) todo.save() return render(request, '/') Template <a href="{% url 'todo-user' todo.id %}"> <button class="btn btn-success btn-block" type="submit" name="validate-property" ></button></a> Urls.py path('validate/<todo_id>/', views.todo_user, name='todo-user), Thanks to you guys ! -
How to grab a part of URL address from Django template, not full template
How do I get '12' which is the id of teacher model in this path from Django template? http://localhost:8000/editTeacher/12/ I searched a bit and I know how to get the entire url, but don't know how do I get a part of it. I also tried using request.get('id') but it didn't work! Please help me fix it Thanks -
Django: how to use a variable key filter with __range
date_one = form.cleaned_data.get('date_one') date_two = form.cleaned_data.get('date_two') date_type = form.cleaned_data.get('date_type') search = MyClass.objects.filter(date_type__range(date_one, date_two)) My model has two different date columns. (created and expires). The user can make a query filtering between two dates, but he can choose if he wants to filter by creation or expiration. I could make two query lines using if, but I really want to know how to do it in the way I'm asking. How can I do this? Since the key before __range is a variable. I tried with (**{ filter: search_string }) but it seems not to be compatible with __range. -
Project Suggestions for building a QR Code based private library
I'm quite new to programming and a huge fan of learning by doing as I've done in other fields of expertise as well, so I wanted to start out with a not too complex project. Project description: I've got plenty of books at home (easily more than 100) and I want to implement a web solution which should represent my "own little library". Additionally I thought about QR Code stickers which I'd put into every book for fetching information about it (in which shelf it lays, my review about it, author, etc). Could anybody give me some suggestions to the architecture? I thought obviously about using HTML, CSS because it should be a web solution and maybe a python backend (I don't really care about languages). Maybe I'll have to build an API for getting the book data form the QR code? Any database suggestions? -
Django Nginx Gunicorn - Media Files Not Showing (DigitalOcean Deployment)
I have deployed a Django project on Ubuntu 16.04 with Nginx and Gunicorn. I have gotten everything, including the static files but my media files will not serve properly. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') models.py resume_upload = models.FileField(blank=False, upload_to='resumes', null=True, validators=[FileExtensionValidator(allowed_extensions=['pdf']), validate_file_size]) What I have listed in /etc/nginx/sites-available/ is server { listen 80; server_name website.com www.website.com ; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/syed/btawebsite; } location = /media/ { root /home/syed/btawebsite; } location / { include proxy_params; proxy_pass http://unix:/home/syed/myproject.sock; } } I would like go on the admin, click on the uploaded file and be able to view the file in the browser. Anyone have any ideas on how I can achieve this? I have verified through using the terminal and looking through the directories that the files are in fact adding to ~btawebsite/media/resumes but I am unable to view them when I click the admin url. When I click on that url I get an error: Not Found The requested resource was not found on this server.