Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Next Auth - OAUTH_GET_ACCESS_TOKEN_ERROR
I'm trying to implement oauth in my next.js app. for backend I'm using Django ODIC Provider and Next Auth for the front-end. but I'm getting an error: { "error": "invalid_grant", "error_description": "The provided authorization grant or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client" } How can I fix this ? I have created a file named: [...nextauth].js in /api/auth/ and added my custom provider. Here's how my env looks like: NEXTAUTH_URL = http://localhost:3000 CLIENT_ID = 466647 CLIENT_SECRET = 079e7fe518e245cb316701faa19ec463c0073fba25d1e51c2db996ab SCOPES = openid profile email and [...nextauth].js: import NextAuth from 'next-auth' export default NextAuth({ providers: [ { id: "pullstream", name: "Pullstream", type: "oauth", version: "2.0", scope: process.env.SCOPES, params: { grant_type: "authorization_code" }, accessTokenUrl: "https://accounts.dev.pullstream.com/api/openid/token/", requestTokenUrl: "https://accounts.dev.pullstream.com/api/accounts/login/", authorizationUrl: "https://accounts.dev.pullstream.com/api/openid/authorize/", profileUrl: "https://accounts.dev.pullstream.com/api/accounts/profile/", async profile(profile, tokens) { console.log(profile, tokens) }, clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET } ], }) -
Scraping Bing or Google in Django
I am building a search engine for only men's apparel in django, so I need help in scraping Bing or Google and using custom querying to get only men's apparel results. body { font-size: 10pt; font-family: arial, sans-serif; } a { text-decoration: none; } a:hover { text-decoration: underline; } button { font-weight: bold; font-family: arial; } /* Top Toolbar */ .top-toolbar { height: 50px; } .top-toolbar nav { float:right; margin: 7px 21px; } .top-toolbar nav a { margin: 3px 6px; color: #404040; } .top-toolbar nav a:hover { color: #111111; } .top-toolbar nav button { padding: 7px 12px; border-radius: 2px; /* background-color: #4585F1;*/ background-image: -moz-linear-gradient(top left, #4084F9 0%, #4585F1 100%); background-image: -o-linear-gradient(top left, #4084F9 0%, #4585F1 100%); background-image: -webkit-gradient(linear, left top, right bottom, color-stop(0, #4585F1), color-stop(1, #0097DE)); background-image: -webkit-linear-gradient(top left, #4084F9 0%, #4585F1 100%); color: white; border: 1px darkblue; font-size: 9.5pt; } .top-toolbar nav button:hover { box-shadow: 1px 1px 0 rgba(0,0,0,.2); } .top-toolbar nav img { margin: 0 7.5px; height: 22px; position: relative; top: 7px;} /* End of Top Toolbar */ /* Search */ .search { text-align: center; clear: both; margin: 11% 0 0 0; } .logo { max-width: 21%; margin: 0 auto; } .search img { margin-bottom: 3%; max-width: 100%; … -
How to model a database to a Dynamic HTML Form?
I'm trying to make a POST REQUEST to link Dynamic HTML form (when you push the add button, will add another textbox, like in the photo) into Django's default database. Right now I have the following issue, every time I submit data, it only saves the last row. How is the best way to model database and HTML form to save that data ? Any documentation is appreciate it ! Infraestructura.html {% extends "Portafolio/layout.html" %} {% load static %} {% block scripts %} <script src = "{% static 'Portafolio/scriptinfra.js' %}" type="text/javascript"></script> {% endblock %} {% block content %} <form action= "{% url 'infraestructura' %}" method="POST" class="form mt-5" id="infra"> {% csrf_token %} <h1>Factibilidad Técnica y Operativa</h1> <h2>Análisis de Infraestructura</h2> <main class="container"> <section class="row"> <div class="col-lg-4 mb-2"> <input name='Infraestructura' class="form-control" type="text" placeholder="Infraestructura"> </div> <div class="col-lg-4 mb-2"> <input name='Tiempo' class="form-control" type="text" placeholder="Tiempo"> </div> <div class="col-lg-4 mb-2"> <input name='Costo' class="form-control" type="text" placeholder="Costo Mensual"> </div> </section> </main> <nav class="btn-group"> <button id='add' class='btn btn-success' type='button'> <i class="fa fa-plus-square"></i> Añadir </button> <button id='rem' class='btn btn-danger' type='button'> <i class="fa fa-minus-square"></i> Eliminar </button> </nav> <!-- Submit buttom--> <div class="d-grid gap-2 mt-3"> <input type="submit" class="btn btn-lg btn-primary"> </div> </form> {% endblock %} models.py from django.db import models # Create your … -
Saving username to model in Django
I am creating a donation app that allows donors to create listings. This data is stored in a Django Model and is going to be displayed on a page. I want to save the user's username to the Django model and display it on the page. My code is down below Models.py class Donation(models.Model): title = models.CharField(max_length=30) phonenumber = models.CharField(max_length=12) category = models.CharField(max_length=20) image = models.CharField(max_length=1000000) deliveryorpickup = models.CharField(max_length=8) description = models.TextField() Views.py from django.contrib.auth.models import User from django.http.request import RAISE_ERROR from django.http.response import HttpResponseRedirect from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import forms, inlineformset_factory from django.contrib.auth.forms import UserCreationForm, UsernameField from .forms import CreateUserForm from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from home.models import Donation # Create your views here. def index(request,*args, **kwargs): return render(request, "index.html", {} ) @login_required(login_url='/login/') def dashboard(request,*args, **kwargs): return render(request, "dashboard.html", {} ) def register(request, ): if request.user.is_authenticated: return redirect('/dashboard/') else: form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been successfully created, {username} ') return redirect('loginpage') context = {'form': form} return render(request, "register.html", context ) def loginpage(request): if request.user.is_authenticated: … -
Error starting django. server, because: ModuleNotFoundError: No module named 'djoser'
I can't run my server in django. When I attempt to start it with python3 manage.py runserver I recieve the error message: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'djoser' I'm not sure what I'm doing wrong, becase djoser is in my installed apps in my settings.py file. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'djoser', 'accounts', 'social_django', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist' ] I've been looking at it, and can't figure out what's wrong. Would anyone have suggestions? -
I have removed a form from formset. now form submit not working on button click (Django)
I'm having a Formset which contains forms as Adventure Details, Adventure Pictures, and Adventure Pricing. Now I have removed Adventure Pricing form from formset, from formset.py file and frontend code also. Now while clicking on Update Adventure button, which is used for submitting formset and which was working earlier is now refreshes and loads the same page without updating anything. Please forgive this question rather than downvoting for not including any code -
Form doesn't display in template - Django
I try to create a form in Django's app but nothing display in browser. app.models.py from django.db import models class Scrap(models.Model): query = models.CharField(max_length=100) author = models.CharField(max_length=100) date = models.DateTimeField('date scrapped') h3 = models.TextField(max_length=500) links = models.TextField(max_length=10000) meta = models.TextField(max_length=10000) app.forms.py from django.forms import ModelForm from app.models import Scrap class ScrapForm(ModelForm): class Meta: model = Scrap fields = ['query',] app.views.py def get_query(request): if request.method == 'POST': form = ScrapForm(request.POST) if form.is_valid(): print('coucou') return redirect('/scrapping') else: form = ScrapForm() return render(request, "scrapping.html", {'form': form}) scrapping.html <form class="navbar-search form-inline mr-3 d-none d-md-flex ml-lg-auto post-form" action="" method="POST">{% csrf_token %} <div class="form-group mb-0"> <div class="input-group input-group-alternative"> <div class="input-group-prepend"> <span class="input-group-text"><i class="fas fa-search"></i></span> </div> {{ form }} <input class="input-group-text" type="submit" value="OK" style="color:initial"> </div> </div> </form> When I inspect html page, form doesn't exist. Could you help me please ? -
Implementing Last Viewed functionality in Django
Am still a newbie but I want to implement "last viewed" functionality in my project and I want this functionality to be user specific. I want to show the users the last 10 objects that they viewed. how can I achieve this. I have seen similar problems with solutions but they are for single models, I want to do use multiple models here. Below is my models class Fblink(Link): class Meta: db_table = "Facebooklinks" get_latest_by = ['-watched_num', 'updated_at'] ordering = [F('user').asc(nulls_last=True)] verbose_name = "Fblink" verbose_name_plural = "Fblinks" class Twlink(Link): class Meta: db_table = "Twitterlinks" get_latest_by = ['-watched_num', 'updated_at'] ordering = [F('user').asc(nulls_last=True)] verbose_name = "TWlink" verbose_name_plural = "TWlinks" -
migrations folder have turned into .pyc files - can no longer run makemigrations
For some reason my migration-files now all are moved into the folder migratios/__pycache__ and turned into .pyc files. I have created a new model, and running python manage.py makemigrations returns No changes detected. Does the .pyc impact Django? How can I make my migration now? How do I stop this problem from happening again? -
how to use default django auth model in react , i want to access api that needs authentication in react?
currently i am using default django auth User model for authentication purposes like registering a new user, login a user and logout a user and now i want to access the authentication required API's in React so how to achienve that if that's not possible what should i do please briefly guide me , currently i am using Django Rest Framework my urls.py from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from authentication import views as authentication_views urlpatterns = [ path('admin/', admin.site.urls), path('', include('liveclass_api.urls')), path('login/', auth_views.LoginView.as_view(template_name='authentication/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='authentication/logout.html'), name='logout'), path('register/', include('authentication.urls')), my login.html ** <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Login</legend> {{form}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info pt-3" type="submit">Login</button> </div> </form> <div class='border-top pt-3'> <small class='text-muted'> Want to get an account? <a class='ml-2' href={% url 'register' %}>Sign up now</a> </small> </div> </div> I am writing register or logput template as they are quite same, i want to modify this authentication or will have to use a new one to work with react Please help me in this process and apologies if not following the stackoverflow formatting guide as i am new to it Thanks -
ERR_BLOCKED_BY_CLIENT when I try to use geocodign api in js
I am trying to execute the following script (that is in moovit_script.js). I need to use reverse geocoding but I obtain an ERR_BLOCKED_BY_CLIENT in js console. lat, lng and status are ok, but destination address is ''. function set_moovitmap() { var m = document.getElementById('mapa_moovit'); const origin = window.opener.origin_ad; m.setAttribute("data-from-lat-long", window.opener.origin_coordinates); const lat = window.opener.latD; const lng = window.opener.lonD; const geocoder = new google.maps.Geocoder(); const latlng = { lat: parseFloat(lat), lng: parseFloat(lng), }; destination_address = ''; // window.alert(latlng.lat); geocoder.geocode({ location: latlng }, (results, status) => { if (status === "OK") { if (results[0]) { destination_address = results[0].formatted_address; } } }); window.alert(destination_address); m.setAttribute("data-from", origin); if (destination_address != '') { m.setAttribute("data-to", destination_address); } } I am using django and I have tried to execute this function in a html file: {% load static %} <script src="{% static 'moovit_script.js'%}"></script> <!-- <script src="{% static 'google_maps.js'%}"></script> --> <script src="https://maps.googleapis.com/maps/api/js?key=myKey&libraries=places"> </script> <div class="mv-wtp" id="mapa_moovit" data-to='' data-from='' data-from-lat-long='' data-lang="es"> <script> set_moovitmap(); </script> Thank you. -
NGINX redirects port 80, works well for other ports
My django runs on 127.0.0.0:8000 My nginx nginx conf is below worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location /{ proxy_pass http://127.0.0.1:8000/; } } } When I type localhost in browser, it redirects (url changes in the address bar) to 127.0.0.1:8000 instead of reverse proxying. when I listen on other ports such as 8001, it reverse proxies as expected Why it doesn't work as expected for listening on port 80? -
How to redirect already authenticated users from login page to home in django?
I'm trying to redirect users who are already authenticated to the home page, so they can't access the login page while they are logged in. This was easily doable for my registration page as its leveraging a function in views.py, but seems to be harder to do for the login page as its leveraging django.contrib.auth.urls (so without a function in views.py). So my question is: how can I redirect users to a specific page without going through a view function? In this case, the mydomain.com/login/ page should redirect to mydomain.com when a users is already logged in. urlpatterns = [ path('admin/', admin.site.urls), path('', homepage), path('registration/', registration), path('', include('django.contrib.auth.urls')), ] -
Django super().save and get_or_create conflict
Inside my Django models under Movies table I have a super().save function. I also have a scraper inside my views.py in another app, that scrapes some data and inserts them using get_or_create() into the Movies table that has the super().save function in it. My problem is that When I try to scrape data and create them using get_or_create(), it gets created twice. I noticed when I comment the super.save() function in my models.py, the problem is solved. How can I have them both together? How can I prevent super.save() from happening when I'm scraping? Thaks in advance for your help. -
SQLite 3.8.3 or later is required (found 3.7.17) 0 0 vote positif
I am trying to eb deploy some Django app. But I face this error. File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/utils.py", line 201, in __getitem__ backend = load_backend(db['ENGINE']) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/opt/python/run/venv/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 66, in <module> check_sqlite_version() File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 63, in check_sqlite_version raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). (ElasticBeanstalk::ExternalInvocationError) I use Django3.1, I've tried downgrading to 2.1 but it won't work neither. File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'PosixPath' is not iterable. container_command 01_migrate in .ebextensions/db-migrate.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2021-06-22 15:34:35 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2021-06-22 15:34:35 ERROR Unsuccessful command execution on instance id(s) 'i-0c5bbcb2318daa82b'. Aborting the operation. 2021-06-22 15:34:35 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. I don't quite understand what's going on here, I'd use some help. -
django multiple user with multiple groups problem at signup
here is my problem, I created 3 groups with django admin panel ('admin', 'prof', 'etudiant' but I don't use the group admin for the moment). I created two model classes which inherit from the User model with oneToOneField ('Professeur' and 'Etudiant'). I also create a registration form for all two model classes. Using django post_save I can register my different users with groups. but now if I try to register a new user 'Professeur' with its own register form for example it is automatically added to the two groups 'prof' and 'etudiant'. what to do so that a user belongs to only one group etudiant/models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import RegexValidator class Etudiant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) et_matricule_regex = RegexValidator(regex=r'^(ET)-[A-Z]{2}-(PM)-[\d]{4}$', message="ex: ET-AD-PM-2020 -> Etudiant - Ali Diop - Pierre Michel- 2020") et_numero_matricule = models.CharField(validators=[et_matricule_regex], max_length=40, unique=True, verbose_name="numéro matricule") et_lieu_de_residence = models.CharField(max_length=150, blank=True, verbose_name="lieu de résidence") et_date_de_naissance = models.DateField(null=True, blank=True, verbose_name="date de naissance") et_telephone_regex = RegexValidator(regex=r'^\+?[\d]{3}-[\d]{2}-[\d]{2}-[\d]{2}-[\d]{2}$', message="+000-00-00-00-00") et_telephone = models.CharField(validators=[et_telephone_regex], max_length=40, blank=True, verbose_name="telephone") professeur/models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import RegexValidator class Professeur(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) prof_matricule_regex = RegexValidator(regex=r'^(PR)-[A-Z]{2}-(PM)-[\d]{4}$', message="ex: PR-ZT-PM-2017 -> Professeur - Zan Togola - … -
NameError During Migrations for Django
I am trying to make migrations but am getting a NameError: name 'Product' is not defined and am not really sure why. I assume it may be something simple but I cannot for the life of me figure it out. The error is happening on line 13(class Orders... is line 12 for quick reference). My models are as follows: from django.db import models from django.contrib.auth.models import User from django.core.validators import MinLengthValidator from phone_field import PhoneField class MyUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=255) phone = PhoneField(help_text='Contact Phone Number') class Orders(models.Model): products = models.ForeignKey(Product, on_delete=models.CASCADE) date_ordered = models.DateTimeField(auto_now=True) quantity_ordered = models.PositiveSmallIntegerField() price = models.PositiveIntegerField() user = models.OneToOneField(MyUser, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=120) description = models.CharField(max_length=255) price = models.PositiveIntegerField() style = models.CharField(max_length=50) artist = models.OneToOneField(Artist, on_delete=models.SET_NULL) class Review(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE) rating = models.DecimalField(max_digits=2, decimal_places=1) comment = models.TextField(validators=[MinLengthValidator(10)]) product = models.OneToOneField(Product, on_delete=models.SET_NULL, null=True) class Artist(models.Model): name = models.CharField(max_length=255) -
uuid.uuid4() not creating random UUID in DJango forms
I have a product creation form in Django admin space. In the product creation form I have a clean product ID method: forms.py import UUID def clean_pk_product_id(self, *args, **kwargs): pk_product_id = uuid.uuid4() return pk_product_id For some reason, this is not generating a random UUID, it will attempt to use a 'pre-determined' ID. I have attempted to create multiple new objects, and all throw the same error stating that the primary key is not unique, and gives the same UUID > (3e18d2da4f624649a7cfa310108a1421) Is there something wrong with the way I am handling the validation of this form? I am unsure how Django admin processes these forms... -
Displaying data retrieve through GraphQL in a django website
(Disclaimer : I'm just getting started with django, and with web dev in general) I have a backend app that stores different kinds of resources. Some are public and some are private. The application is accessible only to identified users. A GraphQL API allows me to access the resources. On another server, I'd like to create a website that will be accessible to everyone. I want to use django to create it. The website will display a list of resources tagged as "public" in the backend app, with a pagination system and, say, 20 resources by page. The CSS will differ from the backend app and there will be a search section. From what I understant, I should be able to retrieve the data through the GraphQL API, but I'm a bit confused here. All doc and tutos I can find about django and GraphQL seem to be about setting up a GraphQL API server with django. All I want to do is to build custom queries and to display them on my different html pages. How can I do that? Where should I start? Any hint or direction will be much appreciated, thank you! -
From Django to Angular - Create dynamic "Fill in blank" and "Multiple choices" questions/exercises
I created years ago a website with Django, where a teacher can add dynamic questions and exercises. For example, Fill in blank or Multiple choices questions, like this one : "Rabbits eats (multiplechoices: apples,carrots,tomatoes) and live in a (fillinblank: burrow)." This question will display a dropdown with 'apples','carrots' and 'tomatoes' choices first, and a text input for the 'burrow' answer. Of course, a question may contains any number of dropdowns or inputs. With Django, it was pretty simple to parse the text from db and replace special patterns (representing input or dropdown) with the right answers when rendering the HTML. I found that with Angular, I can use the same solution, as described here, but I don't know if it's a safe solution. I also read something about Component Factory in Angular, but I don't really figure out how to implement it. The goal is to be able to display all the exercises stored in my db in a brand new Angular web app. Any suggestion would be welcome. Thanks for reading ! -
How to map the response and save it to the database in Django?
I have a Person model: class Person(AbstractBaseUser): userName = models.CharField(max_length=100, unique=True, null=False, blank=False) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) dateOfBirth = models.DateField(null=True, blank=True) In my serializers.py I have this: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' def create(self, validated_data): userName = validated_data['userName'] is_active = validated_data['is_active'] staff = validated_data['staff'] admin = validated_data['admin'] dateOfBirth = validated_data['dateOfBirth'] user = Person(userName=userName, is_active=is_active, staff=staff, admin=admin, dateOfBirth=dateOfBirth) user.set_password("") user.save() return user Then in my views.py I use the serializer like this: class PersonList(generics.ListCreateAPIView): permission_classes = (permissions.AllowAny,) serializer_class = PersonSerializer def post(self, request, format=None): serializer = PersonSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now, this works as supposed to when I send the request from the client with the Person data. But what I'd like to do now is to modify my API so that it would receive a request from the client with no Person information, just a verification code or something like that. After that the back end would send a request to an external API and as a response my app would receive that Person data. I'm wondering what would be the best way to apply these changes. Do I just modify my serializer to … -
How to combine querysets retaining annotate fields?
I have two different queries for the same table: m_i = MyModel.objects.filter( user__profile__newsletter=True ).annotate(name=F('user__profile__complete_name'))\ .values('name')\ .annotate(indicado=Count('user'))\ .order_by('user__profile__complete_name') and m_e = MyModel.objects.filter( user__profile__newsletter=True, chosen=True)\ ).annotate(name=F('user__profile__complete_name'))\ .values('name')\ .annotate(escolhido=Count('user'))\ .order_by('user__profile__complete_name') The queries are very much the same except for one filter in the second and I annotate this same value for the both of them but they come out with different values. Right now the querysets are like this: # m_i [{name:'ex1', indicado: 1}, {name:'ex2', indicado: 2}, {name:'ex3', indicado: 9}, {name:'ex4', indicado: 3}] # m_e [{name:'ex1', escolhido: 1}, {name:'ex2', escolhido: 1}, {name:'ex3', escolhido: 4}, {name:'ex4', escolhido: 2}] I wanted to unite the querysets so I could have something like this: # union [{name:'ex1', escolhido: 1, indicado: 1}, {name:'ex2', escolhido: 1, , indicado: 2}, {name:'ex3', escolhido: 4, , indicado: 9}, {name:'ex4', escolhido: 2, , indicado: 3}] I tried using the method union like this m_i.union(m_e) but it seems as if it assumes that indicado and escolhido are the same thing and retains only one of the two. Using itertools.chain returns to me the both querysets one after the other, not united by the same key. Is there a way to union them both without iterating on the querysets? I can go over all of … -
best way to integrate 2checkout with django
I know(maybe) it's silly question, but just sucked in to it. I'm building an eCommerce website using django, where i need to use 2checkout payment gateway, i'm wondering if there is a package, tutorials or anything that helps me(almost 3days searching about.. I've no idea if it's possible) :| -
How to determine the type of a querset in django
How can I check to know the 'TYPE' of my database queryset. I want to use an 'IF' statement to do something when a certain condition is met but I don't know how to go about it. def tot_query(request): fb = Fblink.objects.all() tw = Twlink.objects.all() yt = Ytlink.objects.all() th = Thlink.objects.all() ig = Iglink.objects.all() sc = Sclink.objects.all() tk = Tklink.objects.all() query = chain(fb, tw, yt, th, ig, sc, tk) print(type(list(query)[0])) if type(list(query)[0]) == 'src.link.models.Fblink': print("This is a facebook link") The first print statement prints the following <class 'src.link.models.Fblink'> and the second and one prints nothing. -
How to display Logs of Django middleware in terminal
I created my own Middleware to validate HTTP-Requests. To make sure everything works fine, I added some logs into the code. I excpect that they will be display in the terminal (if reached obviously). import logging LOG = logging.getLogger(__name__) class ValidationMiddleware: # init-Method is called once the server starts def __init__(self, get_response): self.get_response = get_response # call-Method is called for every new request to the Django application def __call__(self, request): # Code to be executed before middleware is called validate_settings = settings.VALIDATIONMIDDLEWARE.get("default") token_header = 'X-Token' if token_header in request.headers: request_token = request.headers[token_header] url = validate_settings.get("VALIDATE_URL") md5_token = hashlib.md5(request_token.encode('utf-8')).hexdigest() payload = {'checksum': md5_token} LOG.info("Calling" + url + " to validate token.") req = requests.post(url, json=payload) result = req.json() if result['result'] is False: LOG.info("Token not valid anymore.") raise PermissionDenied else: LOG.info("Big Error") requests.HTTPError() response = self.get_response(request) return response I start my django server and did some Post requests (created users via admin, login, etc.), but none of the Logs in the code was displayed in the terminal. Why?