Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Spotipy Authentication Flow (Spotify API)
I'm trying to allow users to login with Spotify (using the Spotipy library) to provide authentication for creating a playlist on their account and populating the playlist. After the user has logged in, I will display the playlist they have just created in the redirect template via an embedded Spotify player (using the playlist ID of the newly created playlist). I have a form input box in my HTML template which takes input from the user (their Spotify username). I also have a list of Spotify URIs for tracks ready to populate the playlist with. I followed Spotipy's documentation regarding obtaining a token for users for authentication as follows (I have removed my client-id & secret).. I'm not sure why it isn't working: import os import spotipy import spotipy.util as util from json.decoder import JSONDecodeError from datetime import date @login_required def save_playlist(request, data='Default_Data'): username = data.split('/')[0] #spotify username track_ids = data.split('/')[1:11] #list of spotify IDs for playlist tracks client_id = '****' client_secret = '****' scope = 'playlist-modify-public, playlist-modify-private' redirect_uri = 'http://127.0.0.1:8000/save_playlist/' #check if username is already in cache, if not, create cache try: token = util.prompt_for_user_token(username, scope=scope,client_id=client_id, client_secret=client_secret,redirect_uri=redirect_uri) except (AttributeError, JSONDecodeError): os.remove(f".cache-{username}") token = util.prompt_for_user_token(username, scope=scope,client_id=client_id, client_secret=client_secret,redirect_uri=redirect_uri) sp=spotipy.Spotify(auth=token) today = … -
Failed to start gunicorn.service: Unit gunicorn.service not found. Ubunto 18.04
I am following the this How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 18.04 guide. I have created the following file sudo nano /etc/systemd/system/gunicorn.service Original RECOMENDED_FORMATTING-s in the guide [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammyRECOMENDED_FORMATTING Group=www-data WorkingDirectory=/home/sammyRECOMENDED_FORMATTING/myprojectdirRECOMENDED_FORMATTING ExecStart=/home/sammyRECOMENDED_FORMATTING/myprojectdirRECOMENDED_FORMATTING/myprojectenvRECOMENDED_FORMATTING/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myprojectRECOMENDED_FORMATTING.wsgi:application [Install] WantedBy=multi-user.target How I have formatted my own version I had my virtual environment outside of the project folder on the server [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=SERVER_USER Group=www-data WorkingDirectory=/home/SERVER_USER/MAIN_PROJECT_FOLDER ExecStart=/home/SERVER_USER/ven/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/home/SERVER_USER/MAIN_PROJECT_FOLDER/MAINAPPLICATION_FOLDER.sock \ MAINAPPLICATION_FOLDER.wsgi:application [Install] WantedBy=multi-user.target I have also tried leaveing these as originally recomended --bind unix:/run/gunicorn.sock \ Than I have tried to execute the following code sudo systemctl start gunicorn Error message Failed to start gunicorn.service: Unit gunicorn.service not found. To solve this, I have tried Failed to start gunicorn.service: Unit gunicorn.service not found This points back to the exact same guide that I am doing except with an older version of linux. this is not the same code and not answered https://askubuntu.com/questions/748836/unit-gunicorn-service-failed-to-load-no-such-file-or-directory -
SuspiciousOperation at /i18n/setlang/ The request's session was deleted before the request completed
My Django Localization works perfectly in my development environment, but once i uploaded in on an ubuntu vps server with apache2 the translation is not working any more gives me this error when i ever i try to change the language : SuspiciousOperation at /i18n/setlang/ The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. Here is my code : settings.py LANGUAGE_CODE = 'en-US' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) My path to locales files are like : base/locale/ar/LC_MESSAGES/django.po And finally here is the form am using : <form style="margin-left: 50px;" action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language" id="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="{% trans 'go' %}"> </form> And also i have 'django.middleware.locale.LocaleMiddleware', inside MIDDLEWARE in my settings.py -
Pycharm "mark as template" missing
In my Pycharm I'm missing the 'templates' and 'resources' options for my directory folder. What should I fix in Pycharm to make this work? -
Convert dict to specific byte format
I am trying to create a Python client for making a HMAC authenticated request to a Django application. I am having trouble recreating the payload byte format that the Django app is using to generate the signature, and therefore I cannot recreate the signature value. the Django app is passing in the request body into the signature function in the format: b'key=value' where the payload is: { "key":"value"} I have tried both: str({ "key": "value" }).encode("UTF-8") and json.dumps({ "key": "value" }).encode("UTF-8") but both of them return: b"{'key': 'value'}" What is the this format (b'key=value') and how can I recreate it from a dict? -
Django Rest Framework - How to create a GIF file from an uploaded video
I have a Django Rest Framework + Android App where the user can upload some video files to my local Django development server. I wanted to show the videos as GIF files via a RecyclerView. I thought that creating the GIF files on server side (Django) would be more efficient than creating them on the client side (device). So I want to make a GIF file from an uploaded video before storing the video file. How can I do that in Django ? Here is my models.py: class Video(models.Model): created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=100, blank=True) video = models.FileField(upload_to='Videos/', blank=True) class Meta: ordering = ('created', ) This is how my views.py looks like: # used for displaying & creating video items class VideoList(generics.ListCreateAPIView): queryset = Video.objects.all() serializer_class = VideoSerializer parser_classes = (MultiPartParser, ) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) # the only part we change return Response({'videos': serializer.data}) And this is the urls.py with the url the app uses to upload the video file: urlpatterns = [ ... path('upload/', views.VideoList.as_view()) ] The upload of videos from my app works, but … -
list_filters are not working with redefined get_queryset in Admin list_view if that contains union
I needed to create Django Admin list_view page with redefined get_queryset() method that will do union by different models to the same page. But after I updated it, list_filter stopped work. As I find out if you use union() - Django doesn't allow to do any further filtering (only LIMIT, OFFSET, COUNT(*), ORDER BY SQL operations). And for some reason application of these filters is implemented after call of get_queryset(). I thought that call super().get_queryset(request) in my ModelAdmin.get_queryset() will return already parsed data. Questions: Is there any simple way how to get queryset with already applied list_filters and after do my custom filtering and union? Is this a bug in Django Framework by itself and this should be reported in their bug-tracker? -
How to pass 2 arguments from temlate to views in django?
So I know I can pass one argument like this: {%url '...path...' argument%} but I want to pass 2 arguments like {%url '...path...' argument1 argument2%} Here is my exact code: search.html: {% for id, title, thumbnail in videos%} <a href="https://www.youtube.com/watch?v={{id}}"><img src="{{thumbnail}}">{{title}}</a><p style="display:inline;"> | </p><a href="{%url 'select' id title%}">Add to playlist</a> <br> {%endfor%} urls.py: path('select/<id>/<title>', views.select, name='select'), I get the following error: Reverse for 'select' with arguments '('omPiA5AsGWw', 'PRESLAVA - POSLEDEN ADRES / Преслава - Последен адрес, 2007')' not found. 1 pattern(s) tried: ['select/(?P[^/]+)/(?P[^/]+)$'] -
Django Order By on Reverse Foreign Key value drops items without relationships
Context I am trying to sort a list of objects based on the value of a reverse foreign key relationship. I have partial solution, but filter used creates an inner join that drops objects without the relationship. The outcome I want to create sorted queryset with all objects, threating "null" reverse relationships as if the related value was null. Models class Student(models.Model): name = models.CharField(max_length=128) class Subject(models.Model): title = models.CharField(max_length=128) class Grade(models.Model): student = models.ForeignKey("Student", related_name="grades", on_delete=models.CASCADE) subject = models.ForeignKey("Subject", related_name="grades", on_delete=models.CASCADE) value = models.IntegerField() Fixtures +------+------------------------+ | name | subject | grade_value | +------+----------+-------------+ | beth | math | 100 | | beth | history | 100 | | mark | math | 90 | | mark | history | 90 | | mike | history | 80 | +------+----------+-------------+ Desired Outcome When sorting students by their "history" grade, I want to get [ beth (100), mark (90), mike (80) ] Now let's say mark was sick at home and missed the math exam. When sorting students by their "math" grade, I want to get [ beth (100), mark (90), mike (null) ] Instead, for the sorted by math grade returns [ beth (100), mark (90) ]. Attempted Solution … -
how save user in database? python (django) this is custom form
this is my django's forms and views py file. i want save new user. how create? this is forms.py from django import forms class SignUpForm(forms.Form): first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'first'})) last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'first'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'first'})) password = forms.CharField(widget = forms.PasswordInput(attrs={'class':'first'})) re_password = forms.CharField(widget = forms.PasswordInput(attrs={'class':'first'})) this is views.py from django.shortcuts import render from django.http import HttpResponse import datetime from . import forms def regform(request): form=forms.SignUpForm() if request.method=='POST': form=form.SignUpForm(request.POST) else: html="welcome" return render(request,'home/home.html', {'html':html, 'form':form}) -
How to fix Uncaught TypeError: $image.cropper is not a function
I got the error of Uncaught TypeError: $image.cropper is not a function in my project when using the cropper jQuery plugin: https://github.com/fengyuanchen/jquery-cropper I guess the error has to do with the order defining jQuery, Bootstrap and Cropper files. After several attempts , i could not define the correct order. My order is: <script src="/static/theme/assets/js/jquery.min.js"></script> <script src="/static/theme/assets/js/bootstrap.bundle.min.js"></script> <script type="text/javascript" src="/static/cropper/js/jquery-cropper.js"></script> If it helps , my project has to do with cropping images in a django application based on the tutorial: https://simpleisbetterthancomplex.com/tutorial/2017/03/02/how-to-crop-images-in-a-django-application.html Here is the error: Uncaught TypeError: $image.cropper is not a function at HTMLDivElement.<anonymous> ((index):425) at HTMLDivElement.dispatch (jquery.min.js:2) at HTMLDivElement.y.handle (jquery.min.js:2) at Object.trigger (jquery.min.js:2) at HTMLDivElement.<anonymous> (jquery.min.js:2) at Function.each (jquery.min.js:2) at w.fn.init.each (jquery.min.js:2) at w.fn.init.trigger (jquery.min.js:2) at HTMLDivElement.o (bootstrap.bundle.min.js:6) at HTMLDivElement.i (jquery.min.js:2) Uncaught TypeError: $image.cropper is not a function at HTMLButtonElement.<anonymous> ((index):451) at HTMLButtonElement.dispatch (jquery.min.js:2) at HTMLButtonElement.y.handle (jquery.min.js:2) -
How can I set a timer in Django?
class Level(models.Model): name = models.CharField(max_length=25) duration = models.IntegerField() I want to set a duration for this model as a timer, and when it will stop call the other function, also I have to show this timer in certain template. Could anyone show me as an example? -
Django Reverse the mapper, URL name doesn't work
I'm currently doing on Django project and using reversing the mapper on urls.py. Before I use reversing it worked well, but after I change it to reversing, it started to do not work anymore. I want to know why it doesn't work. Is it because I didn't add it in proejct file's urls.py? How can I call that url with the name in app's file? from django.urls import path from . import views app_name = 'posting' urlpatterns = [ path('', views.index, name='index'), path('<int:post_id>', views.post, name='post'), path('posting', views.posting, name='postingform') ] index.html <a href='{% url 'postingform' %}'>Upload your beer now!</a> -
How to modify the frontend context for a React App using GenericViews?
I'm trying to transmit additional context to the front end through a ListAPIView by rewriting get_context_data so it returns a modified context["text_var"]="123". When I try to use something like <p>{{ test_var }}</p> at a index.js, I get the console error: "Uncaught ReferenceError: test_var is not defined". I'm trying to follow the patterns from https://docs.djangoproject.com/en/3.0/topics/class-based-views/generic-display/. Maybe the fact that the frontend is a React application implies in the requirement of additional steps? Can someone please point me what I'm missing here? Kind regards -
In Django, how to send context or variables to JQuery?
I have a Model (Persons) which has to be entered using a ModelForm (PersonForm). models.py, GENDER_CHOICES = [ ('Male', 'Male'), ('Female', 'Female'), ] MALE_CATEGORIES = [ ('Male Category 1', 'Male Category 1'), ('Male Category 2', 'Male Category 2'), ('Male Category 3', 'Male Category 3'), ] FEMALE_CATEGORIES = [ ('Female Category 1', 'Female Category 1'), ('Female Category 2', 'Female Category 2'), ('Female Category 3', 'Female Category 3'), ] def get_all_choices(): all_choices = MALE_CATEGORIES all_choices+=FEMALE_CATEGORIES return all_choices class Person(models.Model): name = models.CharField(max_length=50, unique=True) gender = models.CharField(max_length=7, choices=GENDER_CHOICES) category = models.CharField(max_length=20, choices=get_all_choices()) forms.py, class PersonForm(ModelForm): class Meta: model = Person fields = [ 'name', 'gender', 'category', ] views.py, def personform_page(request): context = {} if request.method == 'POST': personform = PersonForm(request.POST) if personform.is_valid(): personform.save() return redirect('personform_page') context['personform'] = personform else: personform = PersonForm() context['personform'] = personform context['male_categories'] = MALE_CATEGORIES context['female_categories'] = FEMALE_CATEGORIES return render(request, 'app1/personform_page.html', context=context) PersonForm has a dependent dropdown list of which the category choices will be dependent on the selected gender. Currently, I am hardcoding the category choices in JQuery as follows: personform_page.html, <form class="form-class" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% for field in personform %} <p> {{ field.label_tag }} {{ field }} {% if field.help_text %} <small style="color: black;"> … -
Django Import-Export, importing related parent and child models
I'm having trouble following the documentation for django-import-export, I think ive tried every variation of changing the child and parent in the admin to try to make this work. Do you see any glaring issues? This code gives me the error "Line number: 1 - Parent matching query does not exist." models.py class Parent(models.Model): store = models.IntegerField(primary_key=True) state = models.CharField(max_length=250, blank=True) # pylint: disable=R0903 def __str__(self): return '{}'.format(self.store) class Child(models.Model): store = models.ForeignKey('Parent', on_delete=models.CASCADE) company = models.CharField(max_length=250, blank=True) rank = models.IntegerField(blank=True, default='') admin.py class ChildResource(resources.ModelResource): state = fields.Field(attribute='state', column_name='State') company = fields.Field(attribute='company', column_name='Company') rank = fields.Field(attribute='rank', column_name='Rank') store = fields.Field(attribute='store', column_name='Store', widget=ForeignKeyWidget(Parent, 'store')) class Meta: model = Child import_id_fields = ('store',) fields = ('store', 'state', 'company', 'rank') class ParentAdmin(ImportExportModelAdmin): inlines = [Child] resource_class = ChildResource list_display = ('company', 'rank') class Meta: model = Child admin.site.register(Child, ChildAdmin) -
How creat Submenu for mainmenu in django
I am trying to displaying Menu and Sub Menu in table format like. Menu1 Menu2 SubMenu1 SubMenu2 SubMenu3 menu2 but i'm getting wrong. menu1 submenu1 menu2 submenu2 and when I'm adding new submenu it's appearing under both main menu my models.py for menu app from django.db import models class Menu(models.Model): menu_name = models.CharField(max_length=100,blank=True) menu_slug = models.SlugField(max_length=100,unique=True,blank=True) menu_icon = models.ImageField(upload_to="imagemenu",blank=True) def __str__(self): return self.menu_name class Submenu(models.Model): submenu_name = models.CharField(max_length=100,blank=True) submenu_slug = models.SlugField(max_length=100, unique=True,blank=True) submenu_icon = models.ImageField(upload_to="imagemenu",blank=True) parent_menu = models.ManyToManyField(Menu, verbose_name=("Mtavari Menu")) def __str__(self): return self.submenu_name my views.py from django.shortcuts import render from django.http import HttpResponse from menu.models import Menu,Submenu # Create your views here. def HomePage(request): template = "front/Homepage.html" menu_item = Menu.objects.all() menu_submenu = Submenu.objects.all() return render(request,template, {"menu_item":menu_item,}) template file <ul> {% for menu in menu_item %} <li> <a href="#">{{menu.menu_name}}</a> <ul class="sub-menu"> {% for sub in menu_submenu %}<li><a href="index.html">{{sub.submenu_name}}</a></li>{% endfo %} </ul> </li> {% endfor %} </ul> -
Why i can not center div in CSS?
Hei! I am trying to center some div on my website. but nothing moves. Everything stays on left side even now when i haved changed all divs to center. i am checking in many browsers, but still everything is on left side. not i have even changed all divs to center.. still everything on left side. Here is my css code: h1 a, h2 a { color: #DE1FAE; body { padding-left: 15px; text-align: center; } #container { text-align: center; } #gobacktomainback { text-align: center; font-size: 5px; } #searchfield { margin-left: 10px; text-align: center; padding: 30px; background-color: white; } #logo { text-align: center; color: white; background-color: #white; text-align: center; } #login { text-align: center; background-color: #C0C0C0; } #menu { background-color: white; } ul > li { list-style-type: none; float: left; } ul > li > a { padding: 0 20px; } #addrecipe text-align: center; #addingredient text-align: center; HTML: {% load static %} <html> <head> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/drinks.css' %}"> </head> <body> <div id=container> <div id=menu> {% if user.is_authenticated %} <ul> <li><a href="add_recipe">Add recipe</a></li> <li><a href="add_ingredient">Add ingredient</a></li> <li><a href="">Drink list</a></li> </ul> {% endif %} </div> <div id=login> {% if user.is_authenticated %} Hi {{ user.username }}! … -
`Server Error (500)` when deploying django application to heroku
I don't know what is the problem I am trying to deploy my application to Heroku with DEBUG=False but it's sending me Server Error (500) in the UI. However, If I deploy the application with DEBUG=True it works perfect. Here is my settings.py: """ Django settings for main_tour_folder project. Generated by 'django-admin startproject' using Django 3.0.3. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # To import the env.py secret_keys if os.path.exists('env.py'): import env import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['<app-name>.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_forms_bootstrap', 'accounts', 'tour_store', 'cart', 'checkout', 'search', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'main_tour_folder.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', # … -
Django model creating new migration after change in model choices
I have a model named UserRole and there is a field role, in which choices are present to select the role. The problem is that whenever I am adding a new choice and running makemigrations, django creating a new migration for that. I don't want a new migration everytime I add a choice. I know about ForeignKey, but in my case there will be at most 10 choices. Right now I have 3 predefined choices. How can I add choices without creating a new migrations? models.py class UserRoleModel(BaseModel): ROLE_1, ROLE_2, ROLE_3 = 1, 2, 3, USER = 'user' SUPPORT = 'support' ANALYST = 'analyst' CHOICES = ( (ROLE_1, USER), (ROLE_2, SUPPORT), (ROLE_3, ANALYST), ) user = models.ForeignKey(get_user_model()) role = models.SmallIntegerField(choices=CHOICES) migration file class Migration(migrations.Migration): operations = [ migrations.AlterField( model_name='userrolemodel', name='role', field=models.SmallIntegerField(choices=[(1, 'user'), (2, 'support'), (3, 'analyst'), (4, 'lol')]), ), ] I have removed redundant code. -
Wagtail manually login user
I have a wagtail application that needs to login and authenticate users for the /admin section using OAuth. The interaction with the OAuth provider works fine is just at the end of the authorize view I am getting a Too many redirects error. Here is my gist: SESSION_KEY = 'access_token' oauth = OAuth() oauth_client = oauth.remote_app(#oauth client setup here) Views def login(request): """ This view is redirecting to my oauth provider, log the user and redirect back to /authorize with the data in the request. """ return HttpResponseRedirect(oauth_client.authorize( callback='http://localhost/admin/authorize')) def authorize(request): resp = oauth_client.authorized_response(request.GET) request.session[SESSION_KEY] = (resp['access_token'], '') data = baton.get('/oauth/me') username = json.loads(data.data).get('username') user, _ = User.objects.get_or_create( username=username, defaults={'password': username, 'is_superuser': True} ) auth_user = authenticate(username=username, password=username) login(auth_user) return HttpResponseRedirect('/admin') Urls urlpatterns = [ url(r'^admin/login', login, name='login'), url(r'^admin/authorize', authorize, name='authorize'), url(r'^admin/', include(wagtailadmin_urls)), ] The Too many redirects I see in the browsers happens when the authorize view validates all the logic and tries to redirect to /admin but I think what is happening is that Wagtail then is redirecting again to /login but I though authenticating and login a user should be enough for Wagtail, apparently not. Any ideas how to overcome this issue, or programmatically login a user … -
django queryset related objects to json array
I have two models class Place(models.Model): title = models.CharField(max_length = 255) description = models.TextField() class PlaceImage(models.Model): place = models.ForeignKey(Place, default=None, on_delete=models.CASCADE) photo = models.ImageField(upload_to='places', verbose_name='Photo') title = models.CharField(max_length = 250, default = "tmp") and function in a view def read_place(request, place_id): place = Place.objects.filter(pk=place_id).annotate(photos=F('placeimage__photo')).values("id", 'title', 'photos') return JsonResponse(list(place), safe=False) that returns me json objects [{"id": 1, "title": "title1", "photos": "places_upload_location/memorial1.jpg"}, {"id": 1, "title": "title1", "photos": "places_upload_location/memorial2.jpg"}, {"id": 1, "title": "title1", "photos": "places_upload_location/memorial3.jpg"}] But I'd like to get single Place object with array of photos, something like this: [{"id": 1, "title": "title1", "photos": [{ "photo_id": 1, "photo": "places_upload_location/memorial1.jpg" "title": "photo 1" }, { "photo_id": 2, "photo": "places_upload_location/memorial2.jpg" "title": "photo 2" }, { "photo_id": 3, "photo": "places_upload_location/memorial3.jpg" "title": "photo 3" }] }] How can I do it? -
Using multiple Django forms in single View which are dependent through OnetoOneField/ForeignKey
I have two models:- class User(AbstractUser): is_customer = models.BooleanField('customer status',default=False) is_manager = models.BooleanField('manager status',default=False) def __str__(self): return self.username class Customer(models.Model): user = models.OneToOneField(User,on_delete=models.PROTECT,primary_key=True,related_name="customers") full_name = models.CharField(max_length=264,) roll_no = models.IntegerField() mobile_no = models.IntegerField() hostel = models.CharField(max_length=264) room_no = models.CharField(max_length=264,) Here Customer's user object is dependent on the User model. forms.py:- class UserCreateForm(UserCreationForm): class Meta: fields =('username','email','password1','password2') model = User def __str__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields["username"].label ="Display name" self.fields["email"].label = "Email address" class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ['full_name','roll_no','hostel'] What I want is to take Customer's details along with User details. So, How can I use these two models in one View (class-based views will be preferred) and create a single form in the Html file? Please explain the code for views.py and for related Html file. -
How to increment variable in Django template?
I was making a grid and need to declare the variable and increment it. {% for new, des, i, link, published, author in mylist %} {% if x == 1 %} <div class="col-md-6"> <div class="h-100 mt-2 row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">World</strong> <h5 class="mb-0">{{new}}</h5> <div class="mb-1 text-muted">{{published}}</div> <p class="card-text mb-auto">{{des}}</p> <a href="{{link}}" class="stretched-link">Continue reading</a> </div> <div class="col-auto d-none d-lg-block"> <img class="bd-placeholder-img" src="{{i}}" width="200" height="250" > </div> </div> </div> {% endif %} {% endfor %} Help me to declare variable x and increment it like x+1 inside the template I was trying {% with x=0 %} but that's not working -
TypeError: Object of type 'DoesNotExist' is not JSON serializable ( Django REST Framework)
Full traceback (heroku): 2020-03-24T16:11:47.624938+00:00 app[web.1]: Internal Server Error: /api/register_domain_name 2020-03-24T16:11:47.624949+00:00 app[web.1]: Traceback (most recent call last): 2020-03-24T16:11:47.624950+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner 2020-03-24T16:11:47.624951+00:00 app[web.1]: response = get_response(request) 2020-03-24T16:11:47.624952+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 158, in _get_response 2020-03-24T16:11:47.624952+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2020-03-24T16:11:47.624953+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response 2020-03-24T16:11:47.624953+00:00 app[web.1]: response = response.render() 2020-03-24T16:11:47.624953+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/template/response.py", line 106, in render 2020-03-24T16:11:47.624954+00:00 app[web.1]: self.content = self.rendered_content 2020-03-24T16:11:47.624954+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/response.py", line 72, in rendered_content 2020-03-24T16:11:47.624955+00:00 app[web.1]: ret = renderer.render(self.data, accepted_media_type, context) 2020-03-24T16:11:47.624955+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/renderers.py", line 105, in render 2020-03-24T16:11:47.624956+00:00 app[web.1]: allow_nan=not self.strict, separators=separators 2020-03-24T16:11:47.624956+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/utils/json.py", line 28, in dumps 2020-03-24T16:11:47.624957+00:00 app[web.1]: return json.dumps(*args, **kwargs) 2020-03-24T16:11:47.624957+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/json/__init__.py", line 238, in dumps 2020-03-24T16:11:47.624958+00:00 app[web.1]: **kw).encode(obj) 2020-03-24T16:11:47.624959+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/json/encoder.py", line 199, in encode 2020-03-24T16:11:47.624959+00:00 app[web.1]: chunks = self.iterencode(o, _one_shot=True) 2020-03-24T16:11:47.624960+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/json/encoder.py", line 257, in iterencode 2020-03-24T16:11:47.624961+00:00 app[web.1]: return _iterencode(o, 0) 2020-03-24T16:11:47.624961+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/utils/encoders.py", line 68, in default 2020-03-24T16:11:47.624962+00:00 app[web.1]: return super(JSONEncoder, self).default(obj) 2020-03-24T16:11:47.624962+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/json/encoder.py", line 180, in default 2020-03-24T16:11:47.624963+00:00 app[web.1]: o.__class__.__name__) 2020-03-24T16:11:47.624963+00:00 app[web.1]: TypeError: Object of type 'DoesNotExist' is not JSON serializable This happens when I call an api func: @api_view(['POST']) @permission_classes((IsAuthenticated,)) @authentication_classes((TokenAuthentication,)) @ensure_csrf_cookie @renderer_classes((JSONRenderer,)) def register_domain_name(request): if request.method …