Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python was not found; can be installed from Microsoft store when python is already installed and present in the path
I tried running a Django app both from the VSCode terminal and cmd. But in both cases, I got the error that Python was not found. a) Python is already installed(3.9) & included in the path b) I didn't create a virtual environment c) got the same error when not using Django d) pip is working -
How to get the instance value of a field in a ModelForm?
I have a ModelForm where on first displaying the form, I want to disable one field based on the value of another: class MyForm(forms.ModelForm): field_1 = forms.BooleanField(default=False) field_2 = forms.CharField(default='mytext', required=True) I.e. if field_1 is False, then field_2 will have widget attr disabled. I know I can set the disabled attr on __init__ but how do I look up the value of field_1? E.g: class MyForm(forms.ModelForm): field_1 = forms.BooleanField(default=False) field_2 = forms.CharField(default='mytext', required=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) // If field_1 is False then: self.fields['field_2'].disabled = True I can get the initial value of field_1 with self.fields['field_2'].initial but I want the actual value of the instance. -
How to deal with migration files on docker
Wanted to know what is the proper way of dealing with migration files on djagno docker. Basically, whenever starting a new instance of my docker container, Im always having this error: File "/usr/local/lib/python3.8/site- packages/django/db/migrations/graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration authentication.0001_initial dependencies reference nonexistent parent node ('auth', '0012_userloginactivity') Which arises , i think because of the way my volume syncs up with my local file system.The error goes away when i delete all migration files in my local repo .Therefore how should i structure my project such that i won't encounter such problems in local and in production development? Here is the code to my docker-compose: version: "3.7" services: postgres: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=user - POSTGRES_DB=user networks: - main backend: build: ./backend ports: - "8000:8000" volumes: - ./backend/:/usr/src/backend/ command: python manage.py runserver 0.0.0.0:8000 env_file: - ./.env.dev image: backend-image depends_on: - postgres - redis networks: - main volumes: postgres_data: pgdata: redisdata: networks: main: Here is the docker-compose file for my production: version: "3.7" services: postgres: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=user - POSTGRES_DB=user networks: - main backend: build: ./backend volumes: - static_data:/vol/web/static - media_data:/vol/web/media env_file: - ./.env.dev … -
How do I keep checkbox value checked in django?
Here is models.py class project(models.Model): project_name = models.CharField(max_length = 20) date = models.DateField(("Date"), default=datetime.date.today) user = models.ForeignKey(User, on_delete=models.CASCADE) class check_done(models.Model): checked_value = models.CharField(max_length = 200) current_project = models.ForeignKey(project, on_delete=models.CASCADE) Here is views.py def show(request): log_user = request.user projects = project.objects.filter(user=log_user) return render(request, 'project.html',{'user_project_list':projects}) def checklist(request, project_id): if request.method == "POST": try: current_project = check_done.objects.get(current_project_id = project_id) except: savedata = check_done() savedata.current_project = project.objects.get(id = project_id) savedata.checked_value = request.POST.get('checked_values') savedata.save() return render(request, 'checklist.html') current_project.checked_value = request.POST.get('checked_values') current_project.save() return render(request, 'checklist.html') else: return render(request, 'checklist.html') Here is checklist.html <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function() { $('.chkcvalues').click(function() { var txt = ""; $('.chkcvalues:checked').each(function() { txt+=$(this).val()+"," }); txt =txt.substring(0,txt.length-1); $('#txtvalues').val(txt); }); }); </script> <style> .pcbcheck { width: 800px; margin: auto; text-align: center; } .save { background-color: gray; display: block; margin: 20px 0px 0px 20px; text-align: center; border-radius: 12px; border: 2px solid #366479; padding: 14px 110px; ouline: none; color: white; cursor: pointer; transition: 0.25px; } button:hover { background-color: #4090F5; } .HomeLblPos { position: fixed; right: 10px; top: 25px; cursor: pointer; } </style> </head> <body> <div class="pcbcheck"><h1 style="color:black;font-size:35px;"> PCB Checks</h1></div> <form align="right" method="get"> {% csrf_token %} <label class="HomeLblPos"> <a class="waves-effect waves-light btn green" href="{% url 'show' %}">Home</a> </label> </form> <div class="main"> <form method="POST"> {% … -
Django performance monitoring on AWS
I have a Django app hosted on AWS Lambda (deployed using Zappa tool) an using RDS for hosting the Postgres database. The app is having performance issues with some pages loading very slowly but not others, making me think that the issue is with poorly written data interactions. I remember at work, the devs were using Azure Application Insights which was monitoring apps at a code level. I think the devs had to insert code throughout their apps to get the monitoring, and I think it monitored on a page by page and code line by line basis. Is there any similar tool on AWS which I could use with my App? I appreciate there are much simpler ways of solving my problem but I thought an AWS tool would be something neat to learn. -
How to query for images efficiently from another referencing model in Django
I have these two Django models: class Product(models.Model): name=models.CharField(max_length=300) description=models.CharField(max_length=10000) class Thumnbnail(models.Model): thumnbnail=models.ImageField(null=True) product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE) For an eCommerce website, I want to show list of products, and their multiple thumbnails (a product might have more than one thumbnail!), filtered by product names with a keyword from user input. What is the most efficient way to retrieve all the products and their thumbnails, without querying twice separately for the products and for the thumbnails? I know that using .select_related() we can fetch the foreign objects as well, but it's like I am still missing something. I can either make two separate Serializers, and separate querysets in two Viewsets, in which case I have to do the keyword-name filtering twice, and it definitely doesn't make sense to do it twice, or another way is to make a nested Serializer, with fields from both models, but that is also not a good idea, since the product description will be repeated again and again in every row for every thumbnail that the product has. Omitting the product description field from serializer is also not an option, since I do need to get it at least once. Doesn't make sense to perform another query … -
Django Lightsail - attempt to write a readonly database
for a few days now I have been trying to deploy my Djago app on AWS Lightsail, and it's just one problem after another. The frustration levels are over the roof. This time, when I try to login/register, I am getting this error: Attempt to write a readonly database I have been googling solutions for quite some time and have tried setting different permissions, even giving away all permissions which might be huge security risk, however it still doesn't work. Could anyone help me. Thank you -
Django Rest Framework: how to access single API elements in URL?
I want to access every API element by URL like this "/api/v1/element_id" I have explicitly defined the pk in serializers serializers.py class TweetSerializer(serializers.ModelSerializer): tweet_id = serializers.IntegerField() class Meta: fields = ('tweet_id', 'author', 'text', 'created_at', 'retweet_count', 'favourite_count',) model = Tweet But it does not work. I get Not found error models.py class Tweet(models.Model): #tweet_id = models.ForeignKey(User, on_delete=models.CASCADE) tweet_id = models.IntegerField() created_at = models.CharField(max_length=100) text = models.TextField() author = models.CharField(max_length=100) retweet_count = models.IntegerField() favourite_count = models.IntegerField() def __str__(self): return str(self.tweet_id) views.py class TweetList(generics.ListCreateAPIView): queryset = Tweet.objects.all() serializer_class = TweetSerializer class TweetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Tweet.objects.all() serializer_class = TweetSerializer urls.py urlpatterns = [ path('<int:pk>/', TweetDetail.as_view()), path('', TweetList.as_view()), ] Listing all tweets works fine, /api/v1/, but single tweet is not returned. I have tried to set a ForeignKey in the models but then I get an error column tweet_id_id not found. -
Django FileField and Media config
I'm completely stuck with this, I have a simple Model with a File-Field: class EmailTemplate(models.Model): template_name = models.CharField(max_length=100, primary_key=True, verbose_name='Template Name') template_file = models.FileField(upload_to=f'documents/non_voice/email_templates', verbose_name='File', validators=[validate_txt_extension]) def __str__(self): return self.template_name The User is able to upload a file through a form and should be able to download them as reference later on. Upload works like a charm but when I present the file in a django_table - Table it links to it's relative path and download won't work since it tries to serve only the partial file path. Shouldn't Django automatically pre-pend my Media Dir to build the correct path?? (I can't provide a full path as "upload_to" only accepts relative ones!) Also the standard upload widget is showing it's current path as a link which is also not working when you click on it, so I would assume the issue has to be somewhere else (best guess is my media settings...) My Media Settings look like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') LOG_DIR = os.path.join(BASE_DIR, 'logs') # MEDIA MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' Any ideas? -
Tus JS Client file upload without CSRF in Django
I want to upload a large video file using tus-js-client to my django media directory. I am encountering a csrf token 403 error. How can I the crsf token to the tus POST and PUT/PATCH requests. See my code below let video_file = $('#id_video_file')[0].files[0]; let tus_uploader = new tus.Upload(video_file, { endpoint: 'http://127.0.0.1:8000/media/myfolder/', retryDelays: [0, 1000, 3000, 5000, 10000], metadata:{ filename: video_file.name, filetype: video_file.type, }, uploadSize: video_file.size, onError: function (error) { }, onProgress: function (bytesUploaded, bytesTotal) { let percentage = (bytesUploaded/bytesTotal * 100).toFixed(2); console.log(percentage); }, onSuccess: function () { console.log("Download %s from %s", tus_uploader.file.name, tus_uploader.url) } }); tus_uploader.start(); -
How do I use django formset_factories?
I am trying to work on a django-based project/website that logs who took out our dogs last. I am very new to django so please bear with lack of knowledge in the field. I currently have my project set up so that I have models based on users/family members, the families' dogs, posts (logs of when and who took out the dogs), and actions, which is a child class that uses the dog and post models as foreign keys to see if the dogs peed and or pooped when they were taken out. The part that I am stuck on is trying to figure out how I create the post form. Since we have two dogs I need the form/post page to display a set of check boxes (for peeing and pooping actions) for each dog model that exists. While I can successfully display one action set, I run into the difficulty of trying to display the correct number of action sets and also to post the set of actions and the post itself. I have been trying to work with the formset_factory function but I am confused as to how I get it to function properly. Can anyone help? … -
temporarily adding watermark image/copyright text while displaying image in django template
I am creating a stock photo site. I need to add watermark temporarily while displaying in django template so that user shouldn't be able to download original photo without purchasing. I've tried django-watermark but got error while migrating. python 3.8+ and django 3.1.3+ So far I've overlapped images using this code, water_mark_image = Image.open(settings.MEDIA_ROOT+'/water.png') water_mark_image = wat.resize((int(im.width/2), int((im.width/2)*(h/w)))) Original_image.paste(wat, (int((im.width-wat.width)/2), int((im.height-wat.height)/1)), mask=wat) but while downloading image comes along with watermark. I dont want to save duplicate image. Please suggest me a way to add watermark temporarily while displaying in detail. -
How to add header to JSONresponce?
In my Angular/Django project I need to make query from angular frontend to the server. In response Django send me JSON data of that user of message that user does not exist. First query(option) has response code 200. Second part(exactly POST) throws CORS error. I think I need add it to response header, but I can't find something about adding header in JSONResponce. Please help me with that My Django code from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponse from django.http.response import JsonResponse from django.utils.decorators import method_decorator from django.views import View from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from .models import User from .serializers import UserSerializer class UserView(View): allowed_methods = ["options", "get", "put", "post", "delete"] @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(UserView, self).dispatch(request, *args, **kwargs) def options(self, request, email=""): response = HttpResponse() response["Access-Control-Allow-Origin"] = '*' response["Access-Control-Allow-Headers"] = "Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Headers" response["Content-Type"] = 'application/json' response["allow"] = ",".join(self.allowed_methods) return response def get(self, request, email=""): users = User.objects.all() users_serializer = UserSerializer(users, many=True) return JsonResponse(users_serializer.data, safe=False) def put(self, request, email=""): user_data = JSONParser().parse(request) user = User.objects.get(email=user_data["email"]) # щоб знати конкретного юзера, інфу якого змінюватимемо user_serializer = UserSerializer(user, data=user_data) if user_serializer.is_valid(): user_serializer.save() return JsonResponse("User information was updated successfully", safe=False) else: return JsonResponse("Failed to … -
InvalidTemplateEngineError in oscar
I am using django-oscar for my development. I have created a new app as per my requirement views.py class MediaImportView(TemplateView): template_name = 'lookup/import_media_file.html' def get(self, request): ctx = {} return render(self.template_name, ctx, request, using=request) getting the error as below. InvalidTemplateEngineError at /import_media_file Could not find config for '<WSGIRequest: GET '/import_media_file'>' in settings.TEMPLATES -
Problems with the integration of Django 3 and Vue 3
I have been trying to integrate Django 3 with Vue 3 for two days and I have partly succeeded but not as I would like. Stage. The idea is to use Vue 3 for components that require Javascript and are not important for SEO like booking forms, etc … Integrate by using django-webpack-loader to inject the bundle into django templates. const BundleTracker = require("webpack-bundle-tracker"); module.exports = { publicPath: "http://0.0.0.0:8080/", outputDir: './dist/', pages: { main: { // entry for the page entry: 'src/main.js', } }, chainWebpack: config => { config.optimization .splitChunks(false) config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.resolve.alias .set('__STATIC__', 'public') config.devServer .public('http://0.0.0.0:8080') .host('0.0.0.0') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .headers({"Access-Control-Allow-Origin": ["\*"]}) } }; This is the content of the ** main.js ** that is the entry point of the Vue3 app import { createApp, reactive, ref } from ‘vue’ const app = createApp({ el: ‘#app’, delimiters: [’[[’, ‘]]’], setup() { const data = { returned_task: ref(''), temp_task: ref(''), modify_index: ref(-1), tasks: reactive([]), } const methods = { select: (index) => { if (data.modify_index.value === index){ data.modify_index.value = -1; } else { data.modify_index.value = index data.temp_task.value = data.tasks[data.modify_index.value] } }, deleteSelected: () => { data.tasks.splice(data.modify_index.value, 1); data.modify_index.value = -1; }, updateSelected: () => { … -
Inheritance in classes django
I am currently working on my first website and I'm working with class-based views because I've been told their inheritance is outstanding. Here's the code so you can make yourselves an idea of what I'm trying to do before I tell you the error I'm having. class TranslatorView(View): def translate_amino(self, codon): return self.amino_mapper.get(codon, "") def build_protein(self, phrase): protein = [] i = 0 while i < len(phrase): codon = phrase[i: i + 3] amino = self.translate_amino(codon) if amino: protein.append(amino) else: print(f"The codon {codon} is not in self.mapper_1") i += 3 return protein def error_1(self, request): amino_1= self.build_protein(request.GET.get('phrase','')) if len(amino_1) % 3: messages.error(request, "DNA chain must be divisible by 3") return redirect('/') Basically, what I'm trying to do is to inherit the function build_protein to the def error_1. That's why I create a variable called amino_1 equal to the def build_protein. Afterwards, I create a condition saying if amino_1 detects a phrase that it's a total number of letters aren't divisible by three, it should raise a value error. However, it appears it's not inheriting anything at all. -
DJANGO: How to specify primary key in fixture when the primary key is not "id"
I just changed my pk name in a model. This is how my model was: class Course(LogsMixin, models.Model): """Definición del modelo de Proveedor.""" name = models.CharField("Nombre del curso", null=False, default="", max_length=200) code = models.CharField("Código del curso", null=False, default="", max_length=50) hours = models.IntegerField(("Número de horas"), null=False, default=0) price = models.DecimalField(("Precio"), max_digits=6, decimal_places=2, null=False, default=0) provider = models.ForeignKey(Provider, verbose_name=("Proveedor"), null=True, default=None, on_delete=models.SET_DEFAULT) active = models.BooleanField("Activo", default=True) As you can see I didnt specified the PK but I changed that: class Course(LogsMixin, models.Model): """Definición del modelo de Proveedor.""" reference = models.CharField("Referencia", primary_key=True, null=False, default="", max_length=50) name = models.CharField("Nombre del curso", null=False, default="", max_length=200) code = models.CharField("Código del curso", null=False, default="", max_length=50) hours = models.IntegerField(("Número de horas"), null=False, default=0) price = models.DecimalField(("Precio"), max_digits=6, decimal_places=2, null=False, default=0) provider = models.ForeignKey(Provider, verbose_name=("Proveedor"), null=True, default=None, on_delete=models.SET_DEFAULT) active = models.BooleanField("Activo", default=True) As you can see now "reference" is my pk but when I try to install this fixture: [{ "models": "consumptions.course", "pk": "AD_ADGD008PO", "fields": { "name": "ANÁLISIS DE PROBLEMAS Y TOMA DE DECISIONES", "code": "ADGD008PO", "price": "21.00", "hours": "30", "provider": "P000019", "active": true } }, I receive the next error: Traceback (most recent call last): File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\serializers\json.py", line 69, in Deserializer yield from PythonDeserializer(objects, **options) File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\serializers\python.py", line … -
Django - How to take string values on URL for PUT?
I set up my URL like this : path('voucher/<str:voucher_id>', views.update_voucher), My process def update_voucher(request, voucher_id): put = QueryDict(request.body) try: customer_id = put.get('customer_id') except: return HttpResponse("Missing parameters") updateVoucher = Voucher.objects.filter(code = voucher_id) Its a PUT call taking parameters from both body and url. (voucher_id from URL) and (customer_id from body) . I call this URL http://127.0.0.1:5448/voucher/NewVoucher I got this error: ValueError: Field 'id' expected a number but got 'NewVoucher'. The below is my model: here. class Voucher(models.Model): code = models.CharField(unique=True, max_length=255) delivery_type = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True, null=True) start_at = models.DateTimeField() end_at = models.DateTimeField() discount_type = models.CharField(max_length=255) discount_amount = models.FloatField(blank=True, null=True) P/S: I am a maintainer - cant change method function, and cant change the way this URL take parameters from both URL and body -
How to make a form with choice fields which lead to different ModelForms based on the selected item
I have two models which are very similar.For each model I just defined a different ModelForm. I am going to make a form wizard with different steps, which in the first step choose which modelform I prefer, X or Y like: step one: forms.Form (choices: ModelForm X or ModelForm Y) step two: field_A in ModelForm X step three: field_B in ModelForm X step four: field_A in ModelForm Y step five: field_B in ModelForm Y step six: submit If X is selected skips form steps related to modelform Y(Four and Five) and submit them in database table X, and vice versa. So, I am asking if you have any experience in merging two modelforms and make choice/skip steps using a seprate form which is joined as the first step of my wizard form? -
Extracting data using ajax from a database in django and then display it in view
How should I extract data from a database using ajax in Django and display it in view in the form of charts. I wanna select items from dropdown options and then display those selected data in the webpage in the form of charts. Can anyone please guide me in this. My codes are: index.html: <div class="row"> <form class="form-row" action="{{ }}" method="post"> {% csrf_token %} <div class="form-group col-md-2"> <select class="form-control select2" > <option>Select Major Head</option> {% for major in majors %} <option value="{{ major.pk }}">{{ major.pk }}: {{ major.description } </option> {% endfor %} </select> </div> <div class="form-group col-md-2"> <input type="submit" value="Display"> </div> </form> </div> . . . <div class="card-body" > <div id="chart"> <embed type="image/svg+xml" src= {{ chart|safe }} /> </div> views.py: def home(request): majors = Major.objects.filter(percentages__isnull=False).distinct().order_by("pk") if request.method == 'POST': form = request.POST.get('be_nextyr_total') line_chart = pygal.Line(width=1500) line_chart.title = 'Budget Estimation' context = { "chart": line_chart.render_data_uri(), 'majors': majors } return render(request, "website/index.html" , context ) charts.js $('form').on('Display',function(e){ e.preventDefault(); $.ajax({ type : "POST", cache : false, url : $(this).attr('action'), data : $(this).serialize(), success : function(data) { // $(".printArea").empty().append(data).css('visibility','visible'); return data; } }); }); -
How create form Html in Django_rest_framework?
My Views is : class TweetsListApiView(generics.ListCreateAPIView): queryset = Tweet.objects.all() serializer_class = TweetListSerializer renderer_classes = [TemplateHTMLRenderer] template_name = 'components/form.html' Serializers: class TweetListSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField('get_likes') class Meta: model = Tweet fields = ['id','content','likes'] def get_likes(self,request): return random.randint(0,9999) from.html {% load rest_framework %} <form method='Post'> {% csrf_token %} {% render_form serializer %} <button type="submit" class="btn btn-secondary">Add</button> </form> urls.py: path('tweets/',TweetsListApiView.as_view()), Is it possible to have from one viewclass class TweetsListApiView standart Rest Page and HTML page where I creating new Tweet. if no what the best way to create this html using serializer and Django REST -
Fashion MNIST dataset Deploy using Streamlit
please do anyone have link where I can learn proper way to deploy mnist fashion classification(the deployment that works perfectly) using streamlit library? Or flask or django? Your quick guide will be highly appreciated. -
Django create ManytoOne relation in one form
I am trying to develop a form where the user would be able to achieve this : Database So the form would have : a TextField for the name a TextField for the description a TextField for the addresses that would be entered by the User as a list According to you, what would be the most appropriate approach to do so? Thank you very much ! -
Django full_clean method and data security
I need to take raw JSON data and put it direct into a Django model by using the Mymodel.objects.create( ... ) method. If I then run full_clean() on the instance created, is it then secure in terms of potential SQL injection or any malicious data that could potentially be injected? The reason that I am not using a form is that the logic on the form is quite complex in that it dynamically builds a form so I need to post data in json format. I don't want to use the rest api as there is just one page where it has this complexity. -
I'm facing a problem in postgresql 13 installation on windows 10
Is there any solution ??enter image description here