Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Making all fields in the model formset required in HTML - Django
I have looked at pretty much all questions on Stack Overflow relating to Django Formsets. None of them answer my question in a realistic manner. I have a page that uses an inlineformset_factory. The goal is to have parents add their information and then their students information. I need ALL of the student fields to be required in HTML. So far, only the parent information has the required attribute in HTML. The number of students is passed in as part of the url - example.com/register/3 would be if a parent has 3 students to register. So, if a parent chooses 3 students on the previous page, they would be sent to example.com/register/3 and it would show the parent form with the 3 student forms. THIS IS WORKING. What is not working is making ALL three of the student forms required in the HTML. My view: def homeschoolRegister(request, num): parent_form = ParentInformationForm() StudentFormSet = inlineformset_factory(ParentInformation, StudentInformation, fields=('student_first_name', 'student_last_name', 'grade'), can_delete=False, extra=int(num)) if request.method == 'POST': parent_form_post = ParentInformationForm(request.POST) if parent_form_post.is_valid(): parent = parent_form_post.save(commit=False) parent.save() student_form_post = StudentFormSet(request.POST, instance=parent) if student_form_post.is_valid(): student_form_post.save() try: if int(num) <= 0: return redirect(reverse('home')) if int(num) > 15: return redirect(reverse('home')) context = {'parent_form':parent_form ,'formset':StudentFormSet} return render(request, 'home/home-register.html', … -
Django and uvicorn throwing `closing handshake failed` errors on page load
I am trying to follow some tutorials to set up a Django server on Heroku and add websockets to pass information to and from my front end pages. I think I did everything correctly, however I am getting the following errors when my websocket on the page tries to connect: 5:06:07 PM web.1 | [2021-10-26 21:06:07 +0000] [36593] [ERROR] Exception in ASGI application 5:06:07 PM web.1 | Traceback (most recent call last): 5:06:07 PM web.1 | File "/Users/bslaght/Library/Python/3.8/lib/python/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 203, in run_asgi 5:06:07 PM web.1 | result = await self.app(self.scope, self.asgi_receive, self.asgi_send) 5:06:07 PM web.1 | File "/Users/bslaght/Library/Python/3.8/lib/python/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__ 5:06:07 PM web.1 | return await self.app(scope, receive, send) 5:06:07 PM web.1 | File "/Users/bslaght/Library/Python/3.8/lib/python/site-packages/channels/routing.py", line 74, in __call__ 5:06:07 PM web.1 | raise ValueError( 5:06:07 PM web.1 | ValueError: No application configured for scope type 'websocket' 5:06:07 PM web.1 | [2021-10-26 21:06:07 +0000] [36593] [INFO] connection open 5:06:07 PM web.1 | [2021-10-26 21:06:07 +0000] [36593] [ERROR] closing handshake failed 5:06:07 PM web.1 | Traceback (most recent call last): 5:06:07 PM web.1 | File "/Users/bslaght/Library/Python/3.8/lib/python/site-packages/websockets/legacy/server.py", line 232, in handler 5:06:07 PM web.1 | await self.close() 5:06:07 PM web.1 | File "/Users/bslaght/Library/Python/3.8/lib/python/site-packages/websockets/legacy/protocol.py", line 779, in close 5:06:07 PM web.1 … -
NoReverseMatch at... (Django)
Getting error: Reverse for 'topping' with arguments '('',)' not found. 1 pattern(s) tried: ['topping/(?P<toppings_id>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/pizzas/ Django Version: 3.2.8 Exception Type: NoReverseMatch Exception Value: Reverse for 'topping' with arguments '('',)' not found. 1 pattern(s) tried: ['topping/(?P<toppings_id>[0-9]+)/$'] admin.py: from django.contrib import admin from .models import Pizzas, Toppings admin.site.register(Pizzas) admin.site.register(Toppings) models.py: from django.db import models class Pizzas(models.Model): """A Pizza for the menu.""" pizza = models.TextField() def __str__(self): """Return string of model.""" return self.pizza class Toppings(models.Model): """A topping for each pizza.""" pizza = models.ForeignKey(Pizzas, on_delete=models.CASCADE) topping = models.TextField() class Meta: verbose_name_plural = 'toppings' def __str__(self): return f"{self.topping}" views.py: from django.shortcuts import render from .models import Pizzas def index(request): """The home page for pizzeria.""" return render(request, 'pizzas/index.html') def pizzas(request): """Show all pizzas.""" pizzas = Pizzas.objects.all() context = {'pizzas': pizzas} return render(request, 'pizzas/pizzas.html', context) def topping(request, toppings_id): """Show each topping for a pizza.""" pizzas = Pizzas.objects.get(id=toppings_id) toppings = pizzas.topping_set.all() context = {'pizzas': pizzas, 'toppings': toppings} return render(request, 'pizzas/toppings.html', context) project urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('pizzas.urls')), ] app urls.py: from django.urls import path from . import views app_name = 'pizzas' urlpatterns = [ # Home page path('', views.index, name='index'), # Pizza menu path('pizzas/', views.pizzas, name='pizzas'), # Detail page for … -
Implementing SSE with DJANGO and REACT
I'd like to send the log of operations happening on the server to the client, but I'm not sure how. I'm trying to use django channels, but I'm having a hard time detecting DB changes. -
How to fix TemplateDoesNotExist Error on Windows10?
I have been following the tutorial for [Writing your first Django app][1] In part 3, I was trying to use a template. I am working with Python 3.1, Django 3.2 on a Windows10. Below is the error that I get: Django tried loading these templates, in this order: Using engine django: - django.template.loaders.app_directories.Loader: C:\Users\KKK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\admin\templates\polls\index.html (Source does not exist) - django.template.loaders.app_directories.Loader: C:\Users\KKK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\auth\templates\polls\index.html (Source does not exist) Below is my file structure: mysite +-- mysite | +--settings.py | +--other files +-- polls | +--templates | | +--polls | | | +--index.html | +--views.py | +--other files +-- db.sqlite3 +-- manage.py` I added a reference to polls configuration class in the INSTALLED_APPS setting. INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Any help would be appreciated. -
Django post_migrate signal been called multiple times
I have created a post_migrate with the goal to sync all the data inside the table whenever a migration runs. This is the snippet of the post_migrate file: # signals.py @receiver(post_migrate) def full_sync_if_model_change(plan, **kwargs): if plan: models_set = set() for file, _ in plan: for model in file.operations: try: model = SyncModel.objects.get( app_name=file.app_label, model_name=model.model_name ) models_set.add(model) except ObjectDoesNotExist: pass print(models_set) if models_set: for model in models_set: model.set_full_sync() run_update_sync(model, False) return However, when I run a migration, it is called 6 times; as you can see in the output of migration: evandro@evandro-340XAA-350XAA-550XAA:~/Desktop/.../test_service$ python3 manage.py migrateOperations to perform: Apply all migrations: admin, auth, contenttypes, django_cron, lakehouse_sync, sessions, test_models Running migrations: Applying test_models.0019_auto_20211026_2052... OK set() set() set() set() set() set() I'll add here also the apps file: class LakeSyncConfig(AppConfig): name = "lake_sync" def ready(self): """Import signals""" import lakehouse_sync.core.delete_action from . import signals I have no idea what to do, I tried to add this return statement, but it doesn't work, because the function is called all the time. -
django form input not showing on frontend/html
so I'm working with django forms to create a software for an ice cream company and I'm having trouble with my django forms to show up on the front end of my website. I was able to have customer information show up but the customer's order won't show and I am confused what's going on. orderentry.html <!--Basic Customer Information--> <form method = "post"> {% csrf_token %} {{ form.as_p }} {{ newOrder}} <button type = "submit">Place your order!</button> </form> views.py from django.http.response import HttpResponseRedirect from django.shortcuts import render, redirect from django.http import HttpResponse import orderentry from orderentry.forms import customerForm, customerInformation def getCustomerInfo(request): form = customerForm(request.POST) if request.method == 'POST': if form.is_valid(): form.save() orderentry.forms.customer_first_name = form.cleaned_data['customer_first_name'] orderentry.forms.customer_last_name = form.cleaned_data['customer_last_name'] orderentry.forms.shipping_address = form.cleaned_data['shipping_address'] orderentry.forms.billing_address = form.cleaned_data['billing_address'] return redirect('/orderentry') else: form=customerForm() return render(request, 'orderentry.html', {'form' : form}) def getCustomerOrder(request): newOrder = customerInformation(request.POST) if request.method == 'POST': if newOrder.is_valid(): newOrder.save() #orderentry.forms.order_Item_Flavor = newOrder.cleaned_data['order_Item_Flavor'] orderentry.forms.half_Pint_Count = newOrder.cleaned_data['half_Pint_Count'] orderentry.forms.one_Quart_Count = newOrder.cleaned_data['one_Quart_Count'] orderentry.forms.pint_Count = newOrder.cleaned_data['pint_Count'] orderentry.forms.half_Gallon_Count = newOrder.cleaned_data['half_Gallon_Count'] orderentry.forms.gallon_Count = newOrder.cleaned_data['gallon_Count'] orderentry.forms.cost = newOrder.cleaned_data['cost'] return redirect('/orderentry') else: print("error") else: newOrder=customerInformation() return render(request, 'orderentry.html', {'newOrder' : newOrder}) forms.py from django import forms from django.forms import ModelForm from orderentry.models import customerInfo, orderInfo class customerForm(forms.ModelForm): customer_first_name = forms.CharField(max_length=30) customer_last_name = forms.CharField(max_length=30) … -
change rendered form html in views django rest-framework
Hi i don't know react yet so i create panels using DRF with swagger and html render using Serializer and in serializer i need data token but in login panel i don't need. I want change it but in views but i dont know now how change meta data in create field: in if request.accepted_renderer.format == 'html': my views: class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer style = {'template_pack': 'rest_framework/vertical/'} template_name = "accounts/login_panel.html" def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] if user is not None and user.tokens is not None: login(request, user) return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get_queryset(self): if self.request is None: return CreateUser.objects.none() return CreateUser.objects.all() def get(self, request): serializer = LoginSerializer() if request.accepted_renderer.format == 'html': return Response( {'serializer': serializer, 'style': self.style, 'messages': 'Logging'}, template_name=self.template_name) elif request.accepted_renderer.format == 'json': new_data = { 'messages': 'Logged in successfully' } new_data.update(serializer.data) return Response(new_data, status=status.HTTP_200_OK) else: return Response({'error': 'Invalid format'}, status=status.HTTP_400_BAD_REQUEST) -
How to send selected files in DJANGO
if (window.FileList && window.File && window.FileReader) { document.getElementById('file-selector').addEventListener('change', event => { console.log(window.FileList, window.File, window.FileReader) // output.src = ''; status.textContent = ''; const file = event.target.files[0]; const size = event.target.files[0].size / 1e+6 var name = event.target.files[0].name; var file_html = `<div class="col-6"> <div class="d-flex border file-upload-box p-3"> <div class="col-10 info d-flex flex-column justify-content-center"> <h3 class="size-10 font-weight-500">${name}</h3> <p class="text-label size-10 m-0">${size}MB</p> </div> <div class="col-2 close d-flex align-items-center"> <i class="fas fa-times bg-gray" role="button" onclick="removeFile(this)"></i> </div> </div> </div> `; document.getElementById('files').innerHTML += file_html; if (!file.type) { status.textContent = 'Error: The File.type property does not appear to be supported on this browser.'; return; } if (!file.type.match('text.*|image.*|application.*')) { status.textContent = 'Error: The selected file does not appear to be an image.' return; } const reader = new FileReader(); reader.addEventListener('load', event => { // output.src = event.target.result; }); reader.readAsDataURL(file); }); } <form method="POST" enctype="multipart/form-data" id="accept-offer-form"> <input type="file" id="file-selector" /> <div class="files"></div> </form> This is working, but how can I send this files using javascript. I'm trying to do this document.getElementById("accept-offer-form").addEventListener("submit", function (e) { let form = $("form");.serialize(); $.ajax({ url: window.location.origin + "/maca/macaok/" + maca_id + "/accept-maca/", success: function (response) { window.location.href = response.url }, error: function (err) {} }); }) I want to accept files in views.py as request.FILES … -
Deploy django app from gitlab ci/cd to heroku
I'm trying to deploy a django web app to heroku from gitlab ci/cd pipeline. Here's my the deploy part of my .yml deploy: type: deploy script: - apt-get update -qy - apt-get install -y ruby-dev - gem install dpl - dpl --provider=heroku --app=$HEROKU_APP_NAME --api-key=$HEROKU_API_SECRET_KEY only: - main And here's the pipeline error: Deploying application uploading application archive triggering new deployment -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app -----> Python app detected -----> Using Python version specified in runtime.txt Traceback (most recent call last): File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> r = f.read().strip() File "/usr/lib/python3.8/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 5: warning: command substitution: ignored null byte in input ) is not available for this stack (heroku-20). It laments about an encoding error... I'm a bit lost -
Django Static url not working with {% static %}
I have my static files being stored in DigitalOcean CDN. I have multiple spaces 1 for clients and 1 for static assets and I use django-storages. Here is my config: AWS_S3_REGION_NAME = 'nyc3' AWS_S3_ENDPOINT_URL = f'https://{AWS_S3_REGION_NAME}.digitaloceanspaces.com' AWS_DEFAULT_ACL = 'private' AWS_DEFAULT_BUCKET = 'exactestate-staging' AWS_RESOURCE = session.resource('s3', region_name=AWS_S3_REGION_NAME, endpoint_url=AWS_S3_ENDPOINT_URL, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) AWS_CLIENT = boto3.client('s3', region_name=AWS_S3_REGION_NAME, endpoint_url=AWS_S3_ENDPOINT_URL, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) # Django’s STATIC_URL must end in a slash and the AWS_S3_CUSTOM_DOMAIN must not. It is best to set this variable independently of STATIC_URL. AWS_S3_CUSTOM_DOMAIN = f'{AWS_DEFAULT_BUCKET}.{AWS_S3_REGION_NAME}.digitaloceanspaces.com' STATIC_URL = f'https://{AWS_DEFAULT_BUCKET}.{AWS_S3_REGION_NAME}.digitaloceanspaces.com/static/' STATICFILES_STORAGE = 'storage_backends.StaticStorage' For some reason if I do not have: AWS_S3_CUSTOM_DOMAIN = f'{AWS_DEFAULT_BUCKET}.{AWS_S3_REGION_NAME}.digitaloceanspaces.com' set, my {% static %} tag uses the AWS_S3_ENDPOINT_URL as the value...but I need it to use what I set for AWS_S3_CUSTOM_DOMAIN. Normally setting AWS_S3_CUSTOM_DOMAIN would be fine but now all file.url calls also go to static instead of my client space...how can I fix this? -
How to get the value of input on button click in django
I have a django template as follows <table class="table"> <thead> <tr> <th>#</th> <th>Master Title</th> <th>Retailer title</th> <th>To add</th> </tr> </thead> <tbody> {% if d %} {% for i in d %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{i.col1}}</td> <td>{{i.col2}}</td> <td> <input type="hidden" name='row_value' value="{{i.col1}}|{{i.col2}}"> <a class='btn btn-success' href="{% url 'match' %}">Match</a> <a class='btn btn-outline-danger' href="{% url 'mismatch' %}">Not a Match</a> </td> </tr> {% endfor %} {% endif %} </tbody> </table> When the match button is clicked, I want to retireve the value of the hidden input in the views. Here is my views.py def match(request): print(request.GET.get('row_value')) print('match') But this returns None. I want the values of col1 and col2 to be printed as follows col1|col2 I am not sure where I am going wrong. -
serializer_action_class not working in modelviewset in DRF
I am trying to make serializer class dynamic, but its not working. I have a default serializer class where as a dynamic serializer class for different actions. Here it is my modelviewset. My view: class ClassView(viewsets.ModelViewSet): queryset = Class.objects.all() serializer_class = ClassSerializer serializer_action_classes = { 'put': AddStudentstoClassSerializer, } def get_serializer_class(self): """ returns a serializer class based on the http method """ try: return self.serializer_action_classes[self.action] except (KeyError, AttributeError): print("iam ClassSerializer") return super(ClassView, self).get_serializer_class() My function inside the same modelviewset above @action(detail=True, methods=['put']) def add_remove_students(self, request, *args, **kwargs): ................ MY url is as below: urlpatterns = [ path("class/<int:pk>/<slug:slug>/",views.ClassView.as_view({"put": "add_remove_students"}), ), ] Here in the above code snippet, I try to get AddStudentstoClassSerializer inside the add_remove_students function but it is not working. As we can see the print("iam ClassSerializer") code is working, however what i wanted or AddStudentstoClassSerializer. -
Django limit next post and previos post on Detail view to only active
I currently have a model view as such from django.db import models from django.contrib.auth.models import User from django.utils import timezone STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="blog_posts" ) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ["-created_on"] def __str__(self): return self.title def get_absolute_url(self): from django.urls import reverse return reverse("post_detail", kwargs={"slug": str(self.slug)}) and my view looks like so class PostDetail(DetailView): model = Post template_name = 'post_detail.html' and my template looks like so <ul class="text-center"> {% if post.get_previous_by_created_on_active %} <li class="prev"> <a rel="next" href="{{ post.get_previous_by_created_on.get_absolute_url}}"> {{ post.get_previous_by_created_on_active}}</a> </li> {% endif %} {% if post.get_next_by_created_on %} <li class="next"> <a rel="next" href="{{ post.get_next_by_created_on.get_absolute_url}}"> {{ post.get_next_by_created_on}} </a> </li> </ul> Is there any way I can pass the status == 1 to the get_next_by_created_on so it always shows the next active post, not the next draft post? -
SystemCheckError: System check identified some issues: (models.E006)
I'm trying to make a Tic Toc Toe game with Django but I have a problem with models. you can see the error here. two lines are marked here. they are error lines and the code worked without these lines, but I need these fields. note: I'm using python3.10 and before starting the project I checked to see if django works for it. ALSO see here for more information about the TextFields. players/models.py scripts: from django.db import models as m from json import dumps, loads class Match(m.Model): player1 = player2 = m.ForeignKey('Player', on_delete=m.CASCADE) started_at = m.DateTimeField() tables = m.TextField() class Player(m.Model): points = m.IntegerField(default=0) matchs_played = m.IntegerField(default=0) speed_average = m.FloatField(null=True) last_game = m.ForeignKey(Match, on_delete=m.CASCADE) class Table(m.Model): starter = rival = m.ForeignKey(Player, on_delete=m.CASCADE) match = m.ForeignKey(Match, on_delete=m.CASCADE) raw_items = m.TextField(default=dumps([[[0, .0] for _ in range(3)] for _ in range(3)])) # [[[0, .0] * 3] * 3] def __init__(self, *, starter, rival, match, items: list[list[list[int]]]): # TODO: convert list to json object super().__init__(starter=starter, rival=rival, match=match, raw_items=loads(items)) @property def items(self) -> list[list[int]]: return loads(self.raw_items) @items.setter def items(self, value: list[list[int]]) -> None: self.raw_items = dumps(value) ... # other methods and error: (venv) X:...>py manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: players.Match.player1: (models.E006) … -
If-statement in a for loop in Django disappears when executing
I am building a chatbot using Django that can take survey's preset answer choices and give different scores to different answer choices. After that, the chatbot will sum all the scores accordingly and print out the results. This is a sample question with preset answer choices <select name="survey1-q" data-conv-question="Bạn có hay nghĩ về một điều sẽ xảy ra trong tương lai theo hướng tồi tệ, thậm chí rất tiêu cực?"> <option value="survey1-never">Không bao giờ</option> <option value="survey1-rarely">Hiếm khi</option> <option value="survey1-sometimes">Đôi khi</option> <option value="survey1-often">Thường xuyên</option> <option value="survey1-veryoften">Rất thường xuyên</option> </select> This is my if-statement inside a for loop <!--looping and getting the survey's result--> {% for i in survey1-q%} {% if survey1-q is "Không bao giờ"%} {{score}}={{score + 0}} {% elif survey1-q is "Hiếm khi" %} {{score}}={{score + 1}} {%elif survey1-q is "Đôi khi"%} {{score}}={{score + 2}} {%elif survey1-q is "Thường xuyên"%} {{score}}={{score + 3}} {%elif survey1-q is "Rất thường xuyên"%} {{score}}={{score + 4}} {%endif%} {% endfor %} <p>Điểm của bạn là {{score}}</p> However, after the survey's questions are finished, the chatbot automatically load back to the beginning stage and ask the first question instead of printing the {{score}} I am afraid I had been wrong in calling out the variables in … -
Automatic login in Django
Hi I'm writing app in Django and I thougt about automatically login "user 0" just for convinience, and when someone tries to log in or register it automatically logs out of "user 0" and lets login to normal user, but I'm not sure how to implement that. -
Can't figure out how to 'assert' properly for psycopg2.errors.NotNullViolation in Django
I am currently creating some tests for a model I created. The test is checking to see if the first_name NOT NULL constraint is working for that field. It should do that by checking if the object.save() method fails. If it fails then the assertation should return pass. My test method looks like this: def test_tutor_fname_notnull(self): ''' Test passes if first_name NOT NULL constraint is working. If first_name is missing, data should not be saved to DB and return false. ''' stevie = Tutors(last_name='wonder',email='sboywonder@gmail.com',birth_day='1990-01-02') self.assertIs(stevie.save(), False) The assertation fails and returns this: psycopg2.errors.NotNullViolation: null value in column "first_name" of relation "artsubjects_tutors" violates not-null constraint DETAIL: Failing row contains (1, null, wonder, sboywonder@gmail.com, 1990-01-02). This means the NOT NULL constraint is working and that the assertation should pass. But the assertation actually fails. ---------------------------------------------------------------------- Ran 1 test in 0.003s FAILED (errors=1) Destroying test database for alias 'default'... Any idea on how I could better handle this assertation as to make it pass as intended when the object.save() method fails as expected? -
Django and Mypy : unable to read config options
I am attempting to use mypy with django, following the tutorial here: django-mypy-check-runs I wasn't able to use the init.py import as per the article, instead I used the same code in the ready function of the apps.py in my top level app. mypy runs perfectly, as long as the function api.run has the project base directory in a list as a parameter as per the code in the article: results = api.run([settings.BASE_DIR]) I am unable to find out why the project base directory presented this way is of any use. According to the docs, the list that is passed to api.run, should have configuration options passed in the list as they would be passed to the executable on the commandline. I have checked the source code of mypy and this seems to be the case. If I change the code so that the api.run has a list as a parameter, that contains configuration options, mypy doesn't work. If I pass an empty list or no list at all, mypy doesn't work. Also, although I have a mypy.ini file in the same directory, and also at the project root (in case this is what the settings.BASE_DIR in the list passed … -
Does Django support integer enums for model fields similar to models.TextChoices?
I'm using Django 3.2 and Python 3.9 and Postgres. I have the below model in which I want to constrain one of the fields ("type") to be from a predefined enum ... class Transaction(models.Model): class TransactionTypes(models.TextChoices): BUY = 'BUY', _('Buy') SELL = 'SELL', _('Sell') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(null=False, default=datetime.now) price = models.FloatField(null=False) amount = models.FloatField(null=False) type = models.CharField( null=False, max_length=5, choices=TransactionTypes.choices, ) class Meta: indexes = [ models.Index(fields=['created']), However, this is slightly space-inefficient as I'm using a character type when I feel I shoudl be using an integer type for the enums. Does Django have anything out of the box that can accommodate integer enum types? -
How to write clean permission in Django
I have never deal with a custom permission system and I am kind of struggling. I have this get_queryset: def get_queryset(self): """ Get query set regarding the user's group. If the group name is not xx then filter the result by dealer name """ user_groups = self.request.user.groups.all().values_list('name', flat=True) if 'xx' not in user_groups: dealer = MANUFACTER_CHOICE dealer_name: str = [dealer_name[1] for dealer_name in dealer if dealer_name[1].lower() in user_groups][0] return ShapeFile.objects.filter(system__dealer__name=dealer_name) return ShapeFile.objects.all() Basically, it check the group the user is in. My users must be in a group. My ShapeFile model have a foreign key to system that have a field dealer. Dealer must be equal to one of my group name. If the user is in xx, he can see every ShapeFile on the DB. Else I need to check the group the user is in and find all shapefile that belong to a system that have a dealer name equal to the user's group. I feel that I should implement a Object level permission https://www.django-rest-framework.org/api-guide/permissions/#object-level-permissions. But I do not see how I could use it. Could anyone explain what's the good way to do this ? Thanks -
[Django]Cant run collectstatic to upload media to S3
I'm using the following configs to store static and media files to S3 USES_S3 = config('USES_S3') == 'True' if USES_S3: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_KEY = config('AWS_SECRET_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_REGION_NAME = config('AWS_S3_REGION_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=94608000'} STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' STATICFILES_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/' MEDIAFILES_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/media/' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') However I keep getting the following error, when I try to run collectstatic k_date = self._sign(('AWS4' + key).encode('utf-8'), TypeError: can only concatenate str (not "NoneType") to str It seems this error happens when you can't connect to S3. What am I doing wrong, any help appreciated. -
Form with ImageField doesn't open pop-up to choose file
I do have a straight forward form to update the user's profile picture. However, in the template when I click choose file it doesn't pop the dialog to select a file from the computer. # Template <form class="update-profile-image-form" method="post" enctype="multipart/form-data" action="update_profile_image/"> {% csrf_token %} {{ profile_image_form }} <button type="submit">Save Image</button> </form> If I submit the form without selection a file, it processes everything just fine using the default image set in the model. So somehow the form seems to be working to some extend at least.. # Form class ImageUpdateForm(forms.ModelForm): class Meta: model = Account fields = ['profile_image'] # Model def get_profile_image_filepath(self, filename): return f'profile_image/{self.pk}/{"profile_image.png"}' def get_default_profile_image(): return "profile_image/Logo_large.png" class Account(AbstractBaseUser): """ Main User Account model, inherits from AbstractBaseUser """ email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=40, unique=True) profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image()) -
Embed jupyter notebook in django
I have a web page(django) which shows the contents of a folder. I want to open the files in this folder with jupyter notebook. How can i embedd the jupyter link on my page ? Clicking the link must: Open a jupyter notebook with selected folder. The notebook must be available seperately for each logged in user.(Preferably all the note book instances must open on the same port, with different token id.) Is it possible ? -
Django throwing a ValueError: source code string cannot contain null bytes
The whole error is quite huge : Traceback (most recent call last): File "C:\Users\FiercePC\IdeaProjects\RadioShazam\server\ServerDjango\manage.py", line 22, in <module> main() File "C:\Users\FiercePC\IdeaProjects\RadioShazam\server\ServerDjango\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 257, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 39, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 3, in <module> from django.core.management.commands.runserver import ( File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 10, in <module> from django.core.servers.basehttp import ( File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\servers\basehttp.py", line 14, in <module> from wsgiref import simple_server ValueError: source code string cannot contain null bytes` I just generated the project and didnt almost anything. The program works on my computer but not on my friends. We have the same versions of python/django etc.