Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin image upload error "submitted file is empty"
I was trying to upload an image with the ImageField and one I select the image and click save it is throwing an error that the submitted file is empty. error screenshot models.py class Gallery(models.Model): id = models.AutoField(primary_key=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=100, null=False) image = models.ImageField(upload_to='images') urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) Also it has not created a media directory. is it because that I have a directory named media inside my static? media directory i created inside static MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Checked google for quick fixes. -
How to have a master detail datatableview in django using MultipleDatatableView
I'd like to have a master-detail datatableview in my app. I've used MultipleDatatableView according to the document. I'm confused How to edit the front and add a GET parameter hint (exp: ?datatable=master) . Without using MultipleDatatableView, my code works correctly but when I change it to multiple, it doen't work because of this error: django.utils.datastructures.MultiValueDictKeyError: 'datatable' I tried to add datatable=master in the option of datatable, but this doesn't work. -
Database columns not being created from base class
I am trying to run migrations from a Django 5.0 project, with the default SQLite database connected. The contents of my models.py file are as follows class CustomBaseModel(models.Model): InsertedBy = models.BigIntegerField(blank=False), InsertedDateTime = models.DateTimeField(blank=False, auto_now_add=True), UpdatedBy = models.BigIntegerField(blank=False), UpdatedDateTime = models.DateTimeField(blank=False, auto_now_add=True), class Meta: abstract = True class ExcelColumnDataType(CustomBaseModel): DataTypeName = models.CharField(max_length=100, blank=False) class Meta(CustomBaseModel.Meta): db_table = "ExcelColumnDataTypes" However, when I run the commands for migration, only "id" and "DataTypeName" columns are being created in the table ExcelColumnDataTypes. The columns specified in the base class are not being created. The contents of the auto-generated migration file is given below class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='ExcelColumnDataType', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('DataTypeName', models.CharField(max_length=100)), ], options={ 'db_table': 'ExcelColumnDataTypes', 'abstract': False, }, ), ] I have also tried removing all tables in the SQLite database file and removing the .py migration files in "migrations" folder. Even then, the same result occurs. Can you please tell me what I am doing wrong? -
createin branches on django website for each admin user
i want to create a branch for each new admin that is register on my e-commerce website based on location of my shops and along with the staff and every transaction and sell done in each branch will only show on that branch -
Someone could help me I have problems with the environment [duplicate]
(entorno) PS C:\\Users\\maner\\OneDrive\\Escritorio\\Secoed\\secoed-develop\> python manage.py createsuperuser Traceback (most recent call last): File "manage.py", line 22, in \<module\> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\\Users\\maner\\OneDrive\\Escritorio\\Secoed\\entorno\\lib\\site-packages\\django\\core\\management\__init_\_.py", line 442, in execute_from_command_line utility.execute() File "C:\\Users\\maner\\OneDrive\\Escritorio\\Secoed\\entorno\\lib\\site-packages\\django\\core\\management\__init_\_.py", line 416, in execute django.setup() File "C:\\Users\\maner\\OneDrive\\Escritorio\\Secoed\\entorno\\lib\\site-packages\\django\__init_\_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\\Users\\maner\\OneDrive\\Escritorio\\Secoed\\entorno\\lib\\site-packages\\django\\apps\\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\\Users\\maner\\OneDrive\\Escritorio\\Secoed\\entorno\\lib\\site-packages\\django\\apps\\config.py", line 193, in create import_module(entry) File "C:\\Users\\maner\\AppData\\Local\\Programs\\Python\\Python38\\lib\\importlib\__init_\_.py", line 127, in import_module return \_bootstrap.\_gcd_import(name\[level:\], package, level) File "\<frozen importlib.\_bootstrap\>", line 1014, in \_gcd_import File "\<frozen importlib.\_bootstrap\>", line 991, in \_find_and_load File "\<frozen importlib.\_bootstrap\>", line 973, in \_find_and_load_unlocked ModuleNotFoundError: No module named 'channels' python manage.py createsuperuser -
Django Forms with multiple models
I am trying to have a several part form that includes property(address) upload date, inspector, and inspectee. There is an add area button that adds a name of an area(backyard,etc) and notes to go along with that area. lastly there is a picture that lets you upload a picture. enter image description here When i add an area that seems to be working to me. it adds the inputs. the problem is when i click upload i get these errors. enter image description here. The problem is that I have seperate models for the property, inspection, areas, and area images. The idea is that one property should have an inspection, many areas, and each area could have one or more images. Im sure the view is wrong, but I don't know what to do. Maybe its because the inspection form hasnt been submitted so lines in the views like this dont work area.property = inspection.property # Set the property field Although im not sure why i wouldnt get a serverside error when submitting then Here are my models from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Add any additional fields here def __str__(self): … -
Unable to access Google Cloud Secrets from Django application
I am able to access an item stored in Google Cloud secrets from the command line or python console - gcloud secrets versions access 1 --secret=sql-db-pass But if I try to access it from a Django application it throws the following error. I have already set the gcloud project and provided auth-default login as below gcloud config set project my-test-project gcloud auth application-default login CODE: secret_parent = f"projects/{my-test-project}" response = secret_client.access_secret_version(request={"name": sql-db-pass}) payload = response.payload.data.decode("UTF-8") print(f"Plaintext: {payload}") ERROR: google.api_core.exceptions.PermissionDenied: 403 Permission denied on resource project sql-db-pass. [links { description: "Google developers console" url: "https://console.developers.google.com" } , reason: "CONSUMER_INVALID" domain: "googleapis.com" metadata { key: "service" value: "secretmanager.googleapis.com" } metadata { key: "consumer" value: "projects/sql-db-pass " } ] I'm stumped - any suggestions are appreciated -
Is this the best way to handle storage of uploaded files in Django?
I'm not sure if I should use something like fs.save() or another method, such as chunking, to handle file uploads in Django. So far this is my method: def handle_uploaded_file(uploaded_file): filename = uploaded_file.name filepath = os.path.join(settings.MEDIA_ROOT, filename) with open(uploaded_file.name, 'wb') as destination: for chunk in uploaded_file.chunks(): destination.write(chunk) return filepath @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): print('valid') uploaded_file = handle_uploaded_file(request.FILES['file']) The purpose of this view is to handle video and audio uploads if this is relevant. I haven't been ablto find any good, simple documentation on this. -
Django Error : No property found matching the query
So I am building a site with Django where a Property has an agent who lists it, in the AgentDetailView I am rendering all the agent's information but I also want to render the agent's listed properties in the same page. So I was trying the Property.objects.filter method but to no success. How can I make my code work? Thanks in advance! My models.py: class Property(models.Model): price = models.IntegerField() address = models.CharField(max_length = 10000) state = models.CharField(max_length = 1000) country = models.CharField(max_length = 1000) description = models.TextField() image1 = models.ImageField(upload_to = 'Images/') image2 = models.ImageField(upload_to = 'Images/') image3 = models.ImageField(upload_to = 'Images/') agent = models.ForeignKey(Agent, on_delete=models.CASCADE) agent_description = models.TextField() is_featured = models.BooleanField(default = False) bedrooms = models.IntegerField() bathrooms = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) slug = models.SlugField(default='') My views.py: class AgentDetailView(DetailView): model = Agent template_name = 'blog/agent_detail.html' slug_field = 'slug' def get_queryset(self): return Property.objects.filter(agent=self.kwargs.get('agent')) -
splitting Django monolithic
Let's say I've a big Django monolithic e-commerce I've product, orders and webhooks apps I want to split them to make sure that when a service is down, the others stays up when I do some changes in a model, I don't want to keep redoing the changes in the others any ideas on better approaches? -
Integrate Stripe with Django app to give the user a Group
I am trying to integrate Stripe with my Django app. My plan : Someone register for free into my site. If this people want to buy an extra service, the Already Logged user get into a group/role called "Paid Users" (that i've already created), only that. Almost everything works well, including the Stripe Webhook. But I cant! Look my code @csrf_exempt def webhookStripe(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) # Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed': #This session print WORKS session = event['data']['object'] print(session) #Problem Starts Here - Only trying to print the user ID for me print("Compra feita com sucesso por") print (get_user(request).id) # Passed signature verification return HttpResponse(status=200) Every time i need to see the ID, or username, or anything about the current user, it shows me: enter image description here "None" Apparently, when the payment is OK, it loses temporarily everything about my user. Tried request.user.username too, but didnt work. Someone can help me? I only need to keep the user informations everytime. Or even better, … -
HTML GET with and without ID in Django View Based Classes
Hello Stranger reading this, Im currently learning Django at work, and we want out project to use View Based Classes instead of using the classic views.py :) The problem Im having is when i try to GET Request my website with ID and without ID in the same class Basically im trying to read my entire DB with: .../sample And only read ID specific entries with ID: .../sample/ Basically what you do in this tutorial, but with View Based Classes: https://www.bezkoder.com/django-rest-api/ I tried the solution suggested for this problem, but i think they differ a little too much: Multiple get methods in same class in Django views So first i tried: path(Sample, SampleClass.asView()), path(Sample/int:id, SampleClass.asView({'get': 'get_id'}) I thought this would reroute the route of the GET with id to use get_id instead of the normal get. Then i tried using the action decorator of the rest_framework: def get(self, request): ... @action(methods=['get], detail=False, url_path='int:id') def get_id(self, request, id): ... And the routing part in the urls.py Seems like a very generic problem, but sadly i wasnt able to solve it myself :( I hope the paraphrasing of the problem is enough, but i can try to describe it further if so … -
Initial value in Django forms
When I try to setup initial value in Django I encounter a problem with sending that value to the database. User should not be able to change the username while posting a review. The field should be populated with username (initial value) that was given during the registration (this part works as per first screenshot) and then input rating (mandatory field) and body (optional field) should be filled by the user. The problem is, when I press "add review" I am encountering below problem. The field 'user' gets erased, the form does not save data into the database (because the form is not valid) and does not allow to move forward until field is populated (which cannot be as the field is disable on purpose). views.py: @require_POST def post_review(request, bookid): book = get_object_or_404(Book, bookid=bookid) if request.user.is_authenticated: form = ReviewForm(data=request.POST) form.fields["user"].initial = request.user.username if form.is_valid(): review = form.save(commit=False) review.book = book review.user = request.user review.save() return redirect(review.book.get_absolute_url()) else: form = ReviewForm(data=request.POST) return render(request, "book/review.html", {"book": book, "form": form}) forms.py: class ReviewForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop("user", None) super(ReviewForm, self).__init__(*args, **kwargs) self.fields["user"].initial = user class Meta: model = Review fields = ("user", "rating", "body") widgets = { 'user': forms.TextInput(attrs={"readonly": "readonly", … -
jwt token is not working with custom user
Hi I want to implement jwt login method in django rest framework. Below are the libraries I use. asgiref 3.7.2 Django 5.0 django-debug-toolbar 4.2.0 djangorestframework 3.14.0 djangorestframework-simplejwt 5.3.1 pip 23.3.1 PyJWT 2.8.0 pytz 2023.3.post1 setuptools 68.2.2 sqlparse 0.4.4 Python Version is 3.11.6 Below are the settings I made. settings.py INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework_simplejwt', 'debug_toolbar', ''' ] AUTH_USER_MODEL = 'accounts.User' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } REST_USE_JWT = True User Model Custom from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, username, password, **kwargs): if not username: raise ValueError('Users must have an username') user = self.model( username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username=None, password=None, **extra_fields): superuser = self.create_user( username=username, password=password, ) superuser.is_staff = True superuser.is_superuser = True superuser.is_active = True superuser.save(using=self._db) return superuser from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.utils.translation import gettext_lazy as _ from accounts.managers import UserManager class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=30, unique=True, null=False, blank=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # 헬퍼 클래스 사용 objects = UserManager() USERNAME_FIELD = 'username' Signup, Login class RegisterAPIView(APIView): def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = … -
Updating user's API call based on user premium status using Djagno custom throttle
I'm trying to write a custom throttle that checks a user's account premium status when making an API call. Looking at the docs I believe I wrote the custom throttle correctly updated my settings. I'm building a translation website where a user clicks a button on a piece of text and provides translation returned from a translator API. Django Settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.ScopedRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'premium': '5/day', 'user': "1/day", } } throttles.py from rest_framework.throttling import UserRateThrottle class UserType(UserRateThrottle): def allow_request(self, request, view): user_type = getattr(request.user, 'premium_account', None) if user_type == False: request.scope = 'user' else: request.scope = 'premium' return super().allow_request(request,view) How I'm passing my UserType into my API. class Translator(APIView): throttle_classes = [UserType] def get(self, request, *args, **kwargs): I tried writing a custom DEFAULT_THROTTLE_CLASES item and it was counting any interaction with my website (like logging in) against the throttle rate. -
Django subclass that has a reference to instance of parent class
I'm trying to make a subclass that has a foreignkey to another instance of its parent class, for example for up-sampling. I want to do this so that I can get a dropdown in a form that has a list of all the classes, regardless of whether it is based on another instance. class ImageResolution(models.Model): image_depth = models.IntegerField(default=3) image_width = models.IntegerField(default=1920) image_height = models.IntegerField(default=1080) class DerivedImageResolution(ImageResolution): base_resolution = models.ForeignKey(ImageResolution, on_delete=models.DO_NOTHING, related_name='base_resolution') This throws an error: imageapp.DerivedImageResolution.base_resolution: (models.E006) The field 'base_resolution' clashes with the field 'base_resolution' from model 'imageapp.imageresolution'. Is it possible to do this? If so, how can it be done? -
Why I can't install django in my virtual enviroment?
Well, basically i'm trying to install django through this code: pipenv install django and the result is:[] then I have an ERROR: Couldn't install package:... thousand of things I can't even show here I tried to download the new python version and the new django version but keeps asking for python >=3.7 and I can't understand why I have no idea about what to do because as I stopped backend to study datascience I let django and python on the corner and now I don't even know what happened. I tried to download python 3.12 and Django 5.0 but didn't work MAYBE as I just deleted some folders from my computer related to django as I wasn't working with it there can be something faulting. When I uninstall django and install again, there is some requirements already installed on my computer and it can be the error. -
Adding custom rich text format to Wagtail
I need to use underline for a certain project and I discovered it was frowned upon by the developers. While respectfully disagreeing with the opinion, Wagtail has enough documentation to make it possible to spin my own feature to try to add it back. I succeeded in showing an underline feature in the editor but the frontend doesn't render a <u> tag. @hooks.register("register_rich_text_features") def register_underline_feature(features): """ Registering the `underline` feature, which uses the `UNDERLINE` Draft.js inline style type, and is stored as HTML with a `<u>` tag. """ feature_name = "underline" type_ = "UNDERLINE" tag = "u" control = { "type": type_, # for all intents and purposes this should have worked but the actual icon is missing. Deliberate? # "icon": "underline", "label": "U͟", "description": "Underline", "style": {"textDecoration": "underline"}, } features.register_editor_plugin("draftail", feature_name, draftail_features.InlineStyleFeature(control)) db_conversion = { "from_database_format": {tag: InlineStyleElementHandler(type_)}, "to_database_format": {"style_map": {type_: tag}}, } features.register_converter_rule("contentstate", feature_name, db_conversion) features.default_features.append("underline") My suspicion is in db_conversion. I was looking into turning the tag into a <u> or a <span> with an inline text-decoration style in the frontend but it doesn't. What am I missing? -
Don't get linkify=True working within Django-Tables2 Column
I want to display two tables a single page/view (using MultiTableMixin). Within each row there should be links to the instance (display), modification and deletion. Classical access to (c)RUD operations through extra columns compared to the actual model. I also saw a similar question already. But it didn't work as expected. I wanted to simplify/ clean up my code using linkify instead of LinkColumn. Unfortunately, I already struggle with the display part. The following old style works: columns.LinkColumn( "matching:search", args=[A("pk")], verbose_name="", text="display", orderable=False, ) As stated by the docs, using linkify=True should call the get_absolute_url method of the underlying model instance. The method clearly is present and tested. Hence, I added to the table `display = tables.Column(orderable=False, verbose_name="", linkify=True). But all I get is "--" within the now created display column instead of the wanted link. Looking at the source code I see a needed accessor attribute for the linkify to take effect. Am I understanding something wrong? Any help to clearify would be appreciated. -
I couldn't make virtual environment in visual-studio. please check this error
below is the screenshot of the error i got while making virtual environment in visual studio code. there is an error message in terminal section while the myvenv (virtual environment folder) was created. actually there is not 'activate' file in Scripts folder of myvenv folder. I cannot understand the error message, how can I handle this problem? -
Problem after upgrading to django 5.0 "AttributeError: 'BlankChoiceIterator' object has no attribute '__len__' "
I'm new in django triad to upgrade to version 5.0 but got this problem in my project Traceback (most recent call last): File "dirto/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "dirto/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "dirto/env/lib/python3.10/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content File "dirto/env/lib/python3.10/site-packages/django/template/response.py", line 92, in rendered_content return template.render(context, self._request) File "dirto/env/lib/python3.10/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 171, in render return self._render(context) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 1000, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 1000, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 961, in render_annotated return self.render(context) File "dirto/env/lib/python3.10/site-packages/django/template/loader_tags.py", line 159, in render return compiled_parent._render(context) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 1000, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 1000, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 961, in render_annotated return self.render(context) File "dirto/env/lib/python3.10/site-packages/django/template/defaulttags.py", line 325, in render return nodelist.render(context) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 1000, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 1000, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 961, in render_annotated … -
How to override "save_model" for UserAdmin of User model
i'm trying to override save_model when i enter an existing email i get this error "<User: >" needs to have a value for field "id" before this many-to-many relationship can be used. class UserAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): email = form.data.get("email") if User.objects.filter(email=email).exists(): messages.set_level(request, messages.ERROR) return messages.error( request, _("An account with this email address already exists.") ) else: obj.set_password(form.cleaned_data["password"]) if ( Group.objects.get(id=form.data.get("groups")).is_staff and form.data.get("is_staff") is None ): obj.is_staff = True if ( not Group.objects.get(id=form.data.get("groups")).is_staff and form.data.get("is_staff") is not None ): obj.is_staff = False obj.save() EmailAddress.objects.create(email=email,user_id=obj.id) return super().save_model(request, obj, form, change) i think this error is triggered because it's trying to add user id to groups model but the user is not being created how can i fix it -
Django Bootstrap modal edit not showing data on inputs
I am developing a Django application to store customers data with a CRUD. I decided to use bootstrap modals to Add, edit info and delete a new customer. Therefore, I'm dealing with some problems when I try to open the edit modal. When the edit customer modal is opened the customer information that was clicked on is not appearing in the input fields of the form. Below I will show the pieces of my code in question, which are being used in this feature My base template is "meus-clientes.html" and the button to show the edit modal, is inside the table: <div> <div class="card mb-4" id="tabela-pedidos"> <div class="card-header"> <div> <i class="fas fa-user-tie"></i> Clientes cadastrados </div> </div> <div class="card-body"> <table id="datatablesSimple2"> <thead> <tr> <th>Nome</th> <th>Telefone</th> <th>E-mail</th> <th>CPF</th> <th>Endereço</th> <th>Pagamento</th> <th>Ações</th> </tr> </thead> <tfoot> <tr> <th>Nome</th> <th>Telefone</th> <th>E-mail</th> <th>CPF</th> <th>Endereço</th> <th>Pagamento</th> <th>Ações</th> </tr> </tfoot> <tbody> {% for dados_cliente in dados_clientes %} <tr> <td>{{ dados_cliente.nome }}</td> <td>{{ dados_cliente.telefone }}</td> <td>{{ dados_cliente.email_1 }}</td> <td>{{ dados_cliente.cpf }}</td> <td>{{ dados_cliente.endereco }}</td> <td>{{ dados_cliente.metodo_pagamento }}</td> <td> <div class="action-link"> <a title="Editar cliente" href="{% url 'editar_cliente' dados_cliente.id %}"> <i class="fas fa-pen"></i> </a> <a data-bs-toggle="modal" data-bs-target="#deleteModal{{ dados_cliente.id }}" title="Excluir Cliente"> <i class="fa-solid fa-trash-can"></i> </a> </div> </td> </tr> {% include 'editar-cliente.html' … -
Run pytest behind Django Admin custom action
I'm building API that allows users to send input data to generate printable documents. On top of that I need to allow users to define templates (HTML) for these documents in which users define the layout and logic. I would like users to be able to define test cases for their templates where they can define input data as well as expected output and run tests (pytest) behind a custom Django admin action. Pytest will use test input data, render the output document and compare it to the user defined benchmark. Stdout of pytest run should be written to text file which is included in the response of custom Django admin action. My initial implementation behind Django admin was using pytest.main() functionality. import sys from io import StringIO class TestCaseAdmin(admin.ModelAdmin): ... def run_selected_test_cases(self, request, queryset): sys.stdout = StringIO() pytest.main([ "tests/functional/test_user_cases.py", "-vv", ]) result = sys.stdout.getvalue() response = HttpResponse(result, content_type="text/plain") response["Content-Disposition"] = f"attachment; filename={filename}" return response The above implementation will run the tests defined in test_user_cases.py and download text file with pytest stdout. However after this is done, pytest crashes with error: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. This … -
Django - form is always not valid
I am new to Django, I have to do a simple web page to register people. Some names is in Portuguese, but it does not matter. I do not know what I am doing wrong, maybe I am sending empty data to the view, but I am not sure. view.py: def get_form(request): logger = logging.getLogger('django') logger.info("Request") if request.method == 'POST': logger.info("POST method") form = cadastroForm(request.POST) logger.info(form.errors) if form.is_valid(): logger.info("Valid") insert_data(form.cleaned_data['nome'], form.cleaned_data['mat'], form.cleaned_data['telefone'], form.cleaned_data['email']) return HttpResponseRedirect(reverse('all-borrowed')) else: logger.info("Not Valid") else: form = cadastroForm() html page: {% block page_content %} <h1 style="text-align: center; margin-top: 10%; margin-bottom: 5%; font-size: 64px;">Cadastro</h1> <form action="../../views.py" style="display: inline-block; margin-left: 40%;" method = "POST"> {% csrf_token %} <label for="nome">Nome:</label> <input type="text" id="nome" name="nome" style="margin-left: 30px" maxlength="100" required><br><br> <label for="telefone">Telefone:</label> <input type="text" id="telefone" name="telefone" style="margin-left: 10px" required><br><br> <label for="email">Email:</label> <input type="text" id="email" name="email" style="margin-left: 36px" required> <p style="margin-top: 15px;">Frequenta o IESB: <input type="radio" id="iesb_sim" name="iesb" value="Yes" required><label for="iesb_sim" style="margin-left: 5px">Sim</label> <input type="radio" id="iesb_nao" name="iesb" value="No" required checked="checked"><label for="iesb_nao" style="margin-left: 5px">Não</label> </p> <label for="mat">Matrícula:</label> <input type="text" id="mat" name="mat"> <br><br> <input type="file" style="margin-bottom: 18px" id="myFile" name="filename"> <input type="submit" value="Enviar" style="margin: auto; display: block;"> </form> <script> document.getElementById("iesb_sim").addEventListener("change", function(){ document.getElementById("mat").disabled = false; }) document.getElementById("iesb_nao").addEventListener("change", function(){ document.getElementById("mat").disabled = true; }) </script> {% endblock page_content …