Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django tests: model name cannot be resolved, although site works
I have a website written in Django. Apart from main app, I have one called app and other users. In users I have implemented my CustomUser model, which I am also using inside models for app. When I run the website, it all works fine; however when I tried to create tests for the app I get: ValueError: Related model 'users.customuser' cannot be resolved (even though tests.py are empty now). And obviously, in app/tests.py I do from .models import CustomUser. I tried looking at the order of imports in settings.py but it seemed right to me: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'app', ] I have also done migrations for both apps. -
Django testing a simple model with Foreign Key and UpdateView
Two very simple models from django.db import models class Location(models.Model): name = models.CharField(max_length=255) location_number = models.CharField(max_length=30, unique=True) def __str__(self): return self.name class Project(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, to_field='location_number', db_column='location_number', related_name='projects', verbose_name='Standort') name = models.CharField(max_length=255) slug = models.SlugField(unique=True) def __str__(self): return self.name with an UpdateView from .models import Project from django.views.generic import UpdateView class ProjectUpdateView(UpdateView): model = Project fields = "__all__" slug_url_kwarg = 'project_slug' slug_field = 'slug' should be tested with this simple test: from django.test import TestCase from django.urls import reverse from .models import Project, Location from urllib.parse import urlencode from django.utils.http import urlencode class ProjectUpdateTest(TestCase): def setUp(self): self.location = Location.objects.create( name='Test Location', ) self.project = Project.objects.create( location=self.location, slug="test", name='Test Project', ) def test_project_update_view(self): # Prepare the data for the form form_data = { 'name': 'Updated Project', 'location': self.location.pk, 'slug': 'test', } # Build the URL for the project detail view url = reverse('update_project', kwargs={ 'project_slug': self.project.slug }) # Encode the form data as form-encoded data encoded_form_data = urlencode(form_data, doseq=True) # Send a POST request to the project update view with the form-encoded data response = self.client.post(url, data=encoded_form_data, content_type='application/x-www-form-urlencoded') # Print form errors, if any form = response.context['form'] print(form.errors) self.project.refresh_from_db() self.assertEqual(self.project.name, 'Updated Project') But it fails with locationSelect a valid … -
how to upload file to server / django rest framework
Thanks to stack overflow, I implemented loading a file in views, but how to make sure that the file gets to the server and data appears in the database. If I upload a file through the admin panel, then everything works fine. I'm testing with postman. Thank you) # urls.py path('api/v1/UploadDataset/', UploadDataset.as_view()), # models.py class Datasets(models.Model): create_at = models.IntegerField(max_length=50) user = models.IntegerField(max_length=50) name_dataset = models.CharField(max_length=255) link_dataset = models.FileField (upload_to=datasets_filename) # serializers.py class UploadDatasetSerializer(serializers.ModelSerializer): class Meta: model = Datasets fields = '__all__' # views.py class UploadDataset(APIView): parser_classes = (MultiPartParser, FormParser ) #parser_classes = [FileUploadParser] def put(self, request, format=None): file_obj = request.FILES['file'] # do some stuff with uploaded file ??? return Response(status=204) -
drf_spectacular.utils.PolymorphicProxySerializer.__init__() got an unexpected keyword argument 'context'
I am using a PolymorphicProxySerializer provided by drf_spectacular but I am getting a strange error when attempting to load the schema usage @extend_schema( parameters=[NoteQueryParameters], responses=PolymorphicProxySerializer( component_name="NoteSerializer", serializers=[NoteSerializer, NoteSerializerWithJiraData], resource_type_field_name=None, ), ) def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) serializers class CleanedJiraDataSerializer(serializers.Serializer): key = serializers.CharField(max_length=20, allow_null=True) class BugSerializer(serializers.Serializer): failures = serializers.CharField(max_length=10, required=False, allow_null=True) suite = serializers.CharField(max_length=100, required=False, allow_null=True) notes = serializers.CharField(max_length=1000, required=False, allow_null=True) tags = StringListField(required=False, allow_null=True, allow_empty=True) testCaseNames = StringListField(required=False, allow_null=True, allow_empty=True) testCaseIds = StringListField(required=False, allow_null=True, allow_empty=True) jira = CleanedJiraDataSerializer(required=False, allow_null=True) class BugSerializerWithJiraData(BugSerializer): jira = serializers.DictField() class NoteSerializer(serializers.ModelSerializer): bug = serializers.ListField(child=BugSerializer()) class Meta: model = Notes fields = "__all__" class NoteSerializerWithJiraData(serializers.ModelSerializer): bug = serializers.ListField(child=BugSerializerWithJiraData()) class Meta: model = Notes fields = "__all__" Basically, if a boolean query parameter is added to the request, I will inject some dynamic data fetched from the jira api. I am trying to update the api docs to represent to two distinct possible schema PolymorphicProxySerializer.__init__() got an unexpected keyword argument 'context' -
How do I run a python APscheduler independant of subsequent deployments
I have a django application with a python AP scheduler running a specific job. I wish to run the job once every week. There might be subsequent deployments to the application and I do not want the scheduler to reset the jobs every time that happens. Is there any way to provide a past start date or check if a week has elapsed since the last run to ensure that the scheduler jobs run independant of deployments. The scheduler code - from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler() scheduler.add_job(send_weekly_email, 'interval', weeks=1) scheduler.start() -
Translate jquery ajax code snippet into HTMX or manage to fetch selector value
I built a 3 interdependent select lists using htmx, (country region town) and I managed to fetch the selected town as I have this on the last part <select id="localidades" class="form-control-sm custom-select " name="town" hx-get="{% url 'query_for_properties' %}" hx-trigger="change" hx-target="#response" required> <option value="">Select municipality</option> {% for z in lista_localidades %} <option value="{{z}}">{{z}}</option> {% endfor %} </select>` Here I fetch it alright (notice that I am calling this function from the above snippet) def query_for_properties(request): town = request.GET.get('town') etc as I need that town value for the next code. However, this next code needs to send the values to different targets and for each target a different value, like, number of cars, number of bikes etc to different selectors.And that is where I get stuck.The htmx docs, as usual everywhere, are only for the very simple scenarios, but if you need something else, you are a goner, stranded. I have no idea how to deal out different values to different targets. So, I tried ajax, and with jquery it was easy to build calls for every selector. However, because I built the interdependent select lists with htmx,ajax query doesn't get the value. Here it goes <script> $(document).ready(function(){ $("#localidades").on({ change: function(){ var … -
DJANGO - Error creating Solr container (java.nio.file.AccessDeniedException)
I'm trying to implement Solr in my Django project, but when I run the Solr container I get an AccessDenied error. Below are the container and haystack settings local.yml solr: image: solr:7.7.1 restart: always ports: - "8983:8983" volumes: - ./index/core:/opt/solr/server/solr/core environment: - SOLR_JAVA_MEM=-Xms512m -Xmx512m - SOLR_HEAP=512m settings.py HAYSTACK_CONNECTIONS = { "default": { "ENGINE": "haystack.backends.solr_backend.SolrEngine", "URL": env("SOLR_URL", default="http://0.0.0.0:8983/solr/core"), "SILENTLY_FAIL": False, "SOLR_TIMEOUT": 10 } } HAYSTACK_SIGNAL_PROCESSOR = "haystack.signals.RealtimeSignalProcessor" error: SolrCore Initialization Failures core: org.apache.solr.common.SolrException:org.apache.solr.common.SolrException: java.nio.file.AccessDeniedException: /opt/solr/server/solr/core/data -
Django project not displaying some components
so I am building a Django web application, and it has a preview section and this preview section is supposed to display a main-experience and additional-experience however when the form is filled, the main-experience is not being displayed, only the additional-experience displays, its as if the main-experience is being filtered out when the additional-experience is being displayed. What should I change in the code, such that both main and additional experiences are displayed in the preview? The associated codes are below. this is the code i have. both the views and the associated html: views.py: @login_required def experience_v(request): if request.method == 'POST': form = ExperienceForm(request.POST) if form.is_valid(): main_experience = form.save(commit=False) main_experience.user = request.user main_experience.is_main_experience = True main_experience.save() additional_experiences = experience.objects.filter(user=request.user).exclude(pk=main_experience.pk) for entry in additional_experiences: exp = experience.objects.create( user=request.user, position=entry.position, company=entry.company, startdate=entry.startdate, enddate=entry.enddate, roles=entry.roles ) return redirect('education') else: form = ExperienceForm() return render(request, 'experience.html', {'form': form}) @login_required def preview(request): personal_info = personalinfo.objects.filter(user=request.user).last() main_experience = experience.objects.filter(user=request.user, is_main_experience=True).first() additional_experiences = experience.objects.filter(user=request.user).exclude(pk=main_experience.pk) if main_experience else [] educations = education.objects.filter(user=request.user) certs = certificates.objects.filter(user=request.user) return render(request, 'preview.html', { 'personal_info': personal_info, 'main_experience': main_experience, 'additional_experiences': additional_experiences, 'educations': educations, 'certs': certs }) html: <div class="preview-data"> <h2>Experience</h2> <div class="experience-item"> <p><span class="bred">Position</span>: {{ main_experience.position }}</p> <p><span class="bred">Company</span>: {{ main_experience.company }}</p> <p><span … -
I want to create testcase for my project but i got this error
this is the testcase i wrote i have user model that records create only with email confirmation so i have to get email code from EmailConfirm model and i can't pass it to test class as self.email_code. same problem for self.refresh_token and self.user_id class AccountTestCase(APITestCase): def setUp(self): self.email_code = None self.refresh_token = None self.user_id = None return super().setUp() def test_send_email_code(self): url = reverse("accounts:resend_code") data = { 'email': 'testuser@example.com' } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.email_code = EmailConfirm.objects.get(email='testuser@example.com').code def test_register(self): url = reverse("accounts:register") data = { 'username': 'testuser', 'email': 'testuser@example.com', 'password': 'testpassword', 'confirm_password': 'testpassword', 'code': self.email_code } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.user_id = response.data['id'] def test_login(self): url = reverse("accounts:login") data = { 'username': 'testuser', 'password': 'testpassword', } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.refresh_token = response.data['refresh'] def test_token_refresh(self): url = reverse("accounts:token_refresh") data = { 'refresh': self.refresh_token } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.access_token = response.data['access'] The errors: ERROR: test_register (accounts.tests.AccountTestCase) Traceback (most recent call last): File "C:\Users\Mahdyar Eatemad\OneDrive\Projects\Django\ReelRave API\reelrave\accounts\tests.py", line 40, in test_register response = self.client.post(url, data) File "C:\Users\Mahdyar Eatemad\OneDrive\Projects\Django\ReelRave API\reelrave\venv\lib\site-packages\rest_framework\test.py", line 296, in post response = super().post( File "C:\Users\Mahdyar Eatemad\OneDrive\Projects\Django\ReelRave API\reelrave\venv\lib\site-packages\rest_framework\test.py", line 209, in post data, content_type = self._encode_data(data, format, content_type) File "C:\Users\Mahdyar Eatemad\OneDrive\Projects\Django\ReelRave API\reelrave\venv\lib\site-packages\rest_framework\test.py", line … -
Django-Verify-Email 2.0.3 is not defined even after i installed it
im new to django and im trying to verify users email with Django-Verify-Email 2.0.3. As the documentation says i installed the package and did the same steps as they say but i get this error ModuleNotFoundError: No module named 'verify_email' i checked pip and it's already installed what is the problem is there any steps i should do first like create new app of name verify_email or something? i tryed to reinstall the package but same problem still appear -
How can communicate between HTML docs using Django server running via Google Colab notebook?
I want to simply experiment with this tutorial and reflect inputs of Home.html and reflect the summation of them in result.html using Django Server running in Google Colab notebook. I can run the Django server successfully in Google Colab medium, as shown in this screenshot You just need to manually set ALLOWED_HOSTS = ['colab.research.google.com'] in settings.py once you have installed django library in your cluster. The problem is I can't communicate and reflect the results of Home.html and reflect the summation of them in result.html. I saw in the Tutorial the browser of the local machine when opening HTML docs are: I tried following the set-up, but I still could figure out how I could communicate between HTML docs running by Django in Google Colab medium. I think I'm close to a solution, but I still can't manage it yet. ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] Please feel free to access the notebook for quick troubleshooting. You can create HTML docs quickly using Win notepad and save with .html and upload to notebook if necessary. home.html or download from this link: <h2> Welcome to my Web </h2> <form action="result"> <input type="number" name="no1" placeholder="input1"/> <input type="number" name="no2" placeholder="input2"/> <input type="submit"/> </form> result.html or … -
How can I display data from the current hour of data collection from my Django database using Chart.js on my frontend canvas?
I have an issue displaying data from the current hour of data collection from my django database to my frontend Chart.js . (See code below) I have tried what I found with datetime.now() queries below: #1. This block is the one I am trying to fix from datetime import datetime def datapage(request now = datetime.now() print(now.day) # to check current day output print(now.hour) # to check current hour output # Storing appends labels = [] data = [] queryset = Object.objects.filter(datefield__day=now.day, datefield__hour=now.hour) for entry in queryset: labels.append(entry.date.strftime('Hour %H')) data.append(entry.Datafield) return render(request, 'datapage.html', { 'labels': labels, 'data': data, }) #2 This is the compromise I made but it would display rather the current day's data # Modifying this line queryset = Object.objects.filter(datefield__day=now.day, datefield__hour__lte=now.hour) For Context, here's my script on the chart in the frontend, <body> <div class="flex w-full justify-around g-4"> <div class="w-1/2 shadow-md rounded-lg"> <div class="py-3 px-5 bg-gray-50"> Total Environmental Temperature </div> <canvas class="p-10" id="barChart1"></canvas> </div> </div> </body> <script> const barData = { labels: {{labels|safe}}, datasets: [ { label: 'Bar Dataset', backgroundColor: "rgb(34 211 238)", borderColor: "rgb(34 211 238)", data: {{data|safe}}, }, ], }; const barConfig = { type: 'bar', data: barData, options: { responsive: true, plugins: { legend: { position: … -
How to render django form with validators errors ussing reverse() instea of render() to not duplicate the code actually rendering the whole view?
I am trying to implement forms with validators for the 1st time. I have learned that to actually display validators errors to user after he/she will send the form, in the view function definition that covers POST request processing I have to once again trigger view rendering and pass all saved form data (I am storing that in form variable) to this view. I could do it like that: if form.is_valid: (..) else: return render(request, "auctions/listing-details.html", {"auction_id": auction_id, "bidding_form": form} The problem is, that my view requires bunch of params that are being calculated before render function is being called. So to not have to repeat all the calculation code + render() with all the params, I wanted to use HttpResponseRedirect(reverse()) - in my understanding that would redirect the app to the GET request processing of the view (that includes all the params calculation needed for the view rendering). So for example I could do somethig like: if form.is_valid: (..) else: return HttpResponseRedirect(reverse("auctions:listing_details", kwargs={"auction_id": auction_id, "bidding_form": form},)) BUT with this approach I am getting error Reverse for 'listing_details' with keyword arguments '{'auction_id': 3, 'bidding_form': <BidForm bound=True, valid=False, fields=(bid_amount)>}' not found. 1 pattern(s) tried: ['listing\\-details/(?P<auction_id>[0-9]+)\\Z'] Why is that? Is the only … -
Problem with Python Zappa deploy to AWS Lambda
I couldn't fix the problem with zappa aws lambda deploy. My zappa settings: { "dev": { "aws_region": "us-east-1", "django_settings": "photo_crm.settings", "profile_name": "default", "project_name": "photo-crm", "runtime": "python3.10", "s3_bucket": "photo-crm-zappa", "keep_warm": true, "slim_handler": true, "events": [ { "function": "photo_crm.tasks.destroy_galleries_by_terms", "expression": "cron(0 0 * * ? *)" }, { "function": "photo_crm.tasks.birthdays_telegram_bot", "expression": "cron(0 8 * * ? *)" } ], "remote_env": "s3://bucket_link", "exclude": [".env"] } } and I've got the error in the end: Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 500 response code. Part of Logs Calling tail for stage dev.. [1685898767317] INIT_START Runtime Version: python:3.10.v5 Runtime Version ARN: arn:aws:lambda:us-east-1::runtime:51b59a64d1fa5125d324f5fe77fbc805ea96f487f1d112fe4bf3f60323b552cb [1685898767841] Instancing.. [1685898772523] [ERROR] ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2._psycopg' Traceback (most recent call last): File "/var/task/handler.py", line 657, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 241, in lambda_handler handler = global_handler or cls() File "/var/task/handler.py", line 150, in __init__ wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS) File "/var/task/zappa/ext/django_zappa.py", line 13, in get_django_wsgi return get_wsgi_application() File "/var/task/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/task/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/task/django/apps/registry.py", line 116, in populate app_config.import_models() File "/var/task/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/var/lang/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], … -
Recreating Stack Overflow's tag input in Django
I've been trying to recreate Stack Overflow's tag input using Django, Alpine, and Tailwind. I managed to create the UI for it but have no idea how to save it to the database via Django's ORM. For context, we're trying to create a matchmaking system. I am using two fields named wins and losses, based on the teams that player X has wins and losses against. The catch is, a team name that's yet to exist can be entered to accommodate future teams to be registered in the database. Using model forms, I've been told to just use a ManyToMany field for the wins and losses field (related to the Team model), but I don't think that'll work because if they are to be translated into forms, they'd just be dropdowns of pre-existing teams. What's the best approach to this? -
How to safely and atomically decrement a counter with Django and PostgreSQL?
I've been reading up on PostgreSQL transaction isolation and how that relates to Django's transaction.atomic() (e.g. this article, PostgreSQL docs), but I'm far from fluent in this topic and I'm not sure I understand what I've read. We've got a PostgreSQL-backed Django app that involves quota objects. Simplified, it's just this: class Quota(models.Model): obj = models.OneToOneField(AnotherModel) count = models.PositiveIntegerField() An instance of this controls how many times a certain operation can be performed against the obj instance. count is initialized to a certain number, and will only ever decrement until it hits zero. Any number of processes/threads can concurrently perform these operations. Basically, we need to atomically decrement (with UPDATE) the count of a single database row without deadlocking and without two processes/threads ever e.g. starting with a count of 100 and both trying to decrement it to 99. My naive approach would be this: with transaction.atomic(): cursor = connection.cursor() cursor.execute('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE') Quota.objects.filter(obj=instance).update(count=F('count')-1) However, I'm not sure if this is subject to this issue, from the linked article: if at COMMIT the database cannot determine that the transaction could have been performed serially with respect to the read/writes of other transactions, then it will fail with a … -
PostgreSQL synchronous stored procedure execution calls from Django Backend
We have 5 PostgreSQL stored procedures and we need them to be chronologically executed in order. We have them listed in one stored procedure: CREATE PROCEDURE main(input_file_path varchar) LANGUAGE 'plpgsql' begin as $$ CALL get_input_file(input_file_path); CALL gla_first_step(); CALL glab_first_step(); CALL jet_first_step(); CALL completeness(); end; $$ We need gla_first_step procedure to be called after get_input_file procedure is done etc We have tried using PERFORM as was suggested by GPT but that brought the following error: ERROR: get_input_file(character varying) is a procedure LINE 1: SELECT get_input_file(input_file_path) ^ HINT: To call a procedure, use CALL. We have tried calling them separately from our backend with a loop of SELECT 1 to simulate a wait but that also did not work. cur.execute('CALL get_input_file(%s)', [path]) result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() cur.execute('CALL CALL gla_first_step()') result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() cur.execute('CALL glab_first_step()') result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() cur.execute('CALL jet_first_step()') result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() cur.execute('CALL completeness()') result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() -
What is non_field_errors?
I use forms.Form and forms.ModelForm {% if form.non_field_errors %} {% for err in form.non_field_errors %} <span style="color:darkred;">{{ err }}</span><br /> {% endfor %} {% endif %} Show nothing {{ form.errors }} Show everything,clean_fields() and form. -
I am getting this error django.core.exceptions.FieldError: Unsupported lookup 'icontains' for ForeignKey or join on the field not permitted
Below is models.py: class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def __str__(self): return self.first_name + ' ' + self.last_name class Book(models.Model): title = models.CharField(max_length=100) rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) author = models.ForeignKey(Author,on_delete=models.CASCADE,null=True) is_bestselling = models.BooleanField(default=False) slug = models.SlugField(default="",null=False,blank=True) def get_absolute_url(self): return reverse("model_detail", args=[self.slug]) def __str__(self): return self.title Below is admin.py: class BookAdmin(admin.ModelAdmin): list_display = ('title', 'rating', 'author','is_bestselling',) list_display_links = ('title', 'rating',) search_fields = ('title', 'rating','author',) list_filter = ('rating', 'is_bestselling',) prepopulated_fields = { 'slug': ('title',) } class AuthorAdmin(admin.ModelAdmin): list_display = ('first_name', 'last_name',) list_display_links = ('first_name', 'last_name',) search_fields = ('first_name', 'last_name',) I was trying to search Author in my Books Model. Update: This is answer below : To resolve this issue, you can modify the search_fields attribute to search on related fields of the Author model instead. Here's an updated version of my BookAdmin class: class BookAdmin(admin.ModelAdmin): list_display = ('title', 'rating', 'author', 'is_bestselling',) list_display_links = ('title', 'rating',) search_fields = ('title', 'rating', 'author__first_name', 'author__last_name',) list_filter = ('rating', 'is_bestselling',) prepopulated_fields = { 'slug': ('title',) } In the modified search_fields, 'author__first_name' and 'author__last_name' are used to search on the first_name and last_name fields of the related Author model. The __ syntax is used to traverse the relationship between Book and Author models. By specifying the … -
I cannot pass the values between the methods in classBasedView
I need to pass the bundle and the message values to get_context_data() method, but I cannot figure out how to do it. In this instance the form is valid when I pass it (I can add the better error handling when I figure out why the data gets updated in the post method, but doesn't in the get_context_data()). The form has just 1 filed and it takes the file. Please help. class FirmwareView(FormView, TemplateView): template_name = "dev_tools/firmware_cbv2.html" form_class = forms.InitialFirmwareForm2 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.bundle = {} self.message = {} def get_success_url(self): return self.request.path def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): if request.FILES: if "file" in request.FILES: file = request.FILES["file"] try: content = json.loads(file.read().decode('utf-8')) folder_name = utils.format_folder_name(content["title"]) units = [] for unit in content["units"]: units.append(unit) self.bundle["units"] = units self.bundle["file"] = { "name": folder_name, "content": json.dumps(content) } self.message = { "type": "info", "content": "The form was parsed successfully" } except Exception as e: print("there was an error", e) return self.form_valid(form) else: print("the form is invalid") return self.form_invalid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["bundle"] = self.bundle context["msg"] = self.message return context def form_valid(self, form): if isinstance(form, forms.InitialFirmwareForm2): return super().form_valid(form) -
Allow Django model to load non specified DB fields
I have non managed model (having managed = False), which has specified only single field. However, DB table contains more fields than specified on model. I would like retrieve ALL fields, even those, which are not specified by Django's model. My Model: from django.db import models class Employee(models.Model): active = models.BooleanField() class Meta: db_table = "employees" managed = False My Employees DB table: |----------------------------------- | id | active | address | |----------------------------------- | 1 | true | Dolphins street 5 | |----------------------------------- | 2 | false | Green Avenue 1/C | |----------------------------------- What I want: e = Employees.objects.first() print(e.address) # Will return "Dolphins street 5" The problem: e = Employees.objects.first() print(e.address) # Will raise in Attribute error I don't want to specify Employee.address field, because Django would force me to specify max_length. However, max_length is irrelevant for my application, because my model has managed = False. Moreover, DB definition of employees table is managed by third party software. -
coverage won't test the whole files test coverage right?
I'm trying to understand if we we have lot of services file written in the Djano project. We're writing the tests using pytest framework. I have a question related to this command coverage run -m pytest && coverage report && coverage xml So the coverage will not show all the files which has not test cases it will just show the file you have written the test for and how much you have written(in percentage)? is my understanding correct? Can we see somehow for all the files it hasn't covered yet. I tried running the command but its only showing me for one file can someone explain me here -
The rewind slider does not work on the video when trying to replay via Html5 Django
I tried to do video hosting on Django and play videos using Html5, but the video cannot be rewound, the problem disappears after the page is reloaded post.html {% extends 'main/base.html' %} {% block content %} <link href="https://vjs.zencdn.net/7.14.3/video-js.css" rel="stylesheet" /> <script src="https://vjs.zencdn.net/7.14.3/video.min.js"></script> <div class="container"> {% for p in post %} <h1>{{p.title}}</h1> <div> <video id='my-video-{{p.id}}' class='video-js' controls preload='none' width='640' height='264'> {% if door == "1" %} <source src="{{ p.video_door_1.url }}" type="video/mp4"> {% else %} <source src="{{p.video_door_2.url }}" type="video/webm"> {% endif %} <p class='vjs-no-js'> Чтобы посмотреть это видео, пожалуйста, включите поддержку JavaScript и обновите свой браузер. </p> </video> <div> <button onclick="changeSpeed('my-video-{{p.id}}', 0.5)">0.5x</button> <button onclick="changeSpeed('my-video-{{p.id}}', 1)">1x</button> <button onclick="changeSpeed('my-video-{{p.id}}', 1.5)">1.5x</button> <button onclick="changeSpeed('my-video-{{p.id}}', 2)">2x</button> <button onclick="changeSpeed('my-video-{{p.id}}', 5)">5x</button> </div> </div> <script> // Инициализация плеера Video.js для каждого видео var player = videojs('my-video-{{p.id}}', { // Настройки плеера }); function changeSpeed(playerId, speed) { // Получение объекта плеера по его идентификатору var targetPlayer = videojs(playerId); // Определение и установка новой скорости воспроизведения targetPlayer.playbackRate(speed); } </script> {% endfor %} </div> {% endblock %} views.py def show_post(request, post_slug, door): post = Avtobus.objects.filter(slug=post_slug) context = { 'post': post, 'menu': menu, 'door': door, 'title': 'Видео', } return render(request, 'main/post.html', context=context) -
what is React py and in how much time it will be stable?
React.py is a Python library that enables developers to build web applications using the principles and concepts of React, a popular JavaScript library for building user interfaces. React.py allows developers who are more comfortable with Python to leverage the benefits of React without having to write JavaScript code. At the time of my knowledge cutoff in September 2021, React.py was not a widely recognized or established library in the Python ecosystem. It is important to note that the development of open-source libraries and frameworks can be unpredictable, and it is difficult to determine an exact timeline for when a particular library will reach a stable version. However, typically, the stability of a library depends on factors such as community adoption, active maintenance, and the resolution of any reported issues or bugs. Therefore, it is advisable to check the latest updates and releases from the React.py community to assess the current status and stability of the library. Regarding the differences between React.py and React.js, the key distinction lies in the programming language used. React.js is primarily used with JavaScript, while React.py enables the use of Python for building web applications with React concepts. While React.js has a large and established ecosystem, … -
How to make given url path restful
/account/admin/otp /account/admin/otp/verification /account/delegate/otp /account/delegate/otp/verification /account/refresh-token /account/register-delegate /account/delegate-types /account/delegate-proof-documents In here account is the app name in Django and the there is User model and I try to provide the separate endpoint for the delegate and admin login