Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app on GKE (Kubernetes): Click on external IP of load balancer and gives "Bad Request (400)"
Probem: I have 2 replicas for my app, library. I have configured a service to talk to my two replicas. I have a dockerfile that starts my app at port # 8080. The load balancer and the app containers all seem to be running. However, I am not able to connect to them. Every time I click on the external IP shown I get "Bad Request (400)" > $ kubectl get services NAME TYPE CLUSTER-IP > EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP > 10.19.240.1 <none> 443/TCP 61m library-svc LoadBalancer 10.19.254.164 34.93.141.11 80:30227/TCP 50m > > > $ kubectl get pods NAME READY STATUS > RESTARTS AGE libary-6f9b45fcdb-g5xfv 1/1 Running 0 > 54m library-745d6798d8-m45gq 3/3 Running 0 12m Here is the library.yaml file I have to go with it. # [START kubernetes_deployment] apiVersion: extensions/v1beta1 kind: Deployment metadata: name: library labels: app: library spec: replicas: 2 template: metadata: labels: app: library spec: containers: - name: library-app # Replace with your project ID or use `make template` image: gcr.io/library-259506/library # This setting makes nodes pull the docker image every time before # starting the pod. This is useful when debugging, but should be turned # off in production. imagePullPolicy: Always env: # [START cloudsql_secrets] … -
Data From Database Not Loading into HTML table Django
I would like to create a table that lists the rows from a small database (7 rows including header, 3 columns) to an HTML table. I am working in Django and have checked "myapp"views.py, "myapp".urls, and the base.html. I also checked myprojects url settings and did not see anything. Any help would be great. Windows 10 Django 2.2.7 Python 3.8 My code is below: my\app view.py def repList(request): all_objects_Rep=Rep.objects.all() context={'all_objects_Rep': all_objects} return render (request, 'base.html', context) myproject\urls.py urlpatterns = [ path('', include('page.urls')), path('rep/', include('page.urls', namespace='reps')), path('home/', include('page.urls', namespace='home')), path('results/', include('page.urls', namespace='results')), path('admin/', admin.site.urls), myapp\urls.py app_name = 'page' urlpatterns = [ path('', views.homepage_view, name='homepage_view'), path('Rep/', views.repList, name='repList'), path('userInput/', views.userInput, name ='User Input'), path('results/', views.results_view, name='results_view'), myapp\base.html <div class ="RepList"> {% block repList %} <table> <tr> <th>District</th> <th>First Name</th> <th>Last Name</th> </tr> {% for x in all_objects_Rep %} <tr> <td>{{ x.District }}</td> <td>{{ x.f_name }}</td> <td>{{ x.l_name }}</td> </tr> {% endfor %} {% endblock %} </table> </div>``` -
How to stop Django from serving files locally?
I need to prevent local Django/runserver from serving my static files (I want to test whitenoise locally). The --nostatic flag is supposed to do just that. python manage.py runserver --nostatic But I still get 200s (successful) for my static files. So then I set debug = False but still get 200s! I even commented out 'django.contrib.staticfiles' from INSTALLED_APPS. But this did not work either. How could my static files still be served successfully - it's usually not this hard to break things. Perhaps I am misunderstanding what nostatic actually does; I was expecting to get 404s. -
Is there a way not to overwrite heroku database?
I have deployed django-telegram-bot on heroku and i'm changing codes with pycharm(offline) So every time that i push my codes to heroku, data in database is lost Is there a way not to overwrite heroku database? Maybe there is a way to connect heroku and pycharm so i am able to code remotely -
Set user to group when created
I have created a form where user can create their own group, everything work except that the group is not set to the user, so it is worthless. This is my views.py : @login_required def creategroup(request): if request.method == 'POST': groupcreate = Group() groupcreate.user = request.user groupcreate.name = request.POST['name'] groupcreate.save() I have set user, but it does not take the value -
Form Validation Not Displaying on Form
I have a custom form validation that runs on my popup window form. If the form validation occurs i get a bad request error which is what i have programmed in my views.py . How do i render it so the user stays on the form and the validation message displays. Thanks for the help. Here is my code. @login_required def K8_Points_Classroom(request): #context_from_k8_points = request.session['k8_points_context'] if request.method == 'POST': form = K8Points_ClassroomForm(request.POST) if form.is_valid(): form.save(commit=False) form.save() class_name = form.cleaned_data.get('class_name') getstudents = Student.objects.filter(class_name = class_name) students = getstudents.all() form = K8Points_ClassroomForm() context = {'form': form ,'students' : students, 'class_name': class_name,} return render(request,'points/k8_points_classroom.html', context) else: return HttpResponseBadRequest("Bad Request") else: return render(request, 'points/k8_points_classroom.html', {'form': form} ) -
How to setup Django and Solr with Docker Compose?
Below is my Docker Compose file: version: '3' services: search: image: solr ports: - 8983:8983 backend: build: ./backend volumes: - ./backend:/some-library/backend ports: - 8000:8000 stdin_open: true tty: true links: - search environment: - DJANGO_SETTINGS_MODULE=settings.development command: python manage.py runserver 0.0.0.0:8000 and the following is my settings.py where I use django-haystack: HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.solr_backend.SolrEngine', 'URL': 'http://solr:8983/solr/', }, } Now when I try to run python manage.py rebuild_index I always get an error. How should I fix this? -
Reordering Initial Migration calculations
Every time I try to migrate my initial migration, right after makemigrations, I get errors like : django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'Project.Class'>] This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth) The reason I think this happens is because the order of model operations in the 0001_initial.py migration is incorrect. Operations with classes which inherit from others are added before their parents'. After I reorder the operations, it works: Process finished with exit code 0. Cool! But how do I make makemigrations work without doing this every time? Thanks! ps. I tried reordering the import order of my models in the model's __init__.py but it didn't work. -
I'm using django-extra-views to have 2 forms on 1 page. How should I handle custom logic in form_valid?
Here is my views.py code class AttackItemInline(InlineFormSetFactory): model = AttackItem fields = ['attack_used','attack_image'] factory_kwargs = {'extra': 1} class AttackImageCreateView(CreateWithInlinesView): model = AttackImage inlines = [AttackItemInline] template_name = 'engine/attack_image_create.html' fields = ['title','image','source_url'] def form_valid(self, form): f = form.save(commit=False) f.creator = self.request.user f.hidden_data_found = attacks.spa(f.image) f.save() class AttackItemCreateView(CreateView): model = AttackItem template_name = 'engine/attack_item_create.html' def form_valid(self, form): f = form.save(commit=False) f.creator = self.request.user f.save() As you can see I have 2 forms and only 1 form valid. I don't know how to deal with that. Here is my frontend code: {% extends 'base.html' %} {% block content %} <div class="col-md-4 col-md-offset-4 downdown whitebox"> <form method="post" action="{% url 'attack_image_create' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form }} {% for formset in inlines %} {{ formset }} {% endfor %} <input type="submit" value="Submit" /> </form> </div> {% endblock %} How should I be handling custom logic? Like saving the f.creator, saving finding and saving f.hidden_data_found, etc. Link to package: https://github.com/AndrewIngram/django-extra-views -
Django Template: Iterate over a Dictionary of Lists of Dictionaries
I'm having a rough time wrapping my mind around iterating through a context_dict in django. It's a complicated dictionary that I don't have much control over. context_dict = { 'circuitIds_found': # First property (not dynamic) { 'output_123.csv': # csv file where search results were found (dynamic) [ { 'PATH_NAME': '80.L1XX.802084..ABC', 'SERVICE_CATEGORY': 'ETHERNET', 'UNIQUE_FLOW_ID': '80.L1XX.802084..ABC', }, { 'PATH_NAME': '80.L1XX.806000..ABC', 'SERVICE_CATEGORY': 'ETHERNET', 'UNIQUE_FLOW_ID': '80.L1XX.806000..ABC', } ], 'output_456.csv': # another csv file where search results were found (dynamic) [ { 'PATH_NAME': '80.L1XX.123456..ABC', 'SERVICE_CATEGORY': 'ETHERNET', 'UNIQUE_FLOW_ID': '80.L1XX.123456..ABC', } ], 'circuitIds_not_found': [] . # Second property (not dynamic) } I render in views.py: ... return render(request, 'mainApp/index.html', context=context_dict) And then attempt to do nested template for loops: {% for key, value_list in search_results_match.items %} {{ key.unique_flow_id }} <ul> {% for key, value in value_list.items %} <li>{{ key }} : {{ value }}</li> {% endfor %} </ul> {% endfor %} The end goal is to have a rendered list as follows, but the above templating, and everything else I've tried is just not working out..... 80.L1XX.802084..ABC PATH_NAME: 80.L1XX.802084..ABC SERVICE_CATEGORY: ETHERNET 80.L1XX.806000..ABC PATH_NAME: 80.L1XX.806000..ABC SERVICE_CATEGORY: ETHERNET 80.L1XX.123456..ABC PATH_NAME: 80.L1XX.123456..ABC SERVICE_CATEGORY: ETHERNET -
Django Model Form Require Boolean Field To Be Checked True To Submit Form
I would like a boolean field to be required to true in order for the form to be submitted and to throw an error to agree to the terms. Best way to do this? -
Alternative for Elaphe library after upgrading to python 3?
trying to update to python 3+ on my django project but in order to produce some barcodes we are currently using Elaphe (https://pypi.org/project/elaphe/). We use it to produce both QRcodes and Barcodes. I was wondering what everyone else is using that is Django 1.8 compatible and Python 3+ -
Rendering a view on multiple template
So i am trying to render a function on multiple page. This function is rendering the total of task an user has still undone. my views.py context = { "lists": lists, "reccurence": reccurence, "thedate": thedate, "searchform": searchform, "list_count": list_count, "task_count": task_count, } return render(request, "todo/list_lists.html", context) So I thought, maybe I could add more page so it will also render my model on list_detail etc., but it does not work, only working on list_lists.html -
Django Custom Field Validation
I have a validation function in my forms.py that needs to meet the following conditions.Here is my code. The def clean_time frame has to check the following in the database: 1. Timeframe 2. Student 3. Date So if i pick timeframe 9 am for student john smith. You cant logg the same time frame for the student on the same day. How do i make that happen ? Thanks forms.py class K8Points_ClassroomForm(forms.ModelForm): class Meta: model = K8Points fields = ('student_name', 'behavior','academic', 'time_frame','date','day','week_of','class_name') def clean_time_frame(self): time_frame = self.cleaned_data.get('time_frame') date = self.cleaned_data.get('date') student_name = self.cleaned_data.get('student_name') if (time_frame == ""): raise forms.ValidationError('Field can not be left blank !') for instance in K8Points.objects.all(): if instance.time_frame == time_frame: raise forms.ValidationError('This timeframe was already logged !' + time_frame) return time_frame -
Django - Filter by non-existing foreign key
My two models look like this: class Sentence(models.Model): language = models.ForeignKey('Language') class TranslatedSentence(models.Model): sentence = models.ForeignKey(Sentence, related_name='translated_to') language_to = models.ForeignKey('Language') I can filter by sentences that have been translated to a specific language: Sentence.objects.filter(translated_to__language_to__name='Spanish') My question is: How can I filter all sentences that have not been translated to a given language? -
Django Admin custom form - Foreign key field as searchable instead on dropdown
class modelA(Base): account = models.ForeignKey… user = models.ForeignKey… class modelB(Base): user = models.ForeignKey… amount = models….. class modelC(Base): modelA = models.ForeignKey(modelA) modelB = models.ForeignKey(modelC) class formA(forms.ModelForm): account = forms.ModelChoiceField(queryset=Account.objects.all()) user = forms.ModelChoiceField(queryset=User.objects.all()) amount = CustomField….. def save() … class formAAdmin(admin.ModelAdmin): form = formA raw_id_fields = (‘account’) // Cannot use account as it does not belong to modelC. Account is shown as a dropdown but I want it as a popup where we can search. I am getting this error when I added account in raw_id_fields. : (admin:E002) the value of ‘raw_id_fields[0]’ referes to account which is not an attribute of ‘modelC’ . Since account is not part of the modelC, it just displayes it as a dropdown. How can I make it show search for account? -
Simpe upload image button in django
I am new in Django, so do not be mad, i just do not know how to add a button which will upload a file to the specific post in my model. So the problem is how to get the identifier of each post from my model without go to specific url, only in page with all posts My model: class Post(models.Model): title = models.CharField(max_length=20, db_index=True) slug = models.SlugField(max_length=50, unique=True) project_image = models.ImageField(upload_to='images/', blank=True) technologists = models.ManyToManyField('ImageTag', blank=True, related_name='tags') description = models.CharField(max_length=200, blank=True) programme_language = models.CharField(max_length=40, blank=True) update_time = models.CharField(max_length=40, blank=True) link = models.URLField() def __str__(self): return self.title def get_absolute_url(self): """Gettign the absolute url of index.html""" return reverse('project_detail_url', kwargs={'slug': self.slug}) def get_update_url(self): return reverse('project_edit_url', kwargs={'slug': self.slug}) def get_delete_url(self): return reverse('project_delete_url', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): """Complement the method save of django Model""" # if not self.id: # self.slug = gen_slug(self.title) if not self.slug: self.slug = gen_slug(self.title) if self.slug: checker = self.slug.strip() if checker: pass else: self.slug = gen_slug(self.title) super().save(*args, **kwargs) my main html pattern which extend base html pattern and which contain each post detail from my model: {% extends 'base.html' %} {% block content %} {% for post in posts %} <div class="post-wrap"> <div class="title_and_image"> <h2>{{ post.title }}</h2> … -
Django ModelSelect2MultipleWidget FormView won't display initial data
I am using django_select2.forms.ModelSelect2MultipleWidget, forms.Form, FormView. I have 3 tables: Job, HelpText, JobHelpText. From a Job detail page, I want to direct to the Form view (autocomplete multiple select widget), and for that input to have the initial data of all other Jobs associated with that Help Text. What is working: I can autocomplete search for jobs. It only gives access to jobs without help text (like desired). Python print statement is even showing the correct initial data. What won't work: The initial data won't pre-fill in the input box. class Foo(models.Model): job_name = models.CharField(max_length=200, blank=False, null=False) env = models.CharField(max_length=200, blank=False, null=False) ... def __str__(self): return self.job_name class HelpText(models.Model): name = models.CharField(unique=True, max_length=255) ... def __str__(self): return self.name class FooHelpText(models.Model): foo = models.OneToOneField(Autosys, on_delete=models.CASCADE,) help_text = models.ForeignKey(HelpText, on_delete=models.DO_NOTHING, ) ... def __str__(self): return str(self.foo) class ManageFooJobs(AdminCapableJSMixin, django_select2.forms.ModelSelect2MultipleWidget): """ only show foo jobs that have no help text """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = models.Foo.objects.filter(foohelptext__isnull=True) search_fields = [ 'job_name__icontains', ] class ManageJobsForm(forms.Form): """ add or remove jobs """ foo_jobs = forms.MultipleChoiceField( widget=widgets.ManageFooJobs(), required=False, ) class ManageJobsView(LoginRequiredMixin, BootstrapFormMixin, FormView): """ able to add and remove jobs from a help text """ form_class = forms.ManageJobsForm def get_initial(self, *args, **kwargs): initial … -
Add vue js to existing web app (written in django) using docker
I have an existing web app that is written in Django. The app is currently in a Docker container. I have also integrated django REST framework Problem: I am a new developer, therefore I do not know how to add vue js to my existing web app. Attempted solutions: I have spent a few days searching online and although I found a number of tutorials online, none of them solved my specific problem. My tutor told me that I need to add a container that uses vue to my existing situation...that is going to require moving the docker-compose fly and make some changes to the paths in it –– which sounds pretty straight forward, but after attempting to make the addition and changes, this task has turned out to be not so simple. Not asking for someone to give me a step by step answer, rather I would appreciate any tips, suggestions that will help me get going in the right direction to solve my problem. -
Access dynamically created model django
I was working on a Django app which requires creating tables dynamically. def dcreatedb(request): attrs = { 'name': models.CharField(max_length=20), '__module__': 'data.models' } model = type('books', (models.Model,), attrs) with connection.schema_editor() as schema_editor: schema_editor.create_model(model) return HttpResponse('done') The above dcreatedb view creates a model dynamically. But I need to access the same model in some other view but the view is not in the models.py file in the app and created dynamically by the dcreatedb view. def dinsertdb(request): # access the book model and do some work return HttpResponse('work done') for instance let us suppose a model named books is created by the dcreatedb view dynamically, and now I want to access the same model in the dinsertdb view.(Both the dcreatedb model and the dinsertdb models are in the same views.py file under the same app.) How can this be done? Thanks -
Unable to loop through an object in JavaScript
I’m a bit lacking of knowledge in JS. I am accessing some data through an API and retrieving it as JSON. This data is getting into JS very nicely. But I do not really understand with which type object I’m dealing with. I cannot determine the length and also the other loop methods do not work. But I can access the object elements like an array with REValues[0] – first element. '''function drawTable() { debugger; var REValues = {{ json|safe }}; var data = new google.visualization.DataTable(); data.addColumn('number', 'ID'); data.addColumn('string', 'Stadt'); data.addColumn('string', 'Bezirk'); data.addColumn('number', 'Einkaufswert'); data.addColumn('number', 'Fläche'); data.addColumn('number', 'Miete'); for (var REValue in REValues) { debugger; }''' enter image description here -
Django PermissionDenied empty page in production
I have a Django app that is not displaying permission denied exceptions correctly. The project has a custom 403.html template that displays perfectly fine locally and used to work on production but at some point stopped working and I am having a heck of a time tracking down why. The app is served using Apache and Nginx. 403.html extends base.html and should show the normal site styling, menus, etc with the passed in exception message displayed. On production though, every single PermissionDenied raised shows a blank white page stating: "You don't have permission to access /some/path on this server." The Nginx access log shows a single 403 request to the route in question and nothing in the error log. The Apache access log also shows a 403 GET request to the given route. The error log shows the expected PermissionDenied exception. As part of debugging I have tried changing the default permission_denied view that comes included in django. If I change the view to return HttpResponse('test'), the permission denied response still shows a white page, but it does show the given text, 'test'. But if I try the following instead: log.info('a') resp = render(request, '403.html', context={'exception': str(exception)} log.info('b') return HttpResponse(resp) … -
I am getting an error when I am updating the post. It displays in the comment section but not update the post
I am new in Django. I am making Simple Blog site. But I am getting an error when I am updating the post. It displays in the comment section but not update the post. Here is the Code in; View.py from django.db.models import Count, Q from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render, get_object_or_404, redirect, reverse from .forms import CommentForm, PostForm from .models import Post, Author from marketing.models import Signup def get_author(user): qs = Author.objects.filter(user=user) if qs.exists(): return qs[0] return None def search(request): queryset = Post.objects.all() quary = request.GET.get('q') if quary: queryset = queryset.filter( Q(title__icontains=quary) | Q(overview__icontains=quary) ).distinct() context = { 'queryset' : queryset } return render(request, 'search_results.html', context) def get_category_count(): queryset = Post \ .objects \ .values('categories__title') \ .annotate(Count('categories__title')) return queryset def index(request): featured = Post.objects.filter(featured=True) latest = Post.objects.order_by('-timestamp')[0:3] if request.method == 'POST': email = request.POST['email'] new_signup = Signup() new_signup.email = email new_signup.save() context = { 'object_list': featured, 'latest': latest } return render(request, 'index.html', context) def blog(request): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[:5] post_list = Post.objects.all() paginator = Paginator(post_list, 4) page_request_var = 'page' page = request.GET.get(page_request_var) try: paginated_queryset = paginator.page(page) except PageNotAnInteger: paginated_queryset = paginator.page(1) except EmptyPage: paginated_queryset = paginator.page(paginator.num_pages) context = { 'queryset' : paginated_queryset, 'most_recent' … -
Django - 'NoneType' object has no attribute 'threads'
Hello guys so I am trying to add a category system for posts by following a tutorial on this website https://djangopy.org/how-to/how-to-implement-categories-in-django/ (I changed my code up a little) I get this error 'NoneType' object has no attribute 'threads' every time I try and go to the category page to view the posts inside that category. models.py: from django.db import models from django.urls import reverse from django.utils.text import slugify class Category(models.Model): name = models.CharField(max_length=100) short_desc = models.CharField(max_length=160) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "Categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) def save(self, *args, **kwargs): value = self.name self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) class Thread(models.Model): ... category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE, related_name='threads') ... def get_cat_list(self): k = self.category breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb)-1): breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1]) return breadcrumb[-1:0:-1] ... views.py: from django.shortcuts import render, HttpResponseRedirect from django.contrib import messages from .models import Category, Thread from .forms import SubmitScamNumber def show_category_view(request, hierarchy=None): category_slug = hierarchy.split('/') category_queryset = list(Category.objects.all()) all_slugs = [ x.slug for … -
Django multiple models , multiple fields lookup in autofield coloumn
I have two models BOQ and DPR boq model choicestype=(('start','start'),('finish','finish')) class boqmodel(models.Model): code = models.IntegerField() building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True) level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True) activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True) subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True) duration = models.IntegerField() linkactivity = models.CharField(max_length=300,null=True,blank=True) linktype = models.CharField(choices=choicestype,max_length=300,null=True,blank=True) linkduration = models.IntegerField(default=0) plannedstart = models.DateField(null=True,blank=True) plannedfinish = models.DateField(null=True,blank=True) actualstart = models.DateField(null=True,blank=True) actualfinish = models.DateField(null=True,blank=True) DPR class dprmodel(models.Model): Date=models.DateField() Contractor=models.CharField(max_length=300) Building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True) Level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True) Activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True) Subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True) Status=models.CharField(choices=choicestype,max_length=300) Labor=models.IntegerField() Both the models have Building,Level,Activity,Sub Activity as common fields. My entry in BOQ code=1 building=A-1 Level=L-1 Activity=Activity-1 Subactivity-Subactivity-1 duration=2 linkactivity=null linktype=null linkduration=null planned start=01-01-2019(as linkactivity=null) plannedfinish=03-01-2019(planned start+duration) MY DPR Entry Date :10-1-2019 contractor :A building=A-1 Level=L-1 Activity=Activity-A Subactivity=Subactivity-A Status =Start Labor=2 I need to populate the Actual start date in boqmodel such that if boqmodel.building = dprmodel.building and boqmodel.level = dprmodel.level and boqmodel.activity = dprmodel.activity and boqmodel.subactivity = dprmodel.subactivity and dpr.status=start. If the above condition exists then boq.actualstart=dpr.date I am thinking of creating a new field in two models by joining the building,level,activity and subactivity .Then i can join two models using the newly created fields. Any help would be appreciated.