Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Operands could not be broadcast together with shapes (128,) (0,) error
I am trying to implement a facial recognition login system but I have an error "Operands could not be broadcast together with shapes (128,) (0,)" and I have no idea what or how can I solve it. Here are my view.py and facedetector.py that have been implemented and the error that I get from my server: errors Traceback (most recent call last): File "C:\django-projects\lib\site packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\django-projects\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\django-projects\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\django-projects\aps\aps_site\authenticate\views.py", line 54, in login_user if facedect(user.userprofile.head_shot.url): File "C:\django-projects\aps\aps_site\authenticate\views.py", line 37, in facedect check=face_recognition.compare_faces(face_1_face_encoding, face_encodings) File "C:\django-projects\lib\site-packages\face_recognition\api.py", line 222, in compare_faces return list(face_distance(known_face_encodings, face_encoding_to_check) <= tolerance) File "C:\django-projects\lib\site-packages\face_recognition\api.py", line 72, in face_distance return np.linalg.norm(face_encodings - face_to_compare, axis=1) ValueError: operands could not be broadcast together with shapes (128,) (0,) views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout, update_session_auth_hash from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm from django.contrib import messages from .forms import SignUpForm, EditProfileForm from django.urls import path, include import os import face_recognition import cv2 # Create your views here. def home(request): return render(request, 'authenticate/home.html', {}) def facedect(loc): cam = cv2.VideoCapture(0) s, img = … -
Error with FuzzyWuzzy: StringProcessor.replace_non_letters_non_numbers_with_whitespace(s)
I cannot get the following function to run: match, match_score = process.extractOne(score, pct_dict.keys()) I get a whitespace error I cannot seem to resolve. Any idea what is causing this? Error: output = self.func(*resolved_args, **resolved_kwargs) wnas1 | File "/code/cleveland/templatetags/percentiles_ratings.py", line 32, in get_percentile_standard wnas1 | match, match_score = process.extractOne(score, pct_dict.keys()) wnas1 | File "/usr/local/lib/python3.7/site-packages/fuzzywuzzy/process.py", line 220, in extractOne wnas1 | return max(best_list, key=lambda i: i[1]) wnas1 | File "/usr/local/lib/python3.7/site-packages/fuzzywuzzy/process.py", line 78, in extractWithoutOrder wnas1 | processed_query = processor(query) wnas1 | File "/usr/local/lib/python3.7/site-packages/fuzzywuzzy/utils.py", line 95, in full_process wnas1 | string_out = StringProcessor.replace_non_letters_non_numbers_with_whitespace(s) wnas1 | File "/usr/local/lib/python3.7/site-packages/fuzzywuzzy/string_processing.py", line 26, in replace_non_letters_non_numbers_with_whitespace wnas1 | return cls.regex.sub(" ", a_string) from future import unicode_literals from django import template from fuzzywuzzy import fuzz from fuzzywuzzy import process register = template.Library() @register.simple_tag def get_perc(score): MATCH_THRESHOLD = 80 pct_dict = {14: 0.016, 14.7: 0.021, 15.3: 0.026, 16: 0.034, 16.7: 0.04, 17.3: 0.05, 18: 0.07, 18.7: 0.09, 19.3: 0.11, 20: 0.13, 20.7: 0.17, 21.3: 0.21, 22: 0.26, 22.7: 0.31, 23.3: 0.38, 24: 0.47} if not score: return '--' elif score < 26.7: return '<1' match, match_score = process.extractOne(score, pct_dict.keys()) if match_score >= MATCH_THRESHOLD: return pct_dict[match] else: return '--' If the score is 15 it should return 0.026 -
Django_jinja got an unexpected argument "default_extension'
I am trying to run server of opensource django apps that found on github, when i run python3 manage.py makemigrations command. It show me this error and i am not getting how to fix this error, coz, it is in library, even i have updated the library too: File "/home/pyking/.local/lib/python3.6/site-packages/django_jinja/backend.py", line 188, in __init__ self.env = environment_cls(**options) TypeError: __init__() got an unexpected keyword argument 'default_extension' can anyone let me know what is wrong with this? -
Pycharm not making MEDIA folder
Settings and urls.py file ..... Pycharm not able to create MEDIA folder :/ what is happening .. please guide ? MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, '/media') from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('shop/', include('shop.urls')), path('blog/', include('blog.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
django render views from different apps on different bootstrap tabs
I'm building a web app based on Django. My main html view has 3 bootstrap tabs like so: {% block base %} <ul class="nav nav-tabs" style="margin-bottom: 20px;"> <li class="active"><a data-toggle="tab" href="#mktcap">MarketCap</a></li> <li><a data-toggle="tab" href="#portfo">Portfolio</a></li> <li><a data-toggle="tab" href="#rank">Ranking</a></li> <!--<li><a data-toggle="tab" href="#menu3"></a></li>--> </ul> <div class="tab-content"> <div id="mktcap" class="tab-pane fade in active"> {% block mktcap %}{% endblock %} </div> <div id="portfo" class="tab-pane fade"> {% block portfolio %}{% endblock %} </div> <div id="rank" class="tab-pane fade"> {% block ranking %}{% endblock %} </div> </div> </div> {% endblock base %} I'm trying to build my app as modular as possible which is why I would like for each tab to be its own Django app. The problem I'm having is switching to the second "porfolio" tab. I am unable to render the view associated with portfolio whenever I switch the tab which results on the the contents being empty. What would be the best approach to go about this? Is there any way to achieve this without using AJAX? -
django.db.utils.ProgrammingError: column "image" of relation "choices_keyword" already exists
I have an issue between two migrations below. As you see the below code, they have migrations.AddField(... name='image', ...) in common. Because of that, they throw the below error every time I run manage.py migrate. django.db.utils.ProgrammingError: column "image" of relation "choices_keyword" already exists. Just to solve that issue temporarily, I have to run manage.py migrate --fake then it's working, but I know using -fake everytime is not a proper way. How can I solve that issue? 0015_auto_20190404_0925.py class Migration(migrations.Migration): dependencies = [ ('choices', '0014_auto_20190111_1625'), ] operations = [ migrations.AddField( model_name='keyword', name='image', field=imagekit.models.fields.ProcessedImageField(blank=True, null=True, upload_to=modvisor.choices.models.image_path), ), migrations.AddField( model_name='keyword', name='status', field=models.CharField(choices=[('inactive', 'Inactive'), ('active', 'Active')], default='inactive'), ), ] 0015_keyword_image.py class Migration(migrations.Migration): dependencies = [ ('choices', '0014_auto_20190111_1625'), ] operations = [ migrations.AddField( model_name='keyword', name='image', field=imagekit.models.fields.ProcessedImageField(blank=True, null=True, upload_to=modvisor.choices.models.image_path), ), ] -
How to revert Django PostgreSQL database model's primary key to an AutoField whilst maintaining foreign key and many to many relationships
I currently have a Django powered in-production web app that contains multiple models, sitting on top of a Postgresql database (Google Cloud SQL) During initial set-up, one of the models was set up as follows: class ExampleModel(models.Model): id = models.CharField(max_length=60, unique=True, primary_key=True) new_id = models.CharField(max_length=60, unique=True, null=True, db_index=True) name = models.CharField(max_length=300, db_index=True) tags = models.ManyToManyField(Tag, blank=True) The id field contains a unique ID like: AB123456789. I have since realised this is a mistake and would like to revert the primary key field to a standard auto-incrementing autofield, and instead use the 'new_id' field to store the unique ID. Please can someone help to make this change and perform the necessary database migrations? There are a number of foreign key fields in other models that currently use the id field in the above model which will need changing. As you can see in the above, there is also a many to many field between this model and a tag model. I tried removing the id field from my models.py file and migrating - it initially gave an error linked to null fields and default values so I set a dummy default value in the Terminal window and removed this in the … -
How to append information to the end of URL with Django-forms?
Without storing anything to a database, I want for the user to be able to enter a name (NAME) into my form and hit a submit button. Upon hitting submit, the name entered will be appended at the end of my URL like so: http://127.0.0.1:8000/username=NAME All I have is this basic form: <form method="post"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value='Enter Name'></input> </form> I am also trying to make it so that if the user types directly into the URL, they would be able to find the same page as if they were typing into the form. Example: A user types 'Joe' at the end of an URL as http://127.0.0.1:8000/username=Joe and gets a page about Joe. I expect the same resulting page about Joe when I enter 'Joe' into my form. -
Django locale middleware breaking Mapbox-js-gl
I'm trying to add translation to my Django blog. Everything seems to be working fine except for the fact that just adding Django locale middleware is breaking some JavaScript code I have in some pages layering markers over Mapbox map. No middleware: Middleware added: I've tried digging into the issue and it seems like the part that's breaking the JavaScript is this one: def process_request(self, request): urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF) i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf) language = translation.get_language_from_request(request, check_path=i18n_patterns_used) language_from_path = translation.get_language_from_path(request.path_info) if not language_from_path and i18n_patterns_used and not prefixed_default_language: language = settings.LANGUAGE_CODE translation.activate(language) request.LANGUAGE_CODE = translation.get_language() Whole middleware code: link Mapbox code in the index.html: <script> mapboxgl.accessToken = 'XXX'; var map = new mapboxgl.Map({ container: 'map-index', style: 'mapbox://styles/mapbox/light-v9', center: [0, 20], zoom: 0.5 }); // planned var geojson_planned = { type: 'FeatureCollection', features: [ {% for i in planned_places %} { type: 'Feature', geometry: { type: 'Point', coordinates: [{{ i.coord_h }}, {{ i.coord_v }}] }, properties: { title: "<div class='place-title'>{{ i.name }}</div>", description: "<div class='place-post'>{% for post in i.posts.all %}<a href='{{ post.get_absolute_url }}'>{{ post.title }}</a><br/>{% endfor %}</div>" } }, {% endfor %} ] }; // add markers to map geojson_planned.features.forEach(function(marker) { // create a HTML element for each feature … -
Django - ForeignKey "Reverse" ("_set")
I need to cruise back in reverse through my Foreignkey. For some reason it doesn't work... models.by : class Investment(models.Model): feeder = models.ForeignKey(Fund, on_delete=models.CASCADE) investor = models.ForeignKey(Investor, on_delete=models.CASCADE) (...) class Fund(models.Model): slug = models.CharField(max_length=100, default = 'default') (...) class Investor(models.Model): account = models.CharField(max_length = 10, unique=True) first_name = models.CharField(max_length = 100) (...) views.py : Investment.objects.filter(investor__pk=pk) --> I need to get to the slug attribute of Fiund of each Investment of an investor.. I have already filtered on investor (that's ok). Next is cruising to the slug. I assume I need to work with fund.set_all() but it doesn't work.. Anyone to the rescue? Thanks !!! -
Search Bar in Django?
I have a bootstrap search bar and I want it to search for list of all Tag in database (Tag are a sort of facebook page or reddit tags) so when i click on search i get the url ?q="typeword" but i want the application to redirect to a new page with the list of all tags , how to do this ? I have tried using GET request and paginator but nothing seems to work , only I add a new url "search/" and then it works but only with this url. models.py .................................... class Tag(models.Model): path = models.CharField(max_length=37,default=0) name = models.CharField(max_length=35) description = models.CharField(max_length=200) image = models.ImageField(default='default.jpg',upload_to='tag_pics') def __str__(self): return self.path ............................................ views .py ............................................ def search(request): q = request.GET.get('q',None) items='' if q is None or q is "": items = Tag.objects.all() elif q is not None: items = Tag.objects.filter(name__contains=q) paginator = Paginator(items, 3) page = request.GET.get('page') items = paginator.get_page(page) title = "Search" return render(request, 'blog/search.html',{'items': items, 'title': title}) ................................................... search.html ................................................... {% extends 'blog/base.html' %} {% block content %} {% if items %} <p class="search-count">Found <strong> {{ items.paginator.count }}</strong> result{{ items.paginator.count|pluralize }}</p> {% for i in items %} {{ i.path }} {% endfor %} {% elif request.GET.q … -
Django: method of model from quering a different one
I've a model CartItem that has a ForeignKey to a Product model. Becuase from Product model I get the description, image, etc. However, I want to have a method called sub_total that returns and integer. I use this to calculate total to be paid for this CartItem. This sub_total method query a different model costo_de_los_productos using some of the propierties of CartItem. like: self.product.category.name, self.product.name, self.size, self.quantity. However, something is not right with me query, if I comment it and return 0 it works, but total is 0. def sub_total(self): product_price = costo_de_los_productos.objects.filter(category = self.product.category.name, product = self.product.name, size=self.size, quantity=self.quantity).values_list("price", flat=True) What could be wrong? class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) size = models.CharField(max_length=20, choices=TAMANIOS) quantity = models.CharField(max_length=20, choices=CANTIDADES) file = models.FileField(upload_to='files', blank=True, null=True) comment = models.CharField(max_length=100, blank=True, null=True, default='') uploaded_at = models.DateTimeField(auto_now_add=True) step_two_complete = models.BooleanField(default=False) # def __str__(self): # return str(self.id) + " - " + str(self.size) + " por " + str(self.quantity) def sub_total(self): product_price = costo_de_los_productos.objects.filter(category = self.product.category.name, product = self.product.name, size=self.size, quantity=self.quantity).values_list("price", flat=True) # print(type(product_price)) return product_price product model: class Product(models.Model): name = models.CharField(max_length=250, unique=False) slug = models.SlugField(max_length=250, unique=False) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to='product', blank=True, null=True) available … -
Replace Django Button data-url With DRF Equivalent
I have a DataTable that includes the following column definition to add a button to each row: "columnDefs": [ { "targets": 11, "data": null, "defaultContent": "<button class='btn btn-warning btn-sm js-update-activity' data-url='https://server/platform/activities/104/update/'></button>" } ], It works, except the number 104 is a hard coded id. The plain Django version looks like this: {% for activity in activities %} <tr> <td>{{ activity.id }}</td> <td> <button class="btn btn-warning btn-sm js-update-activity" data-url="{% url 'activity_update' activity.id %}"> </button> </td> </tr> {% endfor %} activity_update is a URL name for this URL: url(r'^platoform/activities/(?P<pk>\d+)/update/$', views.activity_update, name='activity_update') When the button is clicked, a modal appears based on where data-url is pointed. How would I mimic the plain Django version of the button so that data-url properly returns the hard coded URL for each row of the DataTable? -
How do I use "discover" to run tests in my "tests" directory?
Using DJango/Python 3.7. I read here -- How do I run all Python unit tests in a directory? that I could use a "discover" command to find tests in a specified directory. I want to have a "tests" folder, so I cretaed one and then ran (venv) localhost:myproject davea$ python -m unittest discover tests Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/__main__.py", line 18, in <module> main(module=None) File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py", line 100, in __init__ self.parseArgs(argv) File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py", line 124, in parseArgs self._do_discovery(argv[2:]) File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py", line 244, in _do_discovery self.createTests(from_discovery=True, Loader=Loader) File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py", line 154, in createTests self.test = loader.discover(self.start, self.pattern, self.top) File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 344, in discover raise ImportError('Start directory is not importable: %r' % start_dir) ImportError: Start directory is not importable: 'tests' This is odd to me because I have an (empty) init file ... (venv) localhost:myproject davea$ ls web/tests/ __init__.py model_tests.py What else do I need to do to get my test directory recognized? -
How do I pass usernames from the User model in django to autocomplete
I am implementing autocomplete on a html page on my django website. I am looking to use the autocomplete from materialize <div class="row"> <div class="col s12"> <div class="row"> <div class="input-field col s12"> <i class="material-icons prefix">textsms</i> <input type="text" id="autocomplete-input" class="autocomplete"> <label for="autocomplete-input">Autocomplete</label> </div> </div> </div> </div> Materialize shows how data can be passed to this autocomplete document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('.autocomplete'); var instances = M.Autocomplete.init(elems, options); }); // Or with jQuery $(document).ready(function(){ $('input.autocomplete').autocomplete({ data: { "Apple": null, "Microsoft": null, "Google": 'https://placehold.it/250x250' }, }); }); I understand the second part and can implement it. However I do not understand how the first part works, which I think is what I will need. My need is to pass the usernames from the User model in django to this autocomplete. How would I go about doing this -
Django form field required on condition
I have a Django model form where i want to make a form field required if some value is selected in another form field. e.g if activity_name = 'Project Planned Activities' is selected in activity_name form field the project_id field should be required = true I have added a form validator for this but its not working class ActivityTrackerModelForm(forms.ModelForm): date = forms.DateField(label='', widget=forms.DateInput( attrs={"placeholder": "Select Date", 'id': 'datepicker', 'class': 'form-control', 'autocomplete': 'off'})) activity_name = forms.ModelChoiceField( queryset=activity.objects.all().order_by('activity_name'), label='', empty_label="Select Activity", widget=forms.Select(attrs={'class': 'form-control'})) system_name = forms.ModelChoiceField( queryset=system.objects.all().order_by('system_name'), label='', empty_label="Select System", widget=forms.Select(attrs={'class': 'form-control'})) client_name = forms.ModelChoiceField( queryset=client.objects.all().order_by('client_name'), label='', empty_label="Select Client", widget=forms.Select(attrs={'class': 'form-control'})) hour_choice = [('', 'Choose Hours'), (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8)] hours = forms.ChoiceField(label='', choices=hour_choice, widget=forms.Select(attrs={'class': 'form-control'})) min_choice = [('', 'Choose Mins'), (0, 0), (15, 15), (30, 30), (45, 45)] mins = forms.ChoiceField(label='', choices=min_choice, widget=forms.Select(attrs={'class': 'form-control'})) no_of_records = forms.IntegerField(label='', required=False, widget=forms.NumberInput( attrs={"placeholder": "Enter no. of Records", 'class': 'form-control','autocomplete': 'off'})) project_id = forms.CharField(label='', required=False, widget=forms.TextInput( attrs={"placeholder": "Project ID", 'class': 'form-control'})) user_comments = forms.CharField( label='', required=False, widget=forms.TextInput( attrs={ "placeholder": "Enter Your Comments Here...", 'size': 72, 'class': 'form-control', 'autocomplete': 'off' } ) ) class Meta: model = activity_tracker fields = ['date', 'activity_name', … -
I am creating a graph base on gps database
So basically I am generating a graph using gps in database from the user login, the problem is it generate the graph, when no one loggin, but when someone login and user has no gps in database it should redirect to error page. I do not know where I should put if else statement to do that. !/usr/bin/env python coding: utf-8 from plotly.offline import plot, init_notebook_mode import json import random import plotly import plotly.plotly as py import plotly.graph_objs as go import glob import datetime import operator import random from util import db_API import ast def draw_graph(metadata, uid): #metadata = db_API.load_metadata(uid) #print(metadata[0][1]) #print(type(metadata[0])) #temp = metadata[0] #print(temp[1]) #print(type(temp[1])) #dct = ast.literal_eval(temp[1]) #print(type(dct)) for item in metadata: item[1] = ast.literal_eval(item[1]) metadata = [metadata[i][1] for i in range(len(metadata))] metadata = sorted(metadata, key=operator.itemgetter("timestamp")) #print(metadata[0]) #print(metadata[0]['timestamp']) #print(type(metadata[0]['timestamp'])) # '2015-07-17 21:14:09.190355' #print(datetime.datetime.strptime(metadata[0]['timestamp'], '%Y-%m-%d %H:%M:%S.%f')) for i in range(len(metadata)): metadata[i]['timestamp'] = datetime.datetime.strptime(metadata[i]['timestamp'], '%Y-%m-%d %H:%M:%S.%f') # Format dates for m in metadata: m['timestamp'] = m["timestamp"].date().strftime('%m/%d/%Y') #m['timestamp'] = m["timestamp"].date().strftime('%y/%m/%d') # GPS array for convenience gps = [m["gps"] for m in metadata] # Dates array for plotly slider dates = [m["timestamp"] for m in metadata] seen = set() dates = [d for d in dates if d not in seen … -
How come Django allows user to enter <script>alert("hello")</script> in form CharField without throwing an error?
I am new to Django and in my Django application, I have a model that contains the basic information about a vehicle (name, model, make, year). I add the information through a form. The issue is that if the user were to enter "alert("error")" then the form will allow it and it will be saved as valid input. So when the page refreshes, there will be an alert on the page and the field will now be blank. How to I prevent the user from entering JavaScript in the CharField? I do not have 'autoescape off' anywhere in the code base nor do I use the 'safe' keyword in the html. I do not have the 'def clean' checking for such input as I was under the impression that Django would take care of such injection. Thanks in advance! -
django.db.utils.IntegrityError: UNIQUE constraint failed: beachprofile_beach.beach_id
I am setting up a review feature for the beach profile, and want to submit the review form in beach.html and redirect back to the original beach profile. I am involving a addreview button and review list in beach profile but the thing is that when I open the beach profile I chose it told me that unique constraint failed for beachprofile_beach.beach_id. So I thought it's because after user reviewed it go back to the beachProfile view again and stored the same beach info into the table again. But I don't really know how to fix it. This is a part in beachProfile view that I can store the beach info into my table Beach when I open the new beach profile page. beach = Beach(Beach.objects.get(), beachname=name, safety=testsafe, lat=latitude, lng=longitude) if beach.beach_id == None and beach.beachname == None: beach.save() else: pass For my review model and review model (partial): class Beach(models.Model): beach_id = models.AutoField(primary_key = True,default=1) beachname = models.CharField(max_length=50, unique = True) safety = models.IntegerField(default=0) #default is safe? lat = models.IntegerField() lng = models.IntegerField() fav = models.ManyToManyField(User, related_name="fav",blank=True) ...... class Review(models.Model): review_id = models.AutoField(primary_key = True, default=1) beach = models.ForeignKey(Beach, on_delete = models.CASCADE) pub_date = models.DateTimeField('date published') user_reviewed = models.ManyToManyField(User, … -
"This field is required" when GenericRelation field is marked as not required in serializer
I have a model set up with a GenericRelation named tags. The GenericRelation object defaults the blank kwargs attribute to True - so null is allowed at the Model Level: class Character(models.Model): name = models.CharField(max_length=200) date_of_birth = models.DateField() tags = GenericRelation(TaggableTag, content_type_field='taggable_type', object_id_field='taggable_id') Within the serializer, I have attached a serializer to this tags field to ensure it's eager loaded on each request for Character information. class CharacterSerializer(serializers.HyperlinkedModelSerializer): tags = TaggableTagSerializer(many=True) class Meta: model = Character fields = ('id', 'name', 'date_of_birth', 'tags') extra_kwargs = { 'tags': {'required': False, 'allow_null': True, 'default': None} } validators = [] As you can see, I've gone bit overkill on the validation rules, but all to just be doubly sure that it doesn't force the 'tags' field to be required. However, the POST route seems to still return the following validation message: HTTP 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "tags": [ "This field is required." ] } I'm unsure what to do here, I've followed the documentation on the Django Rest Framework page about Validators - I'm certain this might be because it's a GenericRelation field rather than a normal field, but I'm unsure how to solve it. … -
Using selected_related() in nested serializers
I've been using select_related() to speed up a large DRF call with great success, but I've hit a wall. My main serializer references two other serializers, and one of those references yet another serializer. I'm unsure as how to implement prefetching in the second level serializer. serializer.py class DocumentsThinSerializer(serializers.ModelSerializer): class Meta: model = Documents fields = ('confirmed', ) class PersonThinSerializer(serializers.ModelSerializer): documents = DocumentsThinSerializer() class Meta: model = Person fields = ('name', 'age', 'gender') class EventThinSerializer(serializers.ModelSerializer): day = DayThinSerializer() person = PersonThinSerializer() @staticmethod def setup_eager_loading(queryset): return queryset.select_related('day', 'person') class Meta: model = Event views.py class EventList(generics.ListAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Event.objects.all() serializer_class = EventThinSerializer def get_queryset(self): return self.get_serializer_class().setup_eager_loading(queryset) As you can see, I'm using the static method setup_eager_loading() to get things going, but I can't find a queryset hook for my PersonThinSerializer() to get the speedup when accessing the DocumentsThinSerializer() in the same way. -
How do I get dates to display using my settings TIME_ZONE
I'm using Django and Python 3.7. I have the following set in my settings file ... LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Chicago' USE_I18N = True USE_L10N = True USE_TZ = True I would like for all dates to display using the default time zone I have above. However, when I print out fields like self.created_on.ctime() in which "created_on" maps to a PostGres DATETIME field, the date is printed out using a UTC timezone. How can I get this to display using the time zone I have? -
Client patch gives 400 error in django testing
So basically when i try to test my patch view it doesn't patch at all as i get a 400 error. However, when i call the same patch view outside the APITestCase, while running the test server, it does work. what i've tried: patch_data = json.dumps({'first_name': 'test999'}) format='json' At APITestCase: def test_patch_update_data(self): self.client.force_authenticate(user=self.user) self.assertEqual(self.user.first_name, 'Robert') patch_data = {'first_name': 'test999'} response = self.client.patch('http://testserver/api/patch/{0}/'.format( self.user.id), patch_data, format='json') self.assertEqual(response.status_code, 200) # ERROR:GIVES 400! self.assertEqual(self.user.first_name, 'test999') At views.py class UsuariosUpdatePatchAPIView(UpdateAPIView): queryset = Usuarios.objects.all() serializer_class = UsuariosUpdateSerializer permission_classes = [IsAuthenticated, IsSelfUser] The error: self.assertEqual(response.status_code, 200) AssertionError: 400 != 200 Thanks in advance! :) -
Overriding Django setting doesn't reflect in test
I have a separate settings file for test environment. I'm using DRF for Authentication, but have set the default permission as rest_framework.permissions.AllowAny in the test_setting file. Now to test whether authentication is working or not, I need to override the key. But it doesn't seem to work. I'm using the decorator @override_settings. But it doesn't seem to work. If I change the setttings file directly, then the test is passing. @override_settings(REST_FRAMEWORK={ 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) }) class AuthenticationTest(TestCase): def test_api_should_not_be_hit_without_authorization(self): response = client.get(reverse('some_api', kwargs={'key': value})) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) I'm expecting the status code to 401, but it seems to pass through and is giving me 200. I pasted the below code in the test and it shows that the REST FRAMEWORK was actually overridden, but the test is still failing. from django.conf import settings dir(settings) print(settings.REST_FRAMEWORK) Thanks -
dynamic html Select Dropdown List using data from JSON link in django app
I want to create a dynamic html form Select Dropdown List using data from JSON url from DJANGO model.I want that Select Dropdown List to be update dynamic without the user need to refresh the page to get last changes from json url. for example if some other user add new entry in django table then that Dropdown List update automatically without need refresh page. but in my code the user need refresh the page to get last changes any idea who to avoid refresh page to get data ? here the code : views.py def test_json(request): response_data=serialize('json',andress.objects.all()) return HttpResponse(response_data,content_type='json') urls: url(r'^test_data/$', test_json, name='test_json'), json link : [ { model: "log.mymodel", pk: 3, fields: { f1: "some vasa", f2: "some vadada", f3: "some vsasa", } }, { model: "log.mymodel", pk: 4, fields: { f1: " some v1", f2: "some v2", f3: "some v3", } } ] html page : <select id="locality-dropdown" name="locality"> </select> <script> let dropdown = document.getElementById('locality-dropdown'); dropdown.length = 0; let defaultOption = document.createElement('option'); defaultOption.text = 'Choose State/Province'; dropdown.add(defaultOption); dropdown.selectedIndex = 0; const url = 'http://127.0.0.1:8000/test_data/'; const request = new XMLHttpRequest(); request.open('GET', url, true); request.onload = function() { if (request.status === 200) { const data = JSON.parse(request.responseText); let option; …