Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
djongo.sql2mongo.SQLDecodeError: FAILED SQL: Error in django while filtering Data
i am trying to filter my product list with price less than filter but getting error. i guess the error is i am unable to pass parameters correctly. any help would be appreciated. if you require anymore details, please ask. Note: it does not works even if i pass the query on filter body static. thanks in advance. my method: def getfilter(request, format=None): kwargs = { '{0}__{1}'.format('price', 'lt'): Decimal('1000.00'), # '{0}__{1}'.format('name', 'endswith'): 'Z' } products = Product.objects.all().filter(**kwargs) serializer = ProductSerializer1(products, many=True) return Response(serializer.data) Error I Receive: Traceback (most recent call last): File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 806, in parse return handler(self, statement) File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 934, in _select self._query = SelectQuery(self.db, self.connection_properties, sm, self._params) File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 113, in __init__ super().__init__(*args) File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 74, in __init__ self.parse() File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 153, in parse raise SQLDecodeError djongo.sql2mongo.SQLDecodeError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/sunil/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/sunil/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/sunil/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/sunil/.local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/sunil/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) … -
How to perform upgrade and downgrade migrations in Django Framework
**I did migrations and I got some migration files like ** 0001_initial.py 0001_squashed_0008_delete_userfolder.py 0002_userfolder.py 0003_auto_20200130_1454.py 0004_auto_20200130_1512.py 0005_auto_20200130_1513.py 0006_auto_20200130_1514.py 0007_remove_userfolder_sir_name.py 0008_delete_userfolder.py Syntax python manage.py migrate app_name 0007_remove_userfolder_sir_name Output When I perform that downgrade migration it is not reflecting in the postgres DB -
Static files issue django
I've been searching for 2 days to display an image on the top of my admin page django app. I read several documentation and understood that the best way to do it is by static files. So I configured my app for displaying those static files, but django can't find those static files. I looked for passed topic about the same issue but none of the answers works. Here's my settings : """Django settings for pold project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ import os from django.contrib import admin # 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/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'my_key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['SERVER_IP'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'scrud.apps.ScrudConfig', ] MIDDLEWARE = [ '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 = 'pold.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
django many-to-many polymorphic annotation filtering by polymorphic_ctype
what I have: a target model related with Many-to-Many with polymorphic model. For each object in target model I want to aggregate max value of some common for polymorphic model column but for specific polymorphic model subclass. What I tried: ''' from django.db.models import Max, Q from django.contrib.contenttypes.models import ContentType from polymorphic.models import PolymorphicModel class manytomanymodel(PolymorphicModel): commonfloat = model.FloatField() class A(manytomanymodel): somefields = ... class B(manytomanymodel): someotherfields = .... class TargetModel(model.Model): manytomany = models.ManyToManyField(manytomanymodel) TargetModel.annotate(targetmax=Max("manytomany__commonfloat", filer=Q(manytomany___polymorphic_ctype=ContentType.objects.get_for_model(A))) ''' as a result I obtain: ''' /export/django/venv/lib64/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args) 82 return self.cursor.execute(sql) 83 else: ---> 84 return self.cursor.execute(sql, params) 85 86 def _executemany(self, sql, param_list, *ignored_wrapper_args): ProgrammingError: syntax error at or near "(" LINE 1: ... MAX("manytomany_manytomanymodel"."commonfloat") FILTER (WHERE "he... ''' The query seems to be absolutely legit for me, and works fine without the filtering -
Django server dies when try to connect /admin page
I'm trying to implement Restful API server using Django. I added admin urls like followings, but whenever I connect to admin page, Django server silently dies with return code 245. The last console was "GET /admin HTTP/1.1" 301 0" and nothing. urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/doc/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), ] What did I wrong? I have no AdminModels in admin.py. -
Error when saving a dataframe group by pandas to django models
I tried to create a dataframe grouped by pandas in django models, but got a KeyError as below KeyError:'GoodsID' I think there is a problem with the head of the dataframe when doing groupby as below Quantity GoodsPrice GoodsID GoodsIDSeqNo G1 1 1 1000.0 G2 2 1 0.0 G3 1 1 0.0 G4 1 2 4000.0 2 1 1000.0 G5 2 1 0.0 G6 1 1 2000.0 How can I combine columns in one line? -
NoReverseMatch at /login/ Reverse for 'password_reset' not found. 'password_reset' is not a valid view function or pattern name
I am having trouble with the login page for my django project. Everything works perfectly fine with localhost, but after deploying and going live it has this password_reset error. I have googled for 3-4 hours now but I do not have a solution for this error. It works perfectly fine on localhost, but not live. you can see it on roasitas.com/login/ if you want to see the problem p.s: I have set to DEBUG = False, the error message still appeared... why...? Thanks everyone! enter image description here urlpatterns = [ path('',include('news.urls', namespace="news")), path('admin/', admin.site.urls), path('register/', users_view.register, name='register'), path('profile/', users_view.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='users/password_reset.html', subject_template_name='users/password_reset_subject.txt', success_url=reverse_lazy('users:password_reset_done') ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='users/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( template_name='users/password_reset_complete.html' ), name='password_reset_complete'), # path('web/', include('django.contrib.auth.urls')), path('polls/', include('polls.urls')), path('api/', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('/tinymce/', include('tinymce.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django foreign key problem in the model from legacy database
I have created two tables on PosgreSQL Database. I have referenced a foreign key but in django i cant make it work. to_field is not working. ProgrammingError at /admin/applications/devicedetailline/ column device_dj_detail_line.org_id_id does not exist LINE 1: SELECT "device_dj_detail_line"."id", "device_dj_detail_line"... ^ HINT: Perhaps you meant to reference the column "device_dj_detail_line.org_id". class DeviceDetailHeader(models.Model): organization_ID = models.IntegerField(unique=True) organization_name = models.CharField(max_length=100) def __str__(self): return str(self.organization_name) class Meta: managed = False db_table = 'device_dj_detail_header' class DeviceDetailLine(models.Model): org_id = models.ForeignKey(DeviceDetailHeader,to_field='organization_ID', on_delete=models.CASCADE) label = models.CharField(max_length=250) value = models.CharField(max_length=250) display_flag = models.BooleanField(default=True) class Meta: managed = False db_table = 'device_dj_detail_line' -
django-import-export : import not working
I am trying to populate my database with .csv files with django-import-export module but I keep running in this error Line number: 1 - maximum recursion depth exceeded while calling a Python object 43, Sicilian, L, 0, 1,7, 45.7 whenever I try to populate my Pizza model through the admin UI. Here is my CSV admin.py from django.contrib.admin import ModelAdmin from import_export.admin import ImportExportModelAdmin from .models import Topping, Pizza, Sub, Pasta, Salad, Dinner class PizzaAdmin(ImportExportModelAdmin): def save_related(self, request, form, formsets, change): super(PizzaAdmin, self).save_related(request, form, formsets, change) form.instance.toppings.add(Topping.objects.get(name='Cheese')) @admin.register(Sub) class SubAdmin(ImportExportModelAdmin): pass # Register your models here. admin.site.register(Topping) admin.site.register(Pizza, PizzaAdmin) # admin.site.register(Sub) admin.site.register(Pasta) admin.site.register(Salad) admin.site.register(Dinner) models.py from django.contrib import admin from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save from django.core.validators import MinValueValidator, MaxValueValidator from django.contrib.auth import get_user_model # Create your models here. class Topping(models.Model): name = models.CharField(max_length=64) def __str__(self): return(f"{self.name}") class Pizza(models.Model): PIZZA_SIZES = ( ('S', 'Small'), ('L', 'Large'), ) pizza_type = models.CharField(max_length=64) pizza_size = models.CharField(max_length=1, choices=PIZZA_SIZES) qty_toppings = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3)], default=0) toppings = models.ManyToManyField(Topping, related_name='pizzas', blank=True) price = models.FloatField(help_text="Price in $") def __str__(self): return f"Size: {self.get_pizza_size_display()}, Type: {self.pizza_type}, Number of Toppings: {self.qty_toppings}, Price: {self.price}, Toppings: {self.toppings.in_bulk()}" def save(self, *args, **kwargs): # if … -
Google Authentication Django Social Auth2 django Rest Api
I want to implement a feature of google login, I am using django rest and reactjs,I have seen tutorial but they are on core django and I am facing difficulty,however after lot of research I have seen django social auth2 through which we can login with google using django rest,by getting token,but I am confused as I am unable to get how it is working,my progress so far: INSTALLED_APPS = [ ...... ...... # social-auth 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'solid_proto', 'templates', 'allauth')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ...... ...... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', # Google OAuth2 'social_core.backends.google.GoogleOAuth2', 'rest_framework_social_oauth2.backends.DjangoOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = key SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = Secret SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] It should happen like user will click on google login from react and then at backend an api will be hit along with user credentials(google username and password of user), if credentials are authenticated,then token would be returned which will further be used to access api's of system. Kindly guide me or share me some good resource in this thanks! -
The Django problem with "set.all" returns nothing in the template
Hi Stackoverflow people, You will help with the following. My urls: path('Autorow/szczegoły/<int:id>/', views.Szczegoly_autorzy, name='Szczegoly_autorzy'), My views: def Szczegoly_autorzy(request, id): autor = get_object_or_404(Author, pk=id) return render(request, 'Szczegoly_autorzy.html', {'autor': autor}) My models: class Author(models.Model): zdjecie_autora = models.ImageField(null=False, blank=True, upload_to='zdjecia_autorow') imie_nazwisko = models.CharField(max_length=100, unique=True) data_urodzenia = models.DateField(null=True, blank=True) informacje = models.TextField() def __str__(self): return self.imie_nazwisko class Book(models.Model): tytul = models.CharField(max_length=60, unique=True) autor = models.ForeignKey(Author, on_delete=models.CASCADE) opis = models.TextField(null=True, blank=True) rok_wydania = models.DateField(null=True, blank=True) zdjecie = models.ImageField(null=False, blank=True, upload_to='zdjecia_ksiazek') def __str__(self): return self.tytul Templates: {% for ksiazki in autor.ksiazki_set.all %} <li><a href="{% url 'Szczegoly_ksiazki' ksiazki.id %}">"{{ ksiazki }}"</a></li> {% endfor %} I don't see the list of books the author wrote in my templates. This is my second app and it works in the first one, but I don't know where I'm making a mistake here. Help me -
django.db.utils.InternalError: (1050, "Table 'django_content_type' already exists")
django.db.utils.InternalError: (1050, "Table 'django_content_type' already exists") I just copied a project from my friend, when I run makemirations it runs properly. But for - python3 manage.py migrate it gives this error - Operations to perform: Apply all migrations: admin, auth, balancesheet, contenttypes, dynapp, pandl2, sessions, trialbal2 Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 74, in execute return self.cursor.execute(query, args) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute result = self._query(query) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query conn.query(q) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/pymysql/connections.py", line 517, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/pymysql/connections.py", line 732, in _read_query_result result.read() File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/pymysql/connections.py", line 1075, in read first_packet = self.connection._read_packet() File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/pymysql/connections.py", line 684, in _read_packet packet.check_error() File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/pymysql/protocol.py", line 220, in check_error err.raise_mysql_exception(self._data) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/pymysql/err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.InternalError: (1050, "Table 'django_content_type' already exists") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output … -
What exactly is the parameter 'username' in authenticate function django?
From documentation about django.contrib.auth.authenticate function, we find - Use authenticate() to verify a set of credentials. It takes credentials as keyword arguments, username and password for the default case, checks them against each authentication backend, and returns a User object if the credentials are valid for a backend. Now, my question is what do they mean by username? Is it the name of the column of a model? Or is it a primary key to a model? Actually, I have been sending email as a username because I wanted to check credentials based on email rather than username (of course, whatever it means) but it didn't work... But I named one of a column of my model to username but it still didn't work... So, I wonder what do they mean by username exactly. My code that didn't work - email = request.POST['email'] #email = request.POST['username'] Changed email column-name to username but didn't work! password = request.POST['password'] user = authenticate(request, username=email, password=password) print (user) ## None -
Wagtail Texteditor upload image directly copy and paste
I am trying to implement a wagtail custom copy and paste the image directly to the text editor. is there anyone who knows about it? is it possible to implement it? if possible, how can I do it? -
How to add a vote when clicked on an html button django
this is my class: from django.db import models # Create your models here. class Voter_Form(models.Model): Voter_Name = models.CharField(max_length=30) Emirates_ID = models.IntegerField() Date_Of_Birth = models.DateField(auto_now=False,auto_now_add=False) Contact_Number = models.IntegerField() Email_ID = models.CharField(max_length=254) File_Upload = models.FileField(upload_to=None) Property_Registration = models.BooleanField(help_text='Enter Yes or No') #if we want to see sql code of this we would say #python manage.py sqlmigrate appname ### destination no def __str__(self): return self.Voter_Name class Candidate_Form(models.Model): Candidate_Name = models.CharField(max_length=30) Emirates_ID = models.IntegerField() Date_Of_Birth = models.DateField(auto_now=False, auto_now_add=False) Contact_Number = models.IntegerField() Email_ID = models.CharField(max_length=254) File_Upload = models.FileField(upload_to=None) Message_To_The_People = models.CharField(max_length=200) Video_Upload = models.FileField(upload_to=None) def __str__(self): return self.Candidate_Name class Election_Info(models.Model): Election_ID = models.IntegerField(primary_key=True) Tower_Name = models.CharField(max_length=30) Voting_Date_Time = models.DateTimeField(auto_now=False, auto_now_add=True) Voting_Location = models.CharField(max_length=50) Campaign_Info = models.CharField(max_length=250) Closing_Date = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return self.Tower_Name class Election_Day(models.Model): Can_ID = models.ForeignKey('Candidate_Form', on_delete=models.CASCADE) #you refer the primary key to the whole class and it will automatically pick the id (primary key) of that class and make it a foreign key Elec_ID = models.ForeignKey('Election_Info', on_delete=models.CASCADE) #with that you can also access all the data stored in that table Vote = models.IntegerField(default=0) def __str__(self): return self.Can_ID this is my views: from django.http import HttpResponseRedirect from django.shortcuts import render from election_information.models import Voter_Form from election_information.models import Candidate_Form from election_information.models import Election_Info … -
Insert data in model using loop
model.py class Tag(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) def __str__(self): return self.name class Question(models.Model): name = models.CharField(max_length=255) Tag_name = models.ManyToManyField(Tag) def __str__(self): return self.name I want to enter more than 10000 data in Question model so i am using loop for this, but it did not work, how can i enter data using loop in Question Model. I tried: for i in range(1,3): p = Question(name='a'+str(i),Tag_name = 2) #id of tag and p.save() I know i am doing wrong. -
uwsgi: unrecognized option: socket 0.0.0.0:80
I try to run Django project using uwsgi in docker container, and deploy it to ECS Container. When I try to login admin site I couldn’t able to login and Cloudwatch send this log uwsgi: unrecognized option: socket 0.0.0.0:80 getopt_long() error In docker file I run uwsgi using this command. CMD ["uwsgi", "--socket 0.0.0.0:80", "--protocol=http", "--module bghd.wsgi”] So I changed command little bit differently but still get similar error. CMD ["uwsgi", "--http :80", "--module bghd.wsgi"] I'm using Alpine for OS -
Django: How to annotate queryset to return filtered objects?
Here is a simplified app: class Restaurant(models.Model): # ... class Article(models.Model): # articles belong to one restaurant restaurant = models.ForeignKey(Restaurant) class Convive(models.Model): # convive are users related to one restaurant. @property def linked_restaurant(self) -> Restaurant: pass # this returns the restaurant of the convive class Discount(models.Model): # discounts are applied on articles of multiple restaurants articles = models.ManyToManyField(Article) convives = models.ManyToManyField(Convive, through=ConvivesByDiscount) class ConvivesByDiscount(models.Model): """ Mapping table for M2M between Convive and Discount """ # a discount is usable by a convive, using this object. convive = models.ForeignKey(Convive) discount = models.ForeignKey(Discount) remaining_usages = models.PositiveIntegerField() What I Want to achieve I want to show my convives, the discounted articles that are related to the same restaurant than them. Here is a concrete example. Let's define : 2 restaurants: Fiveguy and McDonalds. 2 convives : John, customer of Fiveguy, and Tom, customer of McDonalds. 2 restaurant articles : Fiveguy Coffee and McDonalds IceCream 1 discount that applies -10% on both articles. John and Tom can use the discount (ConvivesByDiscount object). Now, given this discount object, I'd like to: show to John he has -10% on Coffee show to Tom he has -10% on IceCream My current code I return the convive usable … -
How to use getlist() in django
as you can see in my views.py I have 3 loops and 3 getlist() but only one table use to save the data for amount in request.POST.getlist('amount'): pass for date in request.POST.getlist('date'): pass for each in request.POST.getlist('remark'): insert_StudentPaymentSchedules = StudentPaymentSchedules( Students_Enrollment_Records = V_insert_data, Amount = amount, Payment_Schedule = date, Remarks = each ) insert_StudentPaymentSchedules.save() this is the result if you guys notice that the remarks are correct and the Payment Schedule and Amount is wrong, I have a problem for looping the 3 getlist() -
Google Auth using social-auth-app-django on project(Django + React)
I have project with Djang + React and I need using Google OAuth2 to authenticate user login. Looks like social-auth-app-django is popular package to use for Django, and I had a search on how to use it. But I could not find any example with React on frontend. I can see a lot of examples with a button implemented by Djang templates like this. <a class="btn btn-primary" href="{% url 'social:begin' 'google-oauth2' %}"> Login </a> But what it should be pointing to with a React Login button? And should I pass Google OAuth2 Key or Google OAuth2 Secret from React to Django? -
Django Rest Framwork - Select only some fields in reverse lookup queryset
I'm trying to retrieve only some of the fields in the "Appointments" associated to a rental property "Unit". From the UnitSerializer, I call a SerializerMethodField() to do a reverse lookup for the "appointment" field. This works out well. However, the queryset returns all the fields (id, time, unit, staff, prospect) in each object, when I only need a few (id, time). I tried .values() on the queryset like so: queryset = instance.appointment_set.values('id', 'appointment_time') But I get "Got KeyError when attempting to get a value for field unit on serializer AppointmentSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the dict instance.\nOriginal exception text was: unit." Note sure if you need all the code, but here's the essential. Models class Appointment(models.Model): appointment_time = models.DateTimeField() unit = models.ForeignKey(Unit, on_delete=models.CASCADE) staff = models.ForeignKey(Staff, on_delete=models.CASCADE) prospect = models.ForeignKey(Prospect, on_delete=models.CASCADE) Serializers class AppointmentSerializer(serializers.ModelSerializer): class Meta: model = Appointment fields = ['id','appointment_time'] class UnitSerializer(serializers.ModelSerializer): appointment = SerializerMethodField() class Meta: model = Unit fields = ['id', 'address', 'appointment'] def get_appointment(self, instance): queryset = instance.appointment_set return AppointmentSerializer(queryset, many=True).data -
Django Rest Framework Limiting get_queryset result to not include all fields
view.py class charity_totals(generics.ListAPIView): serializer_class= CharityTotalSerializer queryset=Transaction.objects.all() def get_queryset(self): queryset = super().get_queryset() user_id = self.request.GET.get('userID') if user_id is None: return queryset queryset = queryset.filter(userID=user_id) return queryset.values('charityID').annotate(total_donation=Sum('transactionAmount')) serializer.py class CharityTotalSerializer(ModelSerializer): charity_name= serializer.ReadOnlyField(source='charityID.charityName') total_donation= serializer.DecimalField(max_digits=64,decimal_places=2) class Meta: model = Transaction fields = ['charity_name','total_donation'] model class Transaction(models.Model): transactionAmount = models.DecimalField(max_digits=6, decimal_places=2) userID = models.ForeignKey(User,on_delete=models.CASCADE) charityID = models.ForeignKey(Charity,on_delete=models.CASCADE, related_name='charity_set') processed = models.BooleanField(auto_created=True, default=False) transactionDate = models.DateField(auto_now_add=True) Off of a request such as this http://localhost:8000/requests/charitytotal/?userID=1 my json response is limited to just the [{"total_donation":"3.00"},{"total_donation":"17.00"}] and is not including the charity names that are specified in the serializer. From what I understand the .values should return a dict of both the charityID and the total_donation that was specified which should be able to interact with my serializer. Any Insight would be appreciated -
Use get_object_or_404 to get only one field rather than all fields specified in model in django rest framework?
I am trying to get just one field as a result from get_object_or_404 but it is not seem to be working for me. I am using the User model from the default auth app of django. This is my serializer: class UserSerializer(serializers.Serializer): username = serializers.CharField(max_length=150) email = serializers.EmailField(max_length=254) first_name = serializers.CharField(max_length=30) This is my view: class UserView(APIView): def get(self, request, id=None): if id: data = get_object_or_404(User.objects.only('username'), id=id) serializer = UserSerializer(data, many=False) return Response(serializer.data) else: data = get_list_or_404(User) serializer = UserSerializer(data, many=True) return Response(serializer.data) Even after using this get_object_or_404(User.objects.only('username'), id=id) I am still getting all the fields specified in the serializer rather than just the username. This is the response i get when i pass an id to the api while calling it from the postman. { "username": "admin", "email": "admin@email.com", "first_name": "" } rather than this: { "username": "admin", } -
how can i get in between first and last product image set in django restframework
how can i get in between first and last product image set in django restframework i have maximum ten product image set, in my case i am able to get first and last product image set. how can i get in between first and last product image set. any help, would be appreciated. how can i get in between first and last product image set models.py class Product(models.Model): title = models.CharField(max_length=30) slug= models.SlugField(blank=True, null=True) sku = models.CharField(max_length=30) description = models.TextField(max_length=200, null=True, blank=True) instruction = models.TextField(max_length=200, null=True, blank=True) price = models.DecimalField(decimal_places=2, max_digits= 10,) discount_price= models.DecimalField(decimal_places=2, max_digits= 10, null=True, blank=True) category = models.ManyToManyField('Category', ) default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True, on_delete=models.CASCADE) created_on = models.DateTimeField(default=timezone.now) updated_on = models.DateTimeField(null=True, blank=True) status = models.BooleanField(default=True) class Meta: ordering = ["-id"] def __str__(self): #def __str__(self): return self.title def get_absolute_url(self): return reverse("product_detail", kwargs={"pk": self.pk}) def get_first_image_url(self): img = self.productimage_set.first() if img: return img.image.url return img #None def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(pre_save_post_receiver, sender=Product) def image_upload_to(instance, filename): title = instance.product.title slug = slugify(title) basename, file_extension = filename.split(".") new_filename = "%s-%s.%s" %(slug, instance.id, file_extension) return "products/%s/%s" %(slug, new_filename) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to=image_upload_to) created_on = models.DateTimeField(default=timezone.now) status = models.BooleanField(default=True) def … -
How to get access token from Django REST Framework Social OAuth2 using Alamofire
I implemented social auth backend to Django server using Django REST framework social oauth2(created by Realm team) https://github.com/RealmTeam/django-rest-framework-social-oauth2 Any api requests other than getting access token from Django REST framework social oauth2 are working correctly. Correct response using Postman I get correct response when I made a request using Postman I hided response area from the screen shot since they contain actual tokens but I got correct response. Invalid client error using Alamofire I get SUCCESS response from Alamofire but inside the response stated error "invalid_client" SUCCESS: { error = "invalid_client"; } let params: [String: String] = [ "grant_type" : "convert_token", "client_id" : "<client id here>", "client_secret": "<client secret here>", "backend" : "facebook", "token" : "<facebook token here>", ] Alamofire.upload( multipartFormData: { multipartFormData in for param in params { let data = Data(param.value.utf8) multipartFormData.append(data, withName: param.key) } }, to: "http://127.0.0.1:8000/api/auth/convert-token", encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in let responseData = response print(responseData ?? "success") } case .failure(let encodingError): print(encodingError) } } ) Do I need to change some settings on Django backend to allow request from iOS application?