Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overview of using Authorization Code grant type to authenticate a user in django
I have a django app that Im using drf and ReactJS for my frontend and token authentication. I've been messing around with various packages in Django so that I can implement Social Authentication. I was using implicit authorization but am wanting to switch to an Authorization Code Grant Type. I have been able to make the request, redirect to a callback url on my server where I am able to make a post request to get the user data, refresh token and access token. This is where I have gotten a little stuck because Im not sure how to return those tokens to the frontend. After I authenticate I need to be able to redirect to a "success" page but dont know how to inlcude the access token in that redirect. I know I could use django sessions and just store the tokens there and use that for my authentication but I was hoping to use Token authentication where the user includes their access token to access secure data. I was able to come up with two "working" solutions. With Set-Cookie response = HttpResponseRedirect("/login-success") response.set_cookie("access_token", "<access_token>") return HttpResponseRedirect Appending <access_token> return HttpResponseRedirect("/login-success#<access_token>") # parse token when page is reached I … -
Order Django queryset by annotated field and annotate it again
I need to order Django queryset by annotated field and then annotate result with row number. Steps: Add complex_order field to QuerySet that defines extra logic for future ordering. Order QuerySet by new field and old fields (complex_order, order and id) Annotate sorted QuerySet with number using RowNumber() function. Sample code that almost works queryset.annotate( complex_order=Case( When( Q(foo__type=FooType.ONE.value) | Q(foo__isnull=True) then=Value(1), ), default=Value(0), ), ).order_by( '-complex_order', 'order', 'id' ).annotate( number=Window(expression=RowNumber()) ) But I have a problem with wrong number annotation. After inspecting the SQL query I noticed that annotation happens at the same time with ordering. SELECT "table.id", ... CASE WHEN ("foo"."type" = ONE OR ("foo" IS NULL)) THEN 1 ELSE 0 END AS "complex_order", ROW_NUMBER() OVER () AS "number" FROM ... ORDER BY 32 DESC, "table"."order" ASC, "table"."id" ASC I need to annotate queryset second time, right after sorting it. Or maybe there is a better way to add iterable number for each row in queryset? -
MySQL Query exclude item when blank
I have this issue in my Query which is I can't perform the actual output that I expected, so let say I have this all data in my table named Tev_incoming ID code slashed_out status 1 23-09-00001 1 2 23-09-00002 1 3 23-09-00003 2023-09-18 22:45:46.099847 3 4 23-09-00004 2023-09-18 22:42:14.785251 3 5 23-09-00005 2 8 23-09-00004 3 9 23-09-00003 2 I have this query now SELECT * FROM tev_incoming t1 WHERE (code, id) IN ( SELECT DISTINCT code, MAX(id) FROM tev_incoming GROUP BY code )AND `status` IN (1,3) I have this result to my query provided ID code slashed_out status 1 23-09-00001 1 2 23-09-00002 1 4 23-09-00004 3 Expected output ID code slashed_out status 1 23-09-00001 1 2 23-09-00002 1 As you can see in all data there is duplicate code, it has two duplicate of 23-09-00004 I want to exclude 23-09-00004 because the slashed_out is blank which is status is equals to 3. I tried MAX(id) just to choose the max Id of the duplicate codes. Now How can I modify my query which has conditions I've mention above. -
django.core.exceptions.ImproperlyConfigured: WSGI application 'app.wsgi.application' could not be loaded; Error importing module
INSTALLED_APPS = [ 'base.apps.BaseConfig', 'corsheaders', 'rest_framework', 'rest_framework_simplejwt', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware' 'django.middleware.common.CommonMiddleware', ] WSGI_APPLICATION = 'wsgi.application' I installed everything, even whitenoise and imported all, I still cant get rid of this error -
Connection problem to related_name in save_model function in Django
There is a model called Borrow. Inside BorrowLine model, a ForeignKey is defined with related_name lines. I write BorrowAdmin and BorrowLineInline for Borrow model. Inside BorrowAdmin class I used the save_model function as follows: def save_model(self, request, obj, form, change): obj.save() print(obj.lines) return super(BorrowAdmin, self).save_model(request, obj, form, change) But when I add an instance of Borrow model in Django administration, the following line is printed in the console: borrow.BorrowLine.None and I don't have access to any of the BorrowLine fields. For example, one of its fields is book, but when I call it, it gives this error: 'RelatedManager' object has no attribute 'book' How can I fix this problem and access the class fields? my codes: class Borrow(models.Model): student = models.ForeignKey('student.Student', on_delete=models.CASCADE, related_name='borrow') created_time = models.DateField(auto_now_add=True) delivery_time = models.DateField(default=date.today() + timedelta(days=7), validators=[delivery_time_validator]) delivered = models.BooleanField(default=False) def __str__(self): return str(self.student) class BorrowLine(models.Model): borrow = models.ForeignKey('Borrow', on_delete=models.CASCADE, related_name='lines') book = models.ForeignKey('book.Book', on_delete=models.CASCADE, related_name='lines') def __str__(self): return f'{self.borrow} -> {self.book}' def clean(self): book = self.book if not book.is_available: raise ValidationError(f'The book {book.title} is not available.') class BorrowLineInline(admin.TabularInline): model = BorrowLine extra = 1 max_num = 3 autocomplete_fields = ('book',) @admin.register(Borrow) class BorrowAdmin(admin.ModelAdmin): inlines = (BorrowLineInline,) list_display = ('student', 'created_time', 'delivery_time', 'delivered') search_fields = … -
i am creating a ecommerce website and i want to display size variant of perticular product
my models.py class SizeVariant(models.Model): size_name=models.CharField(max_length=50) price=models.IntegerField(default=0) def __str__(self): return self.size_name class Product(models.Model): product_name=models.CharField(max_length=50) slug=models.SlugField(unique=True, null=True,blank=True) category=models.ForeignKey(Category, on_delete=models.CASCADE, default=1) price=models.IntegerField() desc=models.TextField() image=models.ImageField(upload_to='products') color_variant=models.ManyToManyField(ColorVariant, blank=True) size_variant=models.ManyToManyField(SizeVariant, blank=True) def save(self,*args,**kwargs): self.slug=slugify(self.product_name) super(Product,self).save(*args,kwargs) my html template <div class="product__details__option__size"> <span>Size:</span> {% for size in product.size_variant.all %} <label for="{{size.size_name}}">{{size.size_name}} <input type="radio" > </label> {% endfor %} </div> i have tried using for loop to show all the size variant of particular product but its not working i think there is problem in for loop. because its not taking size variant from database -
TimeoutError while trying to connect SMTP server
I'm trying to make a website that has a message form so that when somebody submits the form it will be present in the django admin panel, but I will get it in e-mail form as well. Here is the port configuration from settings.py: EMAIL_HOST = 'smtp.live.com' EMAIL_HOST_USER = 'mymail@hotmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TSL = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' My model has the fields name, phone, email and message. The function from views.py: def contact(request): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): form.save() name = request.POST.get('name') phone = request.POST.get('phone') email = request.POST.get('email') message = request.POST.get('message') subject = "WeCreate - Contact Form" content = f"Name: {name}\nPhone: {phone}\nEmail: {email}\nMessage: {message}" from_mail = 'wecreate.designs.srl@hotmail.com' recipient_list = ['wecreate.designs.srl@gmail.com'] send_mail(subject, content, from_mail, recipient_list, fail_silently=False) return redirect('/contact') else: form = MessageForm() return render(request, '../templates/lpadj/form.html', {'form': form}) And the error log: TimeoutError at /contact/ [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond If I ping the hostname all the packages return. I have triend different ports, changing the EMAIL_USE_TSL/SSL, changing the host to 'smtp.office365.com' and the firwall lets through the … -
I want to generate a token after I verified the user phone number in Django how can I do that
I write an application which send otp from api server and it actually works but after the user verify the phone number I want to generate a token for the user and after that every time the user want to send the request he should post the token to the headers. first I try tokenauth in rest framework but it needs user to be authenticated and it wants username and password which I can't post this to django server. how can I do that with posting phone number and otp this is all of my code """ Django settings for backend project. Generated by 'django-admin startproject' using Django 3.2.14. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ "2858-151-240-216-221.ngrok-free.app", "localhost" ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'home', 'requests', 'users', 'api', 'otp_api' ] MIDDLEWARE = … -
Django: query to iterate through a column values and search match in another table
I have this 2 tables in my DB : I would like a query to iterate through "company_members-id" and if there is a match in the "table_contacts" id column, return the line as a result I need to use the result in my HTML template to populate a selectbox with something like this : HTML template : <select id="members_in_companies"> {% for option in rendered_result %} <option value="{{ option.id}} "> {{ option.first_name}} + " " + {{ option.last_name}} </option> {% endfor %} </select> For example : iterate through the "Nike" company would populate the selectbox with 2 and 4 as selectbox value and " Ellon Musk" and "Willy Wonka". -
Already registered models django
I want to automate registering models in admin.py here is the code: from django.contrib import admin from django.apps import apps models = apps.get_models() for model in models: try: admin.site.register(model) except admin.sites.AlreadyRegistered: pass Even though i added exception it raises this error raise AlreadyRegistered(msg) django.contrib.admin.sites.AlreadyRegistered: The model Group is already registered in app 'auth'. -
Django filtered and pagination issue
I have a form that filter a queryset, filtering are ok, but if I use pagination links, I loose the filtering value. How can I paginate my filter result ? template table.html {% if is_paginated %} <div class="row"> <div class="col-lg-12"> {% if page_obj.has_other_pages %} <nav> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="{{request.path}}?page=1"> First </a> </li> <li class="page-item"> <a class="page-link" href="{{request.path}}?page={{ page_obj.previous_page_number }}"> Previous </a> </li> {% endif %} {% for page_number in page_obj.paginator.page_range %} {% if page_number <= page_obj.number|add:3 and page_number >= page_obj.number|add:-3 %} {% if page_obj.number == page_number %} <li class="page-item active"> <a class="page-link" href="{{request.path}}?page={{ page_number }}"> {{ page_number }} </a> </li> {% else %} <li class="page-item"> <a class="page-link" href="{{request.path}}?page={{ page_number }}"> {{ page_number }} </a> </li> {% endif %} {% endif %} {% endfor %} views.py: class CmsView(ListView): queryset = Cmsexport.objects.all().values() model = Cmsexport template_name = 'table.html' context_object_name = 'table' paginate_by = 10 def get_queryset(self): queryset = super(CmsView, self).get_queryset() field = self.request.GET.get('field') lookup = self.request.GET.get('lookup') value = self.request.GET.get('value') reset = self.request.GET.get('btn-reset') if (field and lookup and value) is not None: field = self.request.GET.getlist('field') lookup = self.request.GET.getlist('lookup') value = self.request.GET.getlist('value') query = dict() for (f,l,v) in zip(field,lookup,value): q = f.lower().replace(" ", "_") + '__' … -
Implement Recurring Classes/Events
I have to implement upcoming classes functionality. Upcoming classes can be repeated weekly or monthly. User will only create it once and repeat logic should be handled from back end. There should be no data duplication. Listing api should return the first 10 upcoming classes where date >= today date. Add live or upcoming Class Upcoming Class listing The last tried solution is: calculate the next 100 dates based on weekly or monthly interval and store it in a list named repeated_dates. write a scheduler which will get the last repeated date and if it less than today date then calculate the next 100 dates and update the list. filter out upcoming classes based on repeated_dates list. The issue is: If I filter out from list, I only get the class object. I don't know which date is matched. If there is only two classes, then it should return 1st 10 classes from these two based on dates >= today date. But in this solution, it will only return 2. Here is the model: REPEAT_CHOICES = ( ('no_repeat', 'Does not repeat'), ('repeat_weekly', 'Repeat Weekly'), ('repeat_monthly', 'Repeat Monthly'), ) def image_path(instance, filename): if filename: extension = filename.split('.')[-1] else: extension = "png" … -
Invalid password format or unknown hashing algorithm. Raw passwords are not stored. Django
I have a signup code views.py: def signup(req): if req.method == 'POST': form = SignupForm(req.POST) if form.is_valid(): form.save() return redirect('/') form = SignupForm() return render(req,'signup.html',{'form':form}) forms.py class SignupForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password','first_name','last_name'] now whenever I try to login with this code the submission is successful but when I go to the admin panel and click on the user, on the password section it says Password: Invalid password format or unknown hashing algorithm. Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using http://localhost/admin/auth/user/3/password/. -
How do I make a serializer for many to many relationships in django if one model is a proxy model?
I have a project with multiple types of users: admins, drivers and commuters. I made proxy models for the drivers class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=200) email = models.EmailField(unique=True, null=True) phone_number = models.CharField(max_length=15, unique=True) password = models.CharField(max_length=50) class Role(models.TextChoices): ADMIN = "ADMIN", 'Admin' COMMUTER = "COMMUTER", "Commuter" DRIVER = "DRIVER", 'Driver' base_role= Role.ADMIN role = models.CharField(max_length=50, choices=Role.choices) def save(self, *args, **kwargs): if not self.pk: self.role = self.base_role return super().save(*args, **kwargs) def __str__(self): return self.name I want to create a Vehicle model with a many to many relationship with only the drivers and also make serializers to allow me to link instances of drivers to vehicles and also list out all drivers and the vehicles they use. How do I go about this? -
error_css_class doesnt apply to django form
I have a form with one variable 'var1': class MyForm(forms.Form): error_css_class='error' var1=forms.IntegerField(label='var1',widget=forms.NumberInput(attrs={'id':'id_var1', 'name':'var1')) def clean_var1(self): var1=self.cleaned_data.get("var1") if var1 == 2: raise forms.ValidationError('cant be 2!') return var1 and styled the error message: <style> .errorlist { list-style-type: none; padding: 0; margin: 0; } .errorlist li { /* Style each error message */ color: red; } .error { /* the label of the field */ color:red; } .error input{ /* the text field */ border: 2px solid red; } </style> When i render the form using {{form.as_p}} everything works correctly, but when i render it manualy like this <form method="post"> {% csrf_token %} <div> <P>{{ form.var1.label_tag }} {{ form.var1 }} {{ form.var1.errors }}</P> </div> <button type="submit", name="calculate">Submit</button> </form> the class "error" isnt applied to the fields. I want to add stuff bewteen the field so using {{form.as_p}} isnt an option. thanks for the help -
Django annotate by first object from m2o or m2m field
I have 3 models: class Ban: name: models.CharField() person: models.ForeignKey(to="apps.Person") class Employee: name: models.Charfield() person: models.ForeignKey(to="apps.Person") class Person: name: models.Charfield() # here a have access to Ban and Employee as self.ban_set, self.employee_set I can get all Employee objects from Ban object as: ban_object.person.employee_set I need annotate Ban queryset by Employee first object from Ban "person.employee_set" field. I try do this by: employees = Employee.objects.filter(person_id=OuterRef("person_id")) qs = Ban.objects.annotate( employee=Subquery(employees[:1]) ) But I get error: "Cannot resolve expression type, unknown output_field" If I set output_field as models.ForeignKey() for Subquery or annotate, nothing working too -
Django concurrency bug handling
I have an API written in Django that provides user with the list of files that they have. There is also a delete API that can delete a File that the user has. However, there is a bug where a GET request after a deletion still shows the previously deleted object. The GET API uses a filter query on the Files object. While the DELETE API will delete a given file id from the list, by getting and calling .delete(). After googling around, it seems like I need to wrap the database queries into a transaction.atomic block and perform select_for_update() in both of the APIs. Will this solve the issue? By right, if the GET Request is done after receiving the DELETE response it should not ever have this concurrency bug right ? It is only if we sent the requests concurrently. But, select_for_update is locking the database row right? So, will the GET API be able to still read the currently being deleted row? Is this the correct way of handling, or do I need to somehow change the isolation level of the database. Currently the DB is Postgresql which defaults to "Repeatable Read". After reading around, this is … -
Django PostgreSQL - Indexes on JsonField vs. custom fields
I am working on a booking system on Django with the following context: Users can create Items for others to book They can further specify the 'available time' per weekday (mon-sun), i.e. opening_time & closing_time. We can also expect that: A. most users adopt the same 'default' values across 7 weekdays (i.e. override when necessary), and B. most users adopt the same default values, say 8am-10pm. A search on Items by its availability, e.g. "Monday 3-4pm", will be expected and of considerably high traffic, so query performance is a must. I have a few options in mind but cannot decide which is better: Option A: Default values + JsonField + index from django.db import models from django.contrib.postgres.fields import JSONField class Item(models.Model): opening_time = models.TimeField() closing_time = models.TimeField() override = JsonField() class Meta: indexes = [ models.Index(models.F("override__sun_open"), name="override__sun_open"), models.Index(models.F("override__sun_close"), name="override__sun_close"), ... ] The Json will 'override' if necessary - might look something like {'sun_open': 07:00, 'sun_close': 23:00}. The filter() will be more complicated but can save on storage (given most users will use the defaults). Option B: JsonField + index class Item(models.Model): available = JsonField() class Meta: indexes = [ models.Index(models.F("available__sun_open"), name="available__sun_open"), models.Index(models.F("available__sun_close"), name="available__sun_close"), ... ] The query will be easy … -
Django not able display the pdf file from Amazon S3, but able to upload to the amazon S3
i am trying to display my pdf list that had upload to the amazon S3, and i had make sure the connection between django and amazon S3 is correct, cause i am able to upload pdf file to S3 by using admin interface. Currently i am trying to display the list of file that had upload to S3 in a table. I had try to display the pdf file list from S3 and nothing show, but the print statement is able to show when i select the Link of "View PDF List", but no data is displaying at the table that should be display. Now the table is just empty and notthing will be display on the table. i had try looking out, did not find something i think it will help me. demo of the table. (https://i.stack.imgur.com/UVAbi.png) following is my code. views.py views.py def upload_pdf(request): if request.method == 'POST': form = PDFDocumentForm(request.POST, request.FILES) if form.is_valid(): pdf_doc = form.save(commit=False) # Upload the PDF file to S3 s3 = boto3.client('s3') pdf_file = request.FILES['pdf_file'] s3.upload_fileobj(pdf_file, settings.AWS_STORAGE_BUCKET_NAME, f'pdfs/{pdf_file.name}') # Set the S3 URL for the PDF file pdf_doc.pdf_file.name = f'pdfs/{pdf_file.name}' pdf_doc.save() return redirect('pdf_list') else: form = PDFDocumentForm() return render(request, 'customPage/uploadPage.html', {'form': form}) def … -
Django On Delete IntegrityError
I get an integrity Error on deleting a Company. See this code below class Company(models.Model): name = models.CharField(max_length=500, null=True, db_index=True) code = models.CharField(max_length=50, null=True, db_index=True) fmp_code = models.CharField(max_length=50, null=True) stock_exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE) exchange = models.CharField(max_length=50, null=True) class CalculationYearlyGrowth(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) date = models.DateField() current = models.BooleanField(default=False, db_index=True) historical_data = models.ForeignKey(CalculatedHistoricalFundamental, on_delete=models.CASCADE) This is the error I got django.db.utils.IntegrityError: update or delete on table "company_company" violates foreign key constraint "company_calculationy_company_id_c31e6552_fk_company_c" on table "company_calculationyearlygrowth" DETAIL: Key (id)=(308248) is still referenced from table "company_calculationyearlygrowth". So every time I want to delete a company and wherever it has foreign relations, I first have to delete CalculationYearlyGrowth of that company manually and I can't delete the Company. I have seen some other questions related to this but None have worked for me and the error itself is confusing since I have a Cascade delete so I don't expect the error to come. Thanks -
Django many-to-many fields and ModelForms
I am now working on a system that is calculating the CO2 emissions of a building. The thresholds are calculated taking into consideration the building type and the area of it. One building can have more building types and each building type has its area which in the end compose the gross area of the building (total area). What I am trying to do is when the user adds a building for calculation they will add the building information and for each building type the area of the it, the total area of the building is not important for now, but I am thinking on calculating it from the sum of the areas of the building types. Here is the models.py file: class BuildingType(models.Model): type = models.CharField(max_length=255, blank=True, null=True) co2_factor = models.DecimalField(max_digits=15, decimal_places=7, blank=True, null=True) class Building(models.Model): bbl = models.CharField(max_length=10, blank=True, null=True, unique=True) area = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) electricity = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) natural_gas = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) building_type = models.ManyToManyField(BuildingType, through='BuildingTypeSize', blank=True, null=True) class BuildingTypeSize(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) building_type = models.ForeignKey(BuildingType, on_delete=models.CASCADE) area = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) I am fairly new to Python and Django, i tried following some tutorials and also the documentation. … -
Django: How to convert "1 day, 1:00:09" in "HH:MM:SS" format
I have time in seconds. To convert it into the "HH:MM: SS" format used hour = forDuration.strftime('%H:%M:%S', forDuration.gmtime(seconds)) but I got this value: 1 day, 1:00:09. Are there any other options to get an hour in this format "HH:MM: SS" -
Expense Sharing api using DRF
I am creating an API which user can add expense in group. Imagine that we have 3 user in a group. User 1 add two expense with amount 90 and 210, and user 3 add an expense with amount 30. So basically when i see the group as User 1 i only should see Who do I owe and who owes me. it means i should see ( User2 owes you 100 and User3 owes you 90 ). first problem is i dont know how to calculate the 90 because user 3 had expense with amount 30 it means user3 owes user 1 100 but with the expense he paid, it will reduce his part from his balance. my main problem is in calculate settlements between 2 users amoung group. class GroupRetrieveView(generics.RetrieveAPIView): queryset = Group.objects.all() serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated] def calculate_balance(self, pk): try: group = Group.objects.get(pk = pk) except group.DoesNotExists: return Response({'Error':'Group not found !'}, status=status.HTTP_404_NOT_FOUND) expenses = Expense.objects.filter(group = group) summary = defaultdict(Decimal) for expense in expenses: payer = expense.paid_by.username participants = expense.group.members.all() amount = Decimal(expense.amount) len_participants = participants.count() if len_participants > 0: # payment = amount - share share = amount / len_participants for participant in … -
ArrayField is empty even after serializer.save() (Django and Postgres)
I'm trying to save an existing Python list to an ArrayField in Postgres, but when saved it ends up empty. When I print data['questions'] and data['sources'], they both print a populated list (ex. [question1, question2, question3]), but when I print serializer.data, it shows as: 'sources': [] and 'questions': [] data['conversation']['bot'] works correctly. Hence, the problem might be in the model setup, but I'm unable to figure out what's wrong. I have run py manage.py runserver to migrate changes already but the lists are still empty. Here's the excerpt from views.py: def histories(request): if(request.method == 'POST'): data = JSONParser().parse(request) serializer = HistorySerializer(data=data) if(serializer.is_valid()): result = some_python_dictionary data['conversation']['bot'] = result['answer'] data['sources'] = result['sources'] data['questions'] = result['questions'] serializer.save() return JsonResponse(serializer.data, status=201) models.py from django.db import models import json from django.contrib.postgres.fields import ArrayField # Create your models here. class History(models.Model): conversation = models.JSONField() sources = ArrayField(models.CharField(max_length=256), default=list) questions = ArrayField(models.CharField(max_length=256),size=3, default=list) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return json.dumps(self.conversation) class Meta: verbose_name_plural = "Histories" serializers.py from rest_framework import routers, serializers, viewsets from .models import History class HistorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = History fields = ['conversation', 'sources', 'questions', 'created_at'] -
Google Places API returns diferent street number which was given in auto complete
Something wierd starts to happens with Google Places API. I am working on a Python Django app but Google Places API is returning diferent street number in it queries. I search a street name and number "Rua Augusta, 300": But after selecting it the response cames with other number options instead of the choosen one. Does anyone knows what could be happening? It does happens with other addresses even where I live in. :-) Thank you very much!