Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Override user queryset to filter out admin/staff users from the public?
I want to filter the user manager self.get_queryset() method in such a way that users on the client application don't see admin and staff users when searching for or viewing other accounts. The issue I'm running into is I am unable to login with my auth system if I override get_queryset entirely. My current setup is: class AccountManager(BaseUserManager): def get_public_queryset(self): return self.get_queryset().filter(active=True, verified=True, admin=False, staff=False) Using this design works fine if I define various sorting methods in the manager (because I can simply call that method), but it seems as though there should be a better way to do this. Any ideas? -
How to Delete compete table from django sqlite database using django function in terminal?
I have written a code for my project, for that I have created some tables in Django SQLite database server. Now I want don't want table, therefore I want to remove/delete the complete table from database. Is there any way to delete table directly from the single line of code from terminal of IDE? I have tried using Django-admin from that I have use 'django-admin flush' and 'django-admin sqlflush' I am confuse what to use and what not to -
How To Render Two or More Bokeh Plots In HTML with Div and Script Tag? In Django
I want To Plot Two or More Graph in HTML using Div and script Tag , But It Plots Only last one. Am working on Django plot code..... script , divi = components(plot) plot1 = figure() plot1.circle([1,2], [3,4]) script , pie = components(plot1) return render(request,'result.html',{'company':fetch,'tabcontent':temp,'pie':pie,'last_20':last_20f,'divi':divi,'script':script}) some code... <div class="graph1"> {{divi | safe}} </div> <div class="last_20"> {{last_20|safe}} </div> <div class="pie_area"> {{pie | safe}} </div> -
html file urls is not accessible in django
register.html is not accessible on 'register/' url tried changing url to '' and webpage is accessible but not on 'register/' projects urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('login/',include('login.urls')), path('admin/', admin.site.urls), ] apps urls.py from django.urls import path from . import views urlpatterns = [ path('',views.indexView, name = "home"), path('dashboard/', views.dashboardView, name="dashboard"), #path('login/',), path('register/',views.registerView, name="register_url"), #path('logout/',), ] views.py from django.shortcuts import render def indexView(request): return render(request,'index.html') def dashboardView(request): return render(request,'dashboard.html') def registerView(request): return render(request,'register.html') templates/register.html -
#[Errno 2] No such file or directory
So, here what I am doing from the below link: https://django-microsoft-auth.readthedocs.io/en/latest/installation.html#from-sources I am trying to follow all the steps mention in the blog for the installation of django_microsoft_auth. Step-1 i.e. "pip install django_microsoft_auth" # is working Step-2 i.e. "git clone git://github.com/AngellusMortis/django_microsoft_auth" # is also working Step-3 i.e. "python setup.py install" # is giving me the below error. C:\Users\vtinkhed\AppData\Local\Programs\Python\Python37\python.exe: can't open file 'setup.py': [Errno 2] No such file or directory I don't know how to help. Could anybody help me out here? Thanks in advance -
500 internal server error during deployment of django project in elastic beanstalk
I am trying to deploy my django project in AWS elastic beanstalk. The project is deployed fine but I am getting a 500 internal server error when I go to the url after deployment. I got the following error from error log: error log mod_wsgi (pid=29607): Target WSGI script '/opt/python/current/app/DJ/wsgi.py' cannot be loaded as Python module. .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: DJ/wsgi.py StaticFiles: /static/=static/ How can I solve this? -
Defining functions inside of views
I am attempting to create a job board website and upon entering a zip code in a form, that zip code is passed to a search_results view (as zip_code). In this view I need to 1. Get the surrounding zip codes (with a certain mile radius) 2. Get objects in db that match those zip codes. I have step one complete and have not implemented step two yet (actual code not that important to question): from uszipcode import Zipcode, SearchEngine def search_results(request, zip_code): zip_codes = [] search = SearchEngine(simple_zipcode=True) # create SearchEngine object zip_code = search.by_zipcode(zip_code) #create Zipcode object? latitude = zip_code.lat longitude = zip_code.lng result = search.by_coordinates(latitude, longitude, radius = 5, returns = 5) for item in result: zip_codes.append(item.zipcode) # code that will return matching objects My question is can you define functions inside of a view in Django, like such: def search_results(request, zip_code): zip_codes = getSurroundingZipCodes(zip_code) results = getJobsInArea(zip_codes) return render(request, 'results.html', {'results: results}) def getSurroundingZipCodes(zip_code): # logic for this function def getJobsInArea(zip_codes): # logic for this function This is something I haven't seen in any tutorials so I feel like the answer is no, but I'm not sure why? -
Define max relation in ManyToManyField
Story model has a ManyToMany relationship with Genre model. I want to be able set maximum 2 genres to one story. How to do that? P.S. using serilaizers, viewsets and I am used forwardfunc in migrations to provide default genres in DB class Story(models.Model): ... genre = models.ManyToManyField(Genre) class Genre(models.Model): name = models.CharField(max_length=255) -
My functions are not working in my django project
I'm currently trying to return data in json or api view format with my following text fields (email, country and phone number), However I also have 2 validation functions to validate the value in the email and phone number fields which require the get() method and also using it to pass the text as a argument. I am not sure if the 2 validation functions are working or not as when I entered an invalid email, it is still accepted as a valid data. Please tell me what I am doing incorrectly and what changes should be made to my current code. /* serializers.py */ import re import phonenumbers from rest_framework import serializers from .models import validation from phonenumbers import carrier from validate_email import validate_email class validationSerializer(serializers.ModelSerializer): class Meta: model = validation fields = '__all__' def clean_email(self): email = self.cleaned_data.get("email") if not validate_email(email, check_mx=True, verify=True): raise serializers.ValidationError("Invalid email") return email def clean_phone_number(self): phone_number = self.cleaned_data.get("phone_number") clean_number = re.sub("[^0-9&^+]", "", phone_number) alpha_2 = self.cleaned_data.get("country") z = phonenumbers.parse(clean_number, "%s" % (alpha_2)) if len(clean_number) > 15 or len(clean_number) < 3: raise serializers.ValidationError( "Number cannot be more than 15 or less than 3") if not phonenumbers.is_valid_number(z): raise serializers.ValidationError( "Number not correct format or non-existent") … -
How to update instance's particle attribute using Django Modelseirallizer?
I want to update instance's attribute using Django Modelseriallizer. I want to change only 'tel' attribute in 'Activity' model. but my code is not working. this is model class Activity(models.Model): num = models.AutoField(primary_key=True) #번호 name = models.CharField(max_length=100, blank=True, null=True) eventStartDate = models.CharField(max_length=100, blank=True, null=True) eventEndDate = models.CharField(max_length=100, blank=True, null=True) eventTime = models.TextField(max_length=1000, blank=True, null=True) eventPlace = models.TextField(max_length=1000, blank=True, null=True) discription = models.TextField(max_length=1000, blank=True, null=True) longitude = models.DecimalField(max_digits=20, decimal_places=12, blank=True, null=True) latitude = models.DecimalField(max_digits=20, decimal_places=12, blank=True, null=True) tel = models.CharField(max_length=255, blank=True, null=True) img = models.CharField(max_length=255, blank=True, null=True) grade = models.IntegerField(default=0,blank=True, null=True) this is view class ActivityList(APIView): permission_classes = (permissions.AllowAny,) def get(self, request): data = Activity.objects.all() serializer = ActivitySerializer(data, many=True) return Response({"ActivityList":serializer.data}) this is serializer class ActivitySerializer(serializers.ModelSerializer): tel = serializers.CharField() def update(self, instance, validated_data): instance.tel = 'new tel number' instance.save() return instance class Meta: model = Activity fields = ('num', 'name', 'eventStartDate', 'eventEndDate', 'eventTime', 'eventPlace', 'discription', 'longitude', 'latitude', 'tel', 'img', 'grade') # fields = '__all__' -
How to display error message in Django template after HttpRedirect from another view?
I'm creating a simple CRUD application without using the admin page of Django. I only have one template, index.html that displays all the list of student information. I have two views below, one is for displaying only when the user visited the index page. The other view is executed when a user in the index page clicks a submit button for registering a new student (via POST) then redirects to the index view again. I want to display an error message if the student already exists in the database (by using student number). My problem is how can I pass the error message in the index.html template after the HttpRedirect. Or am I doing it the wrong way? def index(request): studentList = Student.objects.all() return render(request, "crud/index.html", {"student_list": studentList}) def addStudent(request): data = request.POST # print(data) if data: try: newStudent = Student.objects.get(student_number=data['student_number']) return HttpResponseRedirect(reverse("crud:index")) except Student.DoesNotExist: newStudent = Student(student_number=data['student_number'], first_name=data['first_name'], last_name=data['last_name'], age=data['age'], sex=data['sex'], email=data['email'] ) newStudent.save() return HttpResponseRedirect(reverse("crud:index")) -
I had an html comment in a Django template, and it was causing a server error when DEBUG=False, why?
Previously I had a favicon.png, I deleted the favicon.png file. This did not create any issues until I switched from DEBUG = True to DEBUG = False in my settings.py file. And I got a 500 server error. To diagnose the issue I added DEBUG_PROPAGATE_EXCEPTIONS = True to my settings.py And I got the following error: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'favicon.png' Only place where there was even a mention of 'favicon.png' was as an html comment in my login html template file, login.html contained the following in head: <title>Login</title> <!-- <link rel="shortcut icon" type="image/png" href="{% static 'favicon.png' %}"/> --> when I deleted the favicon.png html comment so that code became: <title>Login</title> I no longer got a 500 server error, and things worked again. How can an html comment cause an error in my code? I thought it was impossible for an html comment to cause an error. -
How to ForeignKey to a value two tables away?
I have the following models: class Ensemble(Group): name = models.CharField(max_length=100, null=True, blank=True) instrumentation = models.ForeignKey(Instrumentation, verbose_name=_('part'), related_name='ensemble_member', null=True, blank=True, on_delete=models.PROTECT) class EnsembleMember(models.Model): person = models.ForeignKey(Person, verbose_name=_('member'), on_delete=models.PROTECT) instrument ???? = models.ForeignKey(Instrumentation, verbose_name=_('part'), related_name='ensemble_member', null=True, blank=True, on_delete=models.PROTECT) //This is the line in question ensemble = models.ForeignKey(Ensemble, verbose_name=_('ensemble'), related_name='ensemble_member', on_delete=models.PROTECT) class Instrumentation(models.Model): name = models.CharField(max_length=100, null=True, blank=True) class Instrument(MPTTModel): name = models.CharField(max_length=100, null=True, blank=True) category = models.CharField(max_length=100, null=True, blank=True) instrumentation = models.ManyToManyField(Instrumentation, verbose_name=_('instrumentation'), related_name='instrument', blank=True) I would like to be able to able to link EnsembleMembers to only the instruments available in instrumentation under Ensemble. How would I create this ForeignKey relationship. For example: There are three instruments: Violin, Cello, and Piano An instance of instrumentation with this three instruments is called "Piano Trio". An ensemble called the "Beaux Arts Trio" is linked to the instrumentation "Piano Trio". "Menahem Pressler" is an Ensemble Member and the pianist in the "Beaux Arts Trio". I want to link this instrument to the "Piano". Piano is an allowable instrument to be linked because it is in the instrumentation linked to the Ensemble. How do I setup this last connection in the EnsembleMember model? -
How to use nginx to detect/post server too busy page when Django server is not responsive
When django server CPU is too busy, no GET/POST can reach django server. When it happens, I notice, browser has this page until server CPU is NOT too busy. 502 Bad Gateway nginx/1.4.6 (Ubuntu) How to configure nginx to detect/post server too busy page, because 502 Bad Gateway is not user friendly? -
Django LiveServerTestCase appears to reload fixtures between tests
I'm running this with Django 2.2.5 and Postgres 11 It appears that the Django test framework's LiveServerTestCase reloads fixture data in-between each test without deleting the previous data. I come across this with a consistent error: > ./manage.py test functional_tests Creating test database for alias 'default'... System check identified no issues (0 silenced). .EE ====================================================================== The first test passes but the subsequent tests fail. The error I get is: django.db.utils.IntegrityError: Problem installing fixture '.../fixtures/unit_test.json': Could not load app.Configuration(pk=1): duplicate key value violates unique constraint "app_configuration_site_id_3124a87d_uniq" DETAIL: Key (site_id)=(1) already exists. If I comment out and don't load fixtures the 3 tests work perfectly fine. There is only one record entry with the PK in question in the fixtures. This tells me that the Test reloads the data and fails because it finds an existing record with the same PK. Is there a way to tell it to either overwrite the data with the same PKs or ignore (a-la get_or_create)? Is there a better practice to follow with LiveServerTestCase? It's frustrating because I can't seem to be able to use this test class with fixtures when I need to. Any insight is appreciated. RB -
Django dynamic fields - cannot get data from multiples added rows - ManagementForm data is missing or has been tampered with
I am working on a template that generate multiple rows. I am missing something to all get the data from generated row. I get an exception value : ['ManagementForm data is missing or has been tampered with'] when i submit the form. I think I am missing something to get the data from multiple rows. Here is my code : models.py class Product(models.Model): contractNumber = models.ForeignKey('SupportContract', on_delete=models.SET_NULL, null=True) serialNumber = models.CharField(max_length=800, null=True) reference = models.ForeignKey('ProductDescription', on_delete=models.SET_NULL, null=True) quantity = models.IntegerField() def __str__(self): return str(self.serialNumber) if self.serialNumber else '' form.py class ProductForm(forms.ModelForm): contractNumber = forms.ModelChoiceField(required=False, queryset=SupportContract.objects.all().order_by('number'), label='contractNumber', widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'Contract number'})) serialNumber = forms.CharField(required=True, label='serialNumber',widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter serial number'})) reference = forms.ModelChoiceField(required=False, queryset=ProductDescription.objects.all().order_by('name'), label='reference',widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'Product descrition'})) quantity = forms.IntegerField(initial=1, required=True, label='quantity',widget=forms.NumberInput(attrs={'class': 'form-control','placeholder': 'Enter a quantity'})) class Meta: model = Product fields = '__all__' def clean(self): super().clean() contractNumber = self.cleaned_data.get('contract_number') serialNumber = self.cleaned_data.get('serial_number') reference = self.cleaned_data.get('product_reference') quantity = self.cleaned_data.get('quantity') ProductFormset = formset_factory(ProductForm, extra=1) template.html <div data-role="dynamic-fields"> {{ form_Product.management_form }} <div class="form-inline" style="margin-left: -15px"> <div class="form-group col-md-2"> {{ form_Product.quantity }} </div> <div class="form-group col-md-2"> {{ form_Product.serialNumber }} </div> <div class="form-group col-md-2"> <button class="btn btn-danger" data-role="remove"> <span class="fas fa-minus"></span> </button> <button class="btn btn-primary" data-role="add"> <span class="fas fa-plus"></span> </button> </div></div></div> views.py def form_exhibit_c(request): ProductFormset … -
If the field is not entered, how to make it not filtered in django
I am creating a lookup field and would like to know how do I do so that if a field is not entered it does not appear in the address bar even if its value is null. http://localhost:8000/pesquisa/?prova= to http://localhost:8000/pesquisa/ views.py def index(request): provas = Prova.objects.all().order_by('idProva') questoes = Questao.objects.filter().order_by('idProva') categorias = Categoria.objects.all().order_by('nomeCategoria') form = QuestaoProvaForm() return render(request, 'polls/index.html',{'categorias':categorias,'questoes':questoes,'provas':provas,'form':form}) def pesquisa(request): template_name = 'polls/pesquisa.html' query = request.GET.get('q', '') prova = request.GET.get('prova', '') questao = request.GET.get('questao', '') categoria = request.GET.get('categoria', '') results = Questao.objects.filter(idProva=prova) return render(request, template_name, {'results': results,'prova':prova,'questao':questao,'questoes':questoes}) -
How to set up WSGI conf file
I am deploying to productions server but cannot get my static files to work for the life of me. My Apache error logs say: [Thu Oct 03 23:12:17.805038 2019] [mpm_event:notice] [pid 5987:tid 139950847048640] AH00491: caught SIGTERM, shutting down [Thu Oct 03 23:12:17.965217 2019] [mpm_event:notice] [pid 6092:tid 140185146706880] AH00489: Apache/2.4.38 (Ubuntu) mod_wsgi/4.6.5 Python/3.7 configured -- resuming normal operations [Thu Oct 03 23:12:17.965310 2019] [core:notice] [pid 6092:tid 140185146706880] AH00094: Command line: '/usr/sbin/apache2' [Thu Oct 03 23:12:22.324089 2019] [wsgi:error] [pid 6093:tid 140185001051904] [remote 73.192.250.234:60904] Not Found: /users/static/users/main.css And my .conf file: Alias /static /home/david/sc/static <Directory /home/david/sc/static> Require all granted </Directory> Alias /media /home/david/sc/media <Directory /home/david/sc/media> Require all granted </Directory> I am sure it has to do with the fact that my static files are in /sc/users/static/users/ but nothing I do can get the WSGI to point to that folder.. -
Stop .filter() on first match in Django
Is there a way to stop querying the remaining records in the database after the query returns a match. For instance if I do this: Profile.objects.filter(first_name='Dwight') I want it to stop running the query for all the Profiles as soon as it finds a Profile with the first_name of Dwight. -
How swap article from MySql databse using asynchronous threads in Django
Is possible to achieve something like slider in Django ? I would like swap article which came from MySql database in random time. I pretty sure that I can do that using multithreading , but i don't know how handle requests. Thank you for any answer -
Django, autocomplete_light : autocomplete does not work over https
autocomplete suggests some things like below with a URL over http://.... autocomplete does NOT suggest anything with the same URL over https://... How can I make the autocomplete over https to work like the one over the http? -
Django context variable as inline css property's value
i'm trying to pass in a context variable as the value for css property but i can't seem to get it to work <nav style="background-color: {{ nav_color }};"> i tried wrapping the variable in single quotes but it still won't work even though i know the variable gets passed when i inspect the element using devtools(it gets passed with the quotes and hence is not a valid css property) i.e <nav style="background-color: '{{ nav_color }}';"> // doesn't work -
How to replace Google Map Key generated by JAVASCRIPT script in DJANGO by a custom variable
I am trying to find a way to hide my google map key displayed on the javascript script. The key is generated from django settings. I am not sure how to properly achieve it with javascript script and src settings.py GOOGLE_MAP = "XZZZZZZX" views.py def activity_list(request): """ Render list of foo. """ foo = Foo.objects.all() # Google Map Key google_map_key = settings.GOOGLE_MAP context = { 'foo': foo, 'google_map_key': google_map_key } return render(request, 'snippet/index.html', context) HTML {% extends "base.html" %} {% load static %} {% block content %} <!-- Render Map on HTML --> <div id="map"></div></br></br> <!-- Pass the Google Map key variable to Front end --> <div id="google_map" style="display:none" value="{{ google_map_key }}"></br> {% endblock %} {% block key %} <!-- Grab the Google Map key value from HTML above --> var name_ = document.getElementById('google_name').getAttribute("value"); <!-- Google Map Key --> <script id="name" data-name="value" src="https://maps.googleapis.com/maps/api/js?key=XZZZZZZX&callback=initMap" async defer></script> {% endblock %} How can I possibly replace the google map key with the custom variable from the backend? -
Read-the-docs subdomain not working as intended
I am using private read-the-docs server , let's say hosted on "docs.example.com". I am trying to host my documentation build on subdomain, "project.docs.example.com". When I go to that subdomain, browser displays 404 error.There is not project on this path. What configuration am I missing here. I have these settings already set: In /settings/base.py USE_SUBDOMAIN=True PUBLIC_DOMAIN=docs.example.com DEBUG=True I added domain "project.docs.example.com" in my project and I click on checkbox to use that domain as primary one for hosting documentation of that project. I clicked on checkbox "Use single version", for document to be hosted on subdomain without versions. I set my documentation to "Public documentation" Expected result: When click "View docs" after build is finished successfuly it redirected me to "project.docs.example.com" and I see my documentation. Actual result: It redirected me to "project.docs.example.com" but I see 404 error File not found on this path. After some digging arround I found out that my documentation is visible only on docs.example.com/docs/project. -
How to Filter ".get_fields()" to Exclude Proxy Models in Django?
How can I get a list of fields from a given model, but exclude fields from an abstract model? The docs on .get_fields say the following: include_parents True by default. Recursively includes fields defined on parent classes. If set to False, get_fields() will only search for fields declared directly on the current model. Fields from models that directly inherit from abstract models or proxy classes are considered to be local, not on the parent. Which is great, except that I need to exclude proxy/abstract model fields as well. For example: class AbstractModel(models.Model): some_abstract_field = models.IntegerField() class Meta: abstract = True class SomeModel(AbstractModel): some_field = models.IntegerField() How can I get a list of fields for SomeModel but exclude fields from AbstractModel? The only solutions I can think of: subclassing the ModelBase metaclass for my models to include the distinction between abstract models and child models This sounds like a nightmare for a multitude of reasons... monkey patching my abstract models to include a property that returns list of field names I'll likely end up posting an answer using this route, but surely there is a more pythonic way of doing this.