Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add code in the github repository to the html template with django
I want to create a website which will show the code requested by user, taking it from my github repository. I am using django as a backend, but as i am completely beginner here in django, i don't know how to take code from repository and show it on html page. Please can anyone help me with this? -
Translator in an invented language django
I am currently coding my first website, which is a translator in an invented language. You input a random phrase and it should get translated in the invented language. Here's the code for the translation: class TranslatorView(View): template_name= 'main/translated.html' def post (self, request,*args, **kwargs): return render(request, self.template_name) def get (self, request, phrase, *args, **kwargs): phrase = request.POST.get('text', 'translation') translation = phrase for letter in phrase: if letter.lower() in "a": if letter.isupper(): translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper(): translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper(): translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper(): translation = translation + "C" else: translation = translation + "c" context = { 'translation': translation } return render(request,'main/translator.html', context) Template where you input the phrase: {% extends "base.html"%} {% block content%} <form action="{% url 'translated' %}" method="post">{% csrf_token %} <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" name='text' id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> {% endblock content %} Template where the text should appear translated: {% … -
Is it possible to import in forms.py values from a view function Django? Is there another way to create functions in forms.py?
In my forms.py I have a section of code which gives me an error when I try to migrate for the first time. So I thought a good solution would be to change the location of the code. This is the problem section: tags = Tag.objects.all() choice_list_tags =[] for tag in tags: choice_list_tags.append(tag) Its role is to create a list which is used in widgets -> tags -> choices And this is my forms.py: from django import forms from .models import BlogPost, Category, Tag class SimpleForm(forms.Form): content = forms.CharField(widget=forms.Textarea) tags = forms.MultipleChoiceField() tags = Tag.objects.all() choice_list_tags =[] for tag in tags: choice_list_tags.append(tag) class BlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['title', 'content', 'preview_content', 'private', 'tags'] widgets ={ 'title': forms.TextInput(attrs={'class': 'form-control'}), 'content': forms.Textarea(attrs={'class': 'form-control'}), 'preview_content': forms.TextInput(attrs={'class': 'form-control'}), 'private': forms.CheckboxInput(attrs={'class': 'form-check-label'}), 'tags': forms.CheckboxSelectMultiple(choices=choice_list_tags, attrs={'class': 'form-check-label'}), } I tried to create in context_processors.py a function and import the values in forms.py but I dont know how. Iam not sure that's the solution either def tag_list(): tags = Tag.objects.all() choice_list_tags =[] for tag in tags: choice_list_tags.append(tag) return {'choice_list_tags':choice_list_tags} If there is any other solution to avoid the error for the first migration or to make the logic in a view and import it … -
Gunicorn + Django + Nginx configuration has upstream issue
I have configured Gunicorn with Nginx for a Django application. I have received a lot of traffic to my website and I saw an nginx error where it was mentioned Gunicorn.sock failed. What does it mean? Also, Do we need to create gunicorn.conf.py for Gunicorn server? Is it mandatory? -
How can i use the nested ModelSerializer()?
I am trying to use this nested ModelSerializer class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id','email','username','password','followiing') def get_fields(self): fields = super(UserSerializer, self).get_fields() fields['followiing'] = UserSerializer(many=True) return fields This system is not making any changes. What is the issue here that i can't understand? -
Django Model Mocking - Better to create model or mock model for testing?
I have a very simple model like this: class Observation(models.Model): thing = models.ForeignKey(Thing, on_delete=models.PROTECT) user_locked = models.BooleanField(default=False) admin_locked = models.BooleanField(default=False) created = models.DateTimeField(auto_now=False, auto_now_add=True) created_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_created_by" ) updated = models.DateTimeField(auto_now=True, auto_now_add=False) updated_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_updated_by" ) def is_fully_locked(self): """Return boolean if Observation is locked by both""" if self.user_locked and self.admin_locked: return True return False I'm trying to test the is_fully_locked() method and I was curious about creating the Observation model. I have used things like Mixer and factory_boy in the past to create objects to test against, but as those projects grew so did the time it took for the tests to run which I'd like to avoid. I have recently started reading about using Mock (I'm still confused by it a little). My question is - for a simple model like this - what is the best/fastest way to test that method? Currently I have some test like this: class ObservationTest(TestCase): def test_is_fully_locked_with_no_employee_locked(self): start = time.time() observation = Observation(admin_locked=True) print(time.time() - start) # Takes 5.91278076171875e-05 # FASTEST self.assertFalse(observation.is_fully_locked()) def test_is_fully_locked_with_no_employee_locked_mixer(self): start = time.time() observation = mixer.blend(Observation, admin_locked=True) print(time.time() - start) # Takes 0.011276006698608398 # SLOWEST self.assertFalse(observation.is_fully_locked()) def test_is_fully_locked_with_no_employee_locked_mock(self): start = time.time() observation = … -
Django forms - create a variable based on user input selection
I am attempting to create a router config generator using django form. The idea is that the form takes input / choices and these are then displayed as part of a larger router config page using jinja and html. Where I am getting stuck is being able to create a new variable based on input and displaying this in the config_page.html. So for example lets say for 'WAN_SubnetMask' '30' is selected, I want to take the integers entered for 'WAN_Subnet', perform some very basic math e.g. add 2 and then create a new variable called 'WAN_IP'. I can display objects from my database in the however the 'WAN_IP' does not show as desired. Here is what I have come up with so far, I have tried adding the logic to create the 'WAN_IP' variable in both forms and views. forms.py from django import forms from .models import CPEconfig Router = [ ('2901', 'Cisco 2901'), ('1941', 'Cisco 1941'), WAN_SubnetMask = [ ('30', '30'), ('29', '29'), ] LAN_SubnetMask = [ ('30', '30'), ('29', '29'), ] class ConfigForm(forms.ModelForm): Router = forms.CharField(label='Select Router', widget=forms.Select(choices=Router)) WAN_Subnet = forms.GenericIPAddressField() WAN_SubnetMask = forms.CharField(label='WAN Subnet Mask', widget=forms.Select(choices=WAN_SubnetMask)) LAN_SubnetMask = forms.CharField(label='LAN Subnet Mask', widget=forms.Select(choices=LAN_SubnetMask)) class Meta: model = CPEconfig … -
Django not deleting stored messages when iterated over
I'm tryin to retrieve django messages through an api. However the messages are not being deleting upon iteration. It is being consumed with Vue JS on the front-end with a request made through Axios. def api_messages(request): all_messages = [] stored_messages = messages.get_messages(request) for message in stored_messages: all_messages.append({"message": message.message, "tag": message.tags}) response = {"messages": all_messages} return JsonResponse(response) -
Create an app only for the homepage in Django?
The rest of the apps do not seem relevant enough to make use one of their views as the main homepage. Is it a bad practice to create an app only for the homepage? What is the best practice for the homepage when developing in Django? Or at least the most common? -
translate django formset to apollo graphql mutation
I'm currently converting a full django app to a Django/React app and I need to update multiple objects in the same form. I'm using GraphQl with apollo client to link React and Django but I can't find to process to replicate the django Formset. Anyone has an idea ? -
Django and Celery - ModuleNotFoundError: No module named 'celery.task'
I wanted to start a periodic task in Django using Celery. Here are the relevant parts of my project: # celery.py from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookProjectSetting.settings') app = Celery('bookProjectSetting') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') The __init__.py looks like this: # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) My tasks.py file in my books app folder looks like this: from books.models import Book from celery.schedules import crontab from celery.decorators import periodic_task @periodic_task( run_every=(crontab(minute='*/10')), name="update_life_time_of_books", ignore_result=True) def update_life_time_of_books(): # do sth. I also set up redis as broker and installed the django-celery-beat stuff. But when I run the worker via the command: celery -A bookProjectSetting beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler Then I get the following error: File "/home/ac3l1k/Desktop/PROJECT/simpleDjangoProjects/bookProject/env/lib/python3.8/site-packages/celery/local.py", line 403, in _compat_periodic_task_decorator … -
Input text boxes in HTML for loop not recognized
so I am trying to align each Comment input box and comment text per updated posts. I am using for loop to iterate all the posts but only the text input in very first comment input box is recognized, and trying to enter text input on other boxes returns "enter a text" error. Will there be any way to fix this? Below is the code of my for loop. <ol> {% for post in posts reversed%} <li> {% csrf_token %} </form> <span class="details"> <a href ="{% url 'profile' post.created_by.id %}"> <label>Post by</label> <span id = "id_post_profile_{{post.id}}"> {{post.created_by.first_name}} {{post.created_by.last_name}} </span> </a> </span> <div id = "id_post_text_{{post.id}}"> {{post.content}} </div> <span class="details" id = "id_post_date_time_{{post.id}}"> {{post.creation_time}} </span> <br><label class = "comment">Comment: </label> <input type = 'text', id = "id_comment_input_text_{{post.id}}", class = "comment", name = "comment"> <button class = "comment", type = "submit", id = "id_comment_button_{{post.id}}", onclick = "addItem()" >Submit your comment</button> <span id="error" class="error"></span> {% for comment in post.test_set.all %} <li> {{comment.text}} </li> {% endfor %} </li> {% endfor %} </ol> -
What exactly does UpdateCacheMiddleware and FetchFromCacheMiddleware do?
I added these to my "settings.py" and Django seemed to cache every page. I wasn't expecting it to change the behaviour of the whole site. MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', (other middleware goes here) 'django.middleware.cache.FetchFromCacheMiddleware' ] This seems to happen on a view (every one) unless you override the behaviour by adding the never cache decorator for example. I guess that it is how it is supposed to work, right? from django.views.decorators.cache import never_cache @never_cache def fooView(request): return render(request, 'foo.html') If you put this decorator on every view that you didn't want to cache, then is that equivalent to not using this caching middleware and just putting a cache page decorator on all the other pages (the ones you do want to cache), or is there more to it? Using the caching middleware seems a bit drastic if you only need caching on a few pages. -
Django Admin model editor: grey out field if another boolean field is not checked
I have the following two fields in my Treatment Model: is_followup = models.BooleanField() parent_treatment = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) In the screen grab below from my admin page, I'd like to grey out "Parent treatment" if is followup is not checked. Is this possible? and if so, how to do it? -
Django request.POST QueryDict only returns true/on values from forms.booleanfield(required=False)
I am currently working on a Django admin action where you can create a model object from two or more already existing objects. Each object have an integerfield to store the current amount of items it has. When I'm using the action I want to be able to choose how many to take from each object and give to the new one. I also want to have an option to take all. Currently this is a simple Boolean checkbox field. My problem is, whenever i submit my form, where I for example only checked 2/4 checkboxes and two a number in the other two. The request.POST returns a QueryDict where the booleanfield called empty_field is like this: 'empty_field': ['on', 'on']. It doesn't account for False or 'off' which i need. The exact thing I am asking for, is how do I get the False/off values from request.POST? Thanks My views.py: def post(self, request, *args, **kwargs): form = MergeForm(data=request.POST) print(request.POST) My forms.py: class MergeForm(forms.ModelForm): batch_stock_choicefield = forms.IntegerField() empty_field = forms.BooleanField(required=False) class Meta: model = Batch fields = ['batch_stock_choicefield', 'empty_field'] My html div: <div> <form action="" method="POST"> {% csrf_token %} <table class="form-group"> <thead> <tr> <th>Batch id</th> <th>Stock item</th> <th>Quantity</th> <th>Take From Batch … -
Django read file from model, [Errno 2] No such file or directory
In Django I am using model forms to upload .stl file in model shown below. Once I submit form I see files get uploaded to myproject => media directory. But while reading uploaded file from the model, I am keep getting file not found error. I tried using both absolute and relative path without success, any help is much appreciated. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') model.py from django.db import models class StlFile(models.Model): uploaded_file = models.FileField() uploaded_at = models.DateTimeField(auto_now_add=True) volume = models.FloatField(default=0.0) forms.py from django import forms from .models import StlFile class StlForm(forms.ModelForm): class Meta: model = StlFile fields = [ 'uploaded_file' ] After POST request numpy stl reads saved stl file from the model in views.py. views.py import os from django.shortcuts import render import numpy as np from stl import mesh from .forms import StlForm from .models import StlFile # Create your views here. def model_form_upload(request): if request.method == 'POST': form = StlForm(request.POST, request.FILES) if form.is_valid(): stl_file = form.save(commit=False) # Read file but Don't save the file yet stl_file.uploaded_file = request.FILES['uploaded_file'] # Read file instance in model parameter stl_file.save() # Extract mechanical properties from STL stl_path = stl_file.uploaded_file.url stl_mesh = mesh.Mesh.from_file(stl_path) # Read saved file from the … -
Design Database Efficiently with several relations - Django (PostgreSQL)
I want to know the most efficient way for structuring and designing a database with several relations. I will explain my problem with a toy example which is scaled up in my current situation. Here are the Models in the Django database 1.) Employee Master (biggest table with several columns and rows) class Emp_Mast(): emp_mast_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) desgn_mast = models.ForeignKey("hr.Desgn_Mast", on_delete=models.SET_NULL, null=True) qual_mast = models.ForeignKey("hr.Qualification_Mast", on_delete=models.SET_NULL, null=True) office_mast = models.ManyToManyField("company_setup.Office_Mast", ref_mast = models.ForeignKey("hr.Reference_Mast", on_delete=models.SET_NULL, null=True) refernce_mast = models.ForeignKey("hr.Refernce_Mast", on_delete=models.SET_NULL, null=True) This is how the data is displayed in frontend 2.) All the relational field in the Employee Master have their corresponding models 3.) Crw_Movement_Transaction Now I need to create a table for Transaction Data that that stores each and every movement of the employees. We have several Offshore sites that the employees need to travel to and daily about 50 rows would be added to this Transaction Table called Crw_Movement_Transaction The Crw_Movement Table will have a few additional columns of calculations of itself and rest of the columns will be static (data would not be changed from here) and will be from the employee_master such as desgn_mast, souring_mast (so … -
Applozic Django Web Integration Unresponsive
My Current Goal Access the Applozic web demo through my application Final Goal Add a 1 to 1 chat to my Django web application using Applozic with the Fullview UI. Users are able to log-in to my website and chat with each other through the Fullview UI while still having the same navigation bar as my website and being on my website. Expected results Being able to open the demo through my application and send a test message Actual results When I open the demo through my application nothing happens when I press the Enter Chat button What I've tried Sample I downloaded the demo, started it and entered my applozic account information. The first box (that requires the application id) said 'applozic-sample-app', I left this as is. Next, I entered my Applozic email and password to log in, as seen below. [![enter image description here][1]][1] It worked and I was able to send messages to their sample account. [![enter image description here][2]][2] Initial Integration to Django Application Next I copied and pasted the fullview.html file into my django project's template directory, created a new view that shows that file, added the url to redirect to the view and started … -
Django next page and prvious page not working
In my Django admin the previous and next page button is not working.it always go to the else part of the code. I don't know what's the issue. On clicking it always go on the same page {% load admin_list %} {% load i18n %} {% if pagination_required %} <ul class="pagination"> {% if cl.has_previous %} <li><a href="?p={{ cl.previous_page_number }}">&laquo;</a></li> {% else %} <li class="active"><span>&laquo;</span></li> {% endif %} {% for i in cl.paginator.page_range %} {% if cl.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?p={{ i|add:"-1" }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if cl.has_next %} <li><a href="?p={{ cl.next_page_number }}">&raquo;</a></li> {% else %} <li class="active"><span>&raquo;</span></li> {% endif %} </ul> <p style="float:right; margin:10px;">{{ cl.paginator.count }} Projects</p> {% endif %} -
Django progressive web app gives an error in all browsers after caching files
I was following this tutorial to make my website a PWA website using django-progressive-web-app. However, when I opened the app from firefox I get the following error: Oops. The site at http://localhost:8000/ has experienced a network protocol violation that cannot be repaired. The page you are trying to view cannot be shown because an error in the data transmission was detected. Please contact the website owners to inform them of this problem. When I open from Safari I get this error: Safari Can't Open the Page SAfari can't open the page "http://localhost:8000/base_layout/". The error is: "Response served by service worker has redirections" (WebKitInternal:0) I don't have chrome so I can't tell what is the error there, also running it from private -Incognito- window would solve the problem (and clearing data) So the problem is clearly with the cached code How can i fix? My code settings.py: INSTALLED_APPS = [ ... 'pwa', ... ] ... # Pwa settings PWA_SERVICE_WORKER_PATH = os.path.join( BASE_DIR, 'static/chat/js', 'serviceworker.js') urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('webpush/', include('webpush.urls')), path('', chat_views.home, name="home"), path('', include('pwa.urls')), path('base_layout/', chat_views.base_layout, name="base_layout"), ... ] serviceworker.js (path: Orgachat/static/chat/js/serviceworker.js var staticCacheName = 'djangopwa-v1'; self.addEventListener('install', function (event) { event.waitUntil( caches.open(staticCacheName).then(function (cache) { return cache.addAll([ '/base_layout' ]); … -
django_hosts - NoReverseMatch: Reverse for 'home' not found. 'home' is not a valid view function or pattern name
Versions: Django 2.2.10 django-hosts 4.0 I have installed django_hosts successfully as per this documentation. I can successfully now access pages like https://blog.mysite.com However, the urls on the page are NOT resolved correctly. I have followed the example shown in the django_hosts official documentation. This is what my setup looks like: mysite/urls.py # imports etc. truncated for brevity # ... urlpatterns = [ path('', include(('home.urls', 'home'), namespace='home')), path('blog/', include('blog.urls', namespace="blog")), # ... ] home/urls.py from django.urls import path from django.conf.urls import include, url from .views import HomePageView, AboutView, TermsView, PrivacyView, \ sample, register, signin app_name = 'home' urlpatterns = [ path('', HomePageView.as_view(), name='index'), path('about', AboutView.as_view(), name='about'), path('terms', TermsView.as_view(), name='terms'), path('privacy', PrivacyView.as_view(), name='privacy'), path('sample', sample), path('register', register, name='register'), path('signin', signin, name='signin'), ] blog/templates/index.html <div class="container"> 116 <!-- Logo --> 117 <a class="logo" href="{% host_url 'home' host 'www' %}" style="text-decoration: none; font-size: 250%;"> 118 <img src="/static/assets/img/logo.png"> 119 My Site 120 </a> 121 <!-- End Logo --> -
AttributeError: module 'rest_framework.serializers' has no attribute 'serialize'
I am trying to serialize model instance as i can't reach out the url or the details of the 'followiing' model. from django.core import serializers from django.contrib.auth import authenticate from django.contrib.auth.models import update_last_login from rest_framework_jwt.settings import api_settings from django.core import serializers from rest_framework import serializers from urllib import request from rest_framework.permissions import AllowAny,IsAuthenticated from rest_framework import routers, serializers, viewsets from django.http import HttpResponse class UserSerializer(serializers.HyperlinkedModelSerializer): jsonfollowing = serializers.serialize('json', [ followiing ,]) class Meta: model = User fields = ('id','email','username','password','followiing','jsonfollowing') But i get the following error AttributeError: module 'rest_framework.serializers' has no attribute 'serialize' Does anybody know why? -
Django Data Migration
I want to write a data migration that read the records in the right order and delete the older records when the newer record was found I write the sql for this one. But I want to write data migration How can I write this my sql query is this ;with cte as ( select cid,count(*),max(id) as id from automation_irrig_record_data group by cid having count(*)>1 ) Delete from automation_irrig_record_data irrigRec where irrigRec.id in (select irrig.id from automation_irrig_record_data irrig JOIN cte on cte.cid=irrig.cid and cte.id !=irrig.id ) how can I write the Data migration my model name is automation_irrig_record_data id is my primary key cid is my field -
Create a user with a signal
I am trying to implement a signal to create a user when I create another model. When I create the sender object, the signal does not go through. Here is the code. from django.db.models.signals import post_save from django.dispatch import receiver from .models import Spender from django.contrib.auth.models import User @receiver(post_save, sender=Spender) def create_user(sender, instance, created, **kwargs): spender = Spender if created: User.objects.create( username=spender.spender_username, first_name=spender.spender_firstname, last_name=spender.spender_lastname, email=spender.spender_email, password1=spender.spender_password1, password2=spender.spender_password2, ) User.save() -
Best way to store thousands of different files in Django Rest Framework?
I have to create an app in my DRF project that will be used to store thousands of different files (mostly PDF an Excel). The app will allow the user simple ACL requests and simple standard functionalities of a repository (see Recent files, move to different folders..). I've always used the hard disk of the server to store files in Django (through static root), I would like to have some feedback for this situation. Is it better to save them as binary on a databse? what approach would you suggest? In case of an external storage, which one is more functional for my situation? Thank a lot for your answers :)