Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to validate dynamically inputted data using formset in django and making sure they are distinct?
I'm trying to create a form in Django that allows the user to input data for a model which is linked to another model via a ForeignKey. And I have written a custom validation method that will make sure that all the user's input are unique but it doesn't work and goes ahead to save the form which is not what I intended. I hope the code provides more explanation to what I'm trying to do. forms.py class ChoiceModelForm(forms.ModelForm): class Meta: model = Choice fields = ['choice_text'] widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control', }) } class ChoiceModelFormset(BaseModelFormSet): def clean(self): super().clean() choices = [] for form in self.forms: choice = form.cleaned_data['choice_text'].upper() if choice in choices: raise ValidationError("Choices in a poll must be distinct") choices.append(choice) ChoiceFormset = modelformset_factory( Choice, form=ChoiceModelForm, extra=2, formset=ChoiceModelFormset ) Here's code for the models.py file class Choice(models.Model): poll = models.ForeignKey(Poll, on_delete=models.SET_NULL, null=True) choice_text = models.CharField(max_length=200) def __str__(self): """String representing the Choice object""" return self.choice_text The custom validation in the ChoiceModelFormset doesn't work. Any help will be appreciated. -
Form as_p, error validation, django signup
I am using form.as_p in my sign.in template. I have noticed that there is information regarding length of password - it requires at least 8 letters. But when I am registrering a user and put a password with 1 letter it does not raise any error. It accepts this, but after all there is impossible to log in with this data. Do you know how can i solve this? I mean how can I raise this error and do not let sign up a user with for short password? {% extends 'base.html' %} {% block title %}Sign Up{% endblock %} {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} -
Including full name from google into my user model upon google signup (django-rest-auth)
I have been able to implement signup with google using Django-rest-auth. I also have a custom user model that requires just the email and full name. other fields are autogenerated but import and are generated from just the two fields required by the user. The problem is that when I sign up with Google, it is just the email that is automatically passed into the model instead of both the email and full name. How can I get the full name to also be created as the user signs up with google using Django-rest-auth? bellow are how the related apps are set up: models.py class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=250) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=255, unique=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] settings.py SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'email', 'profile', ], 'AUTH_PARAMS': { 'access_type': 'offline', }, 'APP': { 'client_id': 'secret.apps.googleusercontent.com', 'secret': 'specialsecret', 'key': '' } } } views.py class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter Please, what can I do to be able to pass the name data from google into the model upon creation -
Best way of handling large JSON data import in Django Rest Framework?
I've set up a fairly simple Django web app on Google Cloud to handle POSTed API calls that import JSON data into my database. I currently use the standard DRF models to handle serialization as well as validation. However, I've noticed some of the POSTs with larger JSONs timeout after 60 seconds on upload. I am guessing I can just increase the timeout settings on the Google Cloud instance, but was wondering from the perspective of Django what the best step would be. This is a learning project, as I'm new to Django, so I had several ideas on how to proceed. Was wondering if anyone had advice on this topic. Use the Django FileUpload parser. However, I'm not sure this would avoid the timeout issue, and I would have to write my own custom file validation script. Some sort of asynchronous processing where the file is uploaded, some ID is returned to the user which can used with a different endpoint to see when the upload has been processed and validated successfully. The downside of this is to my knowledge Django has no about-the-box solution for async support yet so it might be out-of-scope for a relative beginner. Switch … -
Count across 2 models via FK/M2M using Subquery in Django?
I am trying to iterate a list of a model and include counts of a model which is 2 models away (connected via FK then M2M). An example: A website designed around users posting media from local attractions. These attractions are then sorted by cities. Then, on my page where users can browse through the various cities, they can see both how many attractions are in each city (I've got this part figured out), and then also how much media has been posted at each attraction (this is where I'm stuck). Some sample code: class City(models.Model) name = .modelsCharField... class Attraction(models.Model) name = models.CharField... city = models.ForeignKey(City) class Media(models.Model) upload = models.Imagefield attraction = models.ManyToManyField(Attraction) Now I have a page listing all of the Cities, which I want to display: City#1 (12 attractions, 78 pieces of media) I can pull the number of attractions via attraction_set, but can't figure out how to get the total number of media. I've experimented with QuerySet but can't seem to get it to work. Here's the lines I tried: qs = City.objects.all() qs = qs.annotate(pieces_of_media=Subquery(Media.objects.filter(attraction=OuterRef('pk')).values('attraction').annotate(pieces_of_media=Count('pk')).values('pieces_of_media'))) This doesn't result in any errors or anything, but the numbers returned are not accurate, so I'm not sure … -
Django ORM : restrict foreignkey relationship between models to limited number of times
i have two models: vehicle and Driver. At any given point of time, a vehicle can have zero, one or maximum of two drivers. my current models setup allows by to have more than 2 drivers on one vehicle. How can i restrict the number of driver to just two per vehicle ? my current models class DriverStatus(models.Model): status = models.CharField(max_length=200) def __str__(self): return f'{self.status}' class Driver(models.Model): name = models.CharField(max_length=200) driver_num = models.IntegerField() profile_image = models.ImageField(default="default.jpg",upload_to="images") status = models.ForeignKey(DriverStatus, on_delete=models.CASCADE) current_vehicle = models.ForeignKey(Vehicle, on_delete=models.SET_NULL,null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.name}' class Vehicle(models.Model): vehicle_number = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.vehicle_number -
how to extract value in queryset and convert to string
the output of my code is currently book_name = book.objects.values('book_name').filter(book_id=book_id) book_name =str(book_name[0]) this code should give me 'Chronicles of Narnia '. but it instead returns {'book_name': 'Chronicles of Narnia '}. how do i extract the value i need. *note there will only be 1 value in this query every time -
Django Forms: How to create a simple dropdown list in a form using values from an existing model
I'm new to Django and struggling to find the best/correct way to populate a dropdown list in a ModelChoiceField within a form using a list I have stored in a database. The basic code below works fine with my view passing the form as context to my template but the drop-down returns a 'dictionary' like list with the ugliness or the brackets, colons and the key name (see the attachment) from django import forms from .models import constituency class ConstituencyForm(forms.Form): ConstituencySelection = forms.ModelChoiceField(queryset=constituency.objects.all().values('name')) I want just the area name in this dropdown list My questions are: 1/ The purpose of this page will be to select one of 650 areas from the dropdown list and have it highlighted on the map. Is this an appropriate way to approach the task (using a queryset within the form itself)? 2/ How do I clean up this list, it should simply read:- Aldershot Aldridge-Brownhills Altrincham and Sale West and so on and so on Your help would be forever appreciated! Thanks, Phil #anoobinneed -
How to pass PK into a method decorator
Hello guys i am trying to implement some form of access control on my views. My programme is structured as such: 1 project has some users which are tied to it in the form of a foreign key. I only wish to allow those whom are involved in it to view this project. The problem however is that the PK i use to query the database for my template is in my URL , users which do not have access to the project can simply change the url query and gain access to the items they do not have access to. I came across django's user_passes_test method decorator and thought that it is exactly what i needed to implement this user access control. Here is some code that i have came up with: My view: @method_decorator(user_passes_test(project_check(id), name='dispatch')) class ProjectDetailView(CreateView): ##this is actually not relavant## model = SalesNotation fields = ['sales_notes'] exclude = ['notation_id'] template_name = 'rnd/projects.html' context_object_name = 'form' ##this is actually not relavant## def get_context_data(self, **kwargs): id = self.kwargs['id'] context = super(ProjectDetailView, self).get_context_data(**kwargs) context['projects'] = SalesProject.objects.filter(sales_project_id = id) This is my URL: path('projects/<int:id>/', ProjectDetailView.as_view(), name = 'rnd-projects'), This is my project model: class SalesProject(models.Model): sales_project_id = models.AutoField(primary_key=True) sales_project_name = … -
How to filter keywords from multiple models using SearchFilter in Django rest framework?
I have tried to filter keywords from multiple models in the Django rest framework and have got these errors "AssertionError at /api/searching-posts/ 'SearchPostAPIView' should either include a serializer_class attribute or override the get_serializer_class() method." Please help me. views.py class SearchPostAPIView(generics.ListAPIView): search_fields = "__all__" filter_backends = (filters.SearchFilter,) def get_queryset(self): queryset = ( {'queryset': QueryPost.objects.all(), 'serializer_class': QueryPostSerializer}, {'queryset': ReviewPost.objects.all(), 'serializer_class': ReviewPostSerializer}, ) keyword = self.request.query_params.get('keywords', None) if keyword is not None: queryset = queryset.filter(finding_keywords=keyword) return queryset -
django social authentication logout from entire browser
I'm trying social login method in my django project. i'v used google social auth2 for user authentication. now i'm able to get sign in via google auth. when i click on logout then my site gets logout, here i want to complete disconnect from my gmail account. the problem is when i hit gmail.com in another tab my gmail account automatically gets sign in. according to my research when i click on sign out it sends me to /account/logout/ and this link is used for local user not for social user!. how to get sign out from all the tabs? any segment of code if you required please write i will append her. -
Posting dynamic html table data to Django with form
I am trying to post data from an HTML table that is dynamically created in javascript to my Djnago model. Is this possible? -
Django Model Importerror: cannot import name 'Driver' from 'driver.models'
I have two apps : vehicle and driver . Each vehicle can have 2 unique drivers at any given time. my issue : I not sure if this should be manytomany relationship or manytoone relationship. while trying manytomany relationship (as per the below models), i get an error during makemigrations stating cannot import name 'Driver' from 'driver.models' driver.models.py from django.db import models from datetime import datetime from vehicle.models import Vehicle class DriverStatus(models.Model): status = models.CharField(max_length=200) def __str__(self): return f'{self.status}' class Driver(models.Model): name = models.CharField(max_length=200) driver_num = models.IntegerField() profile_image = models.ImageField(default="default.jpg",upload_to="images") status = models.ForeignKey(DriverStatus, on_delete=models.CASCADE) current_vehicle = models.ManyToManyField(Vehicle) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.name}' vehicle.models.py from django.db import models from datetime import datetime from driver.models import Driver class VehicleStatus(models.Model): status = models.CharField(max_length=200) def __str__(self): return f'{self.status}' class Vehicle(models.Model): vehicle_number = models.CharField(max_length=200) driver_main = models.ManyToManyField(Driver) driver_sec = models.ManyToManyField(Driver) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.name}' -
POST data successfully pass to Django view when using AJAX but fail when using pure Javascript
javascript newbie here. I am trying to send POST data to a django view and subsequently to a JS function. The process was working when I was using AJAX, but does not anymore when I use pure Javascript instead. From the form (simplified) below, I am trying to pass to the view the id of the elements which have a checkbox checked: <form action="{% url 'home' %}" method="POST" id="js-post-form"> {% for element in list %} <input type="checkbox" name="element-checkboxes" value="{{element.id}}"> {{element.name}} {% endfor %} <button type="submit">Submit</button> </form> The relevant part of the view: if request.is_ajax(): data = dict() selected_elements = list() selected_elements = request.POST.getlist('element-checkboxes') // was returning a list of id, now returns an empty list if selected_elements: // do something data = {'selected_elements': selected_elements} return JsonResponse(data) The above was working when I was using Ajax and printing selected_elements from the view was returning a list of ids. Now that I am using pure javascript, it returns an empty list. Why could this be the case ? the js: var myform = document.getElementById('js-post-form'); myform.addEventListener('submit', function(e){ e.preventDefault(); var request = new XMLHttpRequest(); request.open(myform.method, myform.action, true); request.setRequestHeader('X-CSRFToken', cookies['csrftoken']); request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); request.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); request.onload = function () { if (this.status >= 200 && … -
Using value of select form to create a link
Using django 3.0, I am trying to implement the following scheme. On the site there is a select form, <select> <option value="A"> A </option> ... </select> I want to make a button that would take the value from the select element and redirect a user to the page /<selector value>. That is, the button should act as as a link formed dynamicaly based on the value of the select element. For example, A might be an yaer, and the page /A (defined in urls.py) contains the archieve of news for that year. Is there a simple way to do so? Since I do not need to pass any specific information, using POST/GET methods seems to be an overkill. Preferably, I would also like not to use JS. Thanks in advance. -
Hi, can you tell me what this error is? Learning python django
Exception Type: NoReverseMatch at /art/ Exception Value: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. -
Override Django 3.0 Admin Templates
I have followed the documentation: https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#overriding-admin-templates Also followed all the steps in this answer. https://stackoverflow.com/a/29997719/9289272 Still I'm unable to override the templates -
Django-Use two class based views in one template
I have my two class based views, One for just showing some stuffs and other is a image upload form. Now In my template, I want to both show stuffs and the ability to upload images through one template. #models.py class Page(Group): name = models.IntegerField() class Photo(models.Model): file = models.FileField() In views.py, I have two views like this: class UploadView(View): model = Photo def get(self, request,*args, **kwargs): photos_list = Photo.objects.all() return render(self.request, 'page/upload.html', {'photos': photos_list}) def post(self, request, *args, **kwargs): form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) class PageDetailView(DetailView): model = Page template_name = 'page/page_detail.html' You can see I have two separate templates for two views. Also, my photo upload form is like this: class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = ('file', ) Now in my pagedetailview's template, I show stuffs like this: {{ page.name }} <!-- and various things --> And in my upload.html, I have a button for uploading. When I click that button, it takes me to file explorer to choose photos that I want to upload. Kind of like this: #upload photo's template <div > <button type="button" … -
ImportError: No module named 'django_excel'
I am trying to use Django-forms with my Django web-app. My app uses the following version of Django. Django==2.2.6 django-bootstrap3==11.1.0 django-pandas==0.6.1 djangorestframework==3.11.0 the page appears fine on the first load but when I press submit and it gives the following error in the terminal. ImportError: No module named 'django_excel' Here is the complete log... Thanks in advance! Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/contrib/staticfiles/handlers.py", line 65, in __call__ return self.application(environ, start_response) File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 141, in __call__ response = self.get_response(request) File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/views/debug.py", line 94, in technical_500_response html = reporter.get_traceback_html() File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/views/debug.py", line 333, in get_traceback_html c = Context(self.get_traceback_data(), use_l10n=False) File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/views/debug.py", line 305, in get_traceback_data 'filtered_POST_items': list(self.filter.get_post_parameters(self.request).items()), File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/views/debug.py", line 177, in get_post_parameters return request.POST File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 110, in _get_post self._load_post_and_files() File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/http/request.py", line 315, in _load_post_and_files self._post, self._files = self.parse_file_upload(self.META, data) File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/http/request.py", line 271, in parse_file_upload self.upload_handlers, File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/http/request.py", line 259, in upload_handlers self._initialize_handlers() File "/Users/ritambharachauhan/thoreau-backend-main/venv/lib/python3.5/site-packages/django/http/request.py", line 253, … -
Best way to integrate a Django Backend with a Vue front end? [closed]
To integrate a Django Backend and a Vue frontend, it seems the two approaches are to create an API in Django and connect it to a Vue frontend, or instead to simply include Vue in tags in the relevant templates in Django. What are the deciding factors between which approach is better? -
Django Celery worker is not picking up tasks
im trying to run periodic task in my Django app using Celery and local Redis server. I'm using MS Windows and PyCharm. For a long time i fought with versions and so on, now everything seems to works, but tasks are not executing. At the beginign im starting celery beat (test44 is an app name): celery -A test44 beat -l info then: celery -A test44 worker -l info I'm trying to execute 'task_number_one' every 1 minute. Console for beat displays: beat: Starting... Scheduler: Sending due task task-number-one (app1.tasks.task_number_one) And is adding the same message every 1 minute so it is working. Console with celery worker shows: INFO/MainProcess] celery@DESKTOP-J3 ready. INFO/SpawnPoolWorker-11] child process 10776 calling self.run() INFO/SpawnPoolWorker-10] child process 9444 calling self.run() INFO/SpawnPoolWorker-9] child process 5512 calling self.run() INFO/MainProcess] Received task: app1.tasks.task_number_one[d8ca6cc6-59c0-4543-bd1d-dbe01bdbdb72] INFO/SpawnPoolWorker-13] child process 9992 calling self.run() INFO/SpawnPoolWorker-12] child process 7840 calling self.run() INFO/MainProcess] Received task: app1.tasks.task_number_one[3b266a1a-67c1-46ee-9f08-6be0c49b3ab7] INFO/SpawnPoolWorker-14] child process 2172 calling self.run() But nothing happends, as if the function was not executed. Sometimes it creates more those 'spawnPoolWorker', sometime less, like if there were already tasks in some queue. What am i doing wrong? -
Image is not loading from ImageField
My images are getting properly saved in media folder(/media/appIcons/). I am loading image using below html code <img class="card-img" src="{{ app.image.url}}"> But it is not loading on page and i am not seeing any error on console. I have all settings in place. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media/") urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When i inspected elements on browser path is coming properly <img class="card-img" src="/media/appIcons/test.png"> Any help is much appreciated. PS python 2.7, Django 1.11 -
How to fetch rows from django-tables2
I have to apply infinite scrolling in django-tables2. Currently, the table is rendered by {% render_table table %} inside a div. But, can I fetch the data in the form of rows, so that I can use a for loop on the rows and display as many rows I want? -
Trouble with MEDIA_ROOT
I've finished a beginner's tutorial on django-project and now I am trying to go further. So, I want to add an ability to add images to polls. To do that, I need to add 'django.template.context_processors.media' to context_prosessors and create MEDIA_ROOT. So i did BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(str(BASE_DIR)) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, MEDIA_URL) print(str(MEDIA_ROOT)) But when I run the django-server I see the following results of the print functions: What am I doing wrong? And why do I see the results of the print functions twice? -
Why is request.data empty?
I'm currently working on DRF When I visit post_list through local server, It gives me correct data. but When I do test, It gives me empty list. How can I fix it? tests.py from rest_framework.test import APITestCase from rest_framework.reverse import reverse as api_reverse from rest_framework import status from .models import Post class PostAPITestCase(APITestCase): def test_posts(self): url = api_reverse('item:list') response = self.client.get(url, format='json') print(response.data) # [] ???