Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What kind of security should I implement in my Django REST API if it doesn't require authentication?
It's my first time building an API and it only processes GET requests. What kind of security would be necessary for this project? Other than using the .gitignore file and making sure my database key is hidden do I need to further secure the database for production? My project uses Django, Django REST, and PostgreSQL. I haven't yet found a host I like enough to deploy to so any recommendations would be appreciated. -
django.db.utils.OperationalError: (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)")
I am trying to dockerize my Django project which includes a MySQL database and nginx. When I run the command docker-compose up --build, I receive the following error: django.db.utils.OperationalError: (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)"). This is my docker-compose.yml file: version: '3.7' services: app: build: ./app env_file: - .env container_name: app restart: always expose: - 8000 command: bash -c "python3 manage.py collectstatic --noinput && python3 manage.py migrate --noinput --fake-initial && \ gunicorn -b 0.0.0.0:8000 veblog.wsgi" environment: - MYSQL_DATABASE=${NAME} - MYSQL_USER=${USER_NAME} - MYSQL_PASSWORD=${PASSWORD} - MYSQL_HOST=sqldb mem_limit: 1g depends_on: - sqldb # - nginx volumes: - ./volumes/app:/app - type: bind source: ./volumes/media target: /app/media - type: bind source: ./volumes/static target: /app/static nginx: build: ./nginx container_name: nginx restart: always ports: - 8000:80 sqldb: image: mysql:latest container_name: sqldb restart: always depends_on: - nginx expose: - 3306 environment: - MYSQL_DATABASE=${NAME} - MYSQL_USER=${USER_NAME} - MYSQL_PASSWORD=${PASSWORD} - MYSQL_ROOT_PASSWORD=${ROOT_PASSWORD} - MYSQL_INITDB_SKIP_TZINFO=true - MYSQL_INIT_COMMAND=SET GLOBAL host_cache_size=0; volumes: - type: bind source: ./volumes/dbdata target: /var/lib/mysql - /usr/share/zoneinfo:/usr/share/zoneinfo:ro This is my Dockerfile in the app directory: FROM python:3 ENV PYTHONDONTWRITEBYCODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /app WORKDIR /app COPY . . RUN apt update RUN apt install gcc python3-dev musl-dev -y RUN pip install --upgrade … -
How to find overlapping with a given start_time and end_time (Weekday/Hour format)
I am attempting to determine overlapping availability for a specialist based on their stored availability, which is stored as a datetime due to timezone changes, but only the weekday and time portion is used. When searching for availabilities, I search them as isoweekday and time. However, I am facing issues when the start time is greater than the end time or the start day is greater than the end day. Here is my SpecialistAvailability model: class SpecialistAvailability(BaseModel): """ Model to store the availability of a specialist """ specialist = models.ForeignKey(Specialist, on_delete=models.CASCADE, null=False, blank=False) start_time = models.DateTimeField(null=False, blank=False) end_time = models.DateTimeField(null=False, blank=False) objects = SpecialistAvailabilityManager() I am using pytz and Django to filter for overlapping availability for a specialist as such: import pytz from django.db import models from django.db.models import Q, F class SpecialistAvailabilityManager(models.Manager): """ Manager for SpecialistAvailabilityDay model """ def get_overlapping_availability(self, specialist, start_time, end_time): """ Method to get overlapping availability of a specialist """ start_day = start_time.isoweekday() end_day = end_time.isoweekday() start_time = start_time.time() end_time = end_time.time() initial_availabilities = self.filter(specialist=specialist) if start_day > end_day: day_availabilities = initial_availabilities.filter( Q(start_time__iso_week_day__gt=F('end_time__iso_week_day')) | Q(start_time__iso_week_day__lte=end_day) | Q(end_time__iso_week_day__gte=start_day) ) else: day_availabilities = initial_availabilities.filter( Q(start_time__iso_week_day__gt=F('end_time__iso_week_day'), start_time__iso_week_day__lte=end_day) | Q(start_time__iso_week_day__gt=F('end_time__iso_week_day'), end_time__iso_week_day__gte=start_day) | Q(start_time__iso_week_day__lte=end_day, end_time__iso_week_day__gte=start_day) ) if start_time > end_time: availabilities … -
New to django, django server not loading home page
I started a Django project and went through the regular setup process: I used the "startproject" command to create a project named "social_clone_project", and I used "startapp" to create an app named "accounts". Then I created a "views.py" file and set up the "urls.py" file. Here's what it looks like: from django.contrib import admin from django.urls import path, include, re_path from . import views urlpatterns = [ re_path(r'^$', views.HomePage.as_view(), name='home'), path("admin/", admin.site.urls), ] Recently, I switched to Ubuntu Debian with the sublime-text editor. I'm new to the Ubuntu OS, and whenever I run the "runserver" command, the default "Congratulations!" page loads instead of my home page. I've created an "index.html" file, which is supposed to load as the home page, but it's not working. Can someone help me solve this issue? -
how to get values from a context (object ) dinamically in django templates
I'm a newbie in django and I'm trying to get values from an object dynamiclly in the template directly, but nothing seems to work: this is what I have in the django template: {% for key, value in edit.changes.items %} <p>{{ translator.get(key) }}</p> I also tried this: {% for key, value in edit.changes.items %} <p>{{ translator[key] }}</p> this is the view: def medical_record_edit_list(request, pk): translator = { "appointment_date" :"Fecha", "diagnosis_type" : " Tipo de Diagnóstico", "main_diagnosis" : "Diagnóstico Principal (CIE-10)", "related_diagnosis" : "Diagnóstico Relacionado (CIE-10)", "objective" : "Objetivo", "mental_exam" : "Exámen Mental", "development" : "Desarrollo", "employed_interventions" : "Intervenciones Utilizadas", "evaluation_instruments" : "Instrumentos de Evaluación", "agreements" : "Acuerdos", "therapeutic_work" : "Expectativas de la Consulta", "evaluation_instruments" : "Instrumentos de Evaluación", "remission" : "Remisiones y Contrarremisiones", "finality" : "Finalidad", "external_cause" : "Causas Externas", "conduct" : "Conducta", "exit_state" : "Estado de Salida", "exit_diagnosis" : "Diagnóstico de Egreso (CIE-10)", "exit_condition" : "Condición de Salida" } medical_record_entry = MedicalRecordEntry.objects.get(pk=pk) edit_list = MedicalRecordEdit.objects.filter(medical_record_entry=medical_record_entry).order_by("edit_date") return render(request, 'medical_record/medical_record_edit_list.html', {'edit_list':edit_list, 'medical_record_entry':medical_record_entry, 'translator': translator}) I'm just trying to get what something like: {{ context.appointment_date }} outputs but for each key of the for loop that I have above -
Define database models for webapp about event in django
I'm trying to build an web app about events in python django. Basically, users can see which events will happen or happened and also their dates, locations, etc. But the problems are in relations. So, I've created accounts, events, boardgames, frp, mtg apps in django. Here is the I've coded models. ## for accounts class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return f"{self.username}" ## for events class Event(models.Model): name = models.CharField(max_length=256, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.CharField(max_length=256, unique=True) organizer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='organized_events') date = models.DateTimeField() location = models.CharField(max_length=256, unique=True) attendees = models.ManyToManyField(User, through='EventMember') situation = models.BooleanField(default=True) def get_absolute_url(self): return reverse('events:single', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name class EventMember(models.Model): event = models.ForeignKey(Event, related_name='event_memberships', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_events', on_delete=models.CASCADE) def __str__(self): return self.user.username Bu I want to build the models roughly like this: diagram How can I build these models and how can I code views for them ? I also think you dream what kind of webapp is this. I'm open to every kind of suggestions. Thanks. -
Styling the can_delete form checkbox in model formset factory django
forms.py from .models import Bacteria, Citation from django.forms import ModelForm, modelformset_factory, from django import forms class CitationForm(ModelForm): citation = forms.CharField(label=False) citation.widget.attrs.update({'class' : 'form-control','placeholder': 'Source'}) class Meta: model = Citation fields = ('citation',) widgets = {'citation': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Add Reference'}) } CitationFormset = modelformset_factory(Citation, form=CitationForm, extra=0, can_delete=True) For each form instance in the model form set factory, the check box which sets a form in the formset works perfectly fine but has default styling. Is there any way to style the check box and I know the input field is named "DELETE" but I do not know how to style and give the class (for the checkbox for each form) that I want. -
How to properly generate thumbnail image in Django project?
In my Django project, I need to generate thumbnail images to display them on the main page to avoid a long loading page. But somewhy I got the error Exception class django.db.utils.DataError when adding a new post. Could someone advise me on what's wrong and how to solve it? In my code, first, I save a new post, then I generate a thumbnail as well as resize the original image because it may be huge especially uploaded from iPhone. Here is the code: class Post(models.Model): title = models.CharField(max_length=100, validators=[profanity]) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField(validators=[profanity]) image = models.ImageField(upload_to='diary/images/', blank=True) thumbnail = models.ImageField(upload_to='diary/images/thumbnails/', blank=True, null=True, editable=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) published = models.BooleanField(default=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.image: # Load the image using OpenCV img = cv2.imread(self.image.path) # Generate the thumbnail image thumbnail_size = (200, 200) thumbnail_image = cv2.resize(img, thumbnail_size) thumbnail_path = self.image.path.replace('diary/images/', 'diary/images/thumbnails/') cv2.imwrite(thumbnail_path, thumbnail_image) self.thumbnail.name = thumbnail_path super().save(*args, **kwargs) # Get the dimensions of the image height, width = img.shape[:2] # Set the maximum size of the image max_size = 2000 # Determine the scaling factor to use for resizing the image if height > max_size or width > max_size: scale_factor = max_size … -
ResultMissing when performing a Dramatiq task
For my project (Django-based online shop backend) I implemented a simulated order payment. For practice I decided to use Dramatiq to practice with asynchronous task execution. Here is my code (app_payment/views.py): from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from tasks import post_func_for_payment, backend class PaymentAPIView(APIView): def post(self, request, *args, **kwargs): result = post_func_for_payment.send(request.data, kwargs['id']) response = result.get_result(backend=backend) data_dict = response['data'] return Response(data=data_dict, status=status.HTTP_200_OK) app_payment/tasks.py: import os import django from rest_framework.response import Response from dramatiq.results import Results from dramatiq.results.backends import RedisBackend import dramatiq backend = RedisBackend() broker = dramatiq.get_broker() broker.add_middleware(Results(backend=backend)) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "megano.settings") django.setup() from app_order.models import Order @dramatiq.actor(store_results=True) def post_func_for_payment(data, id): order = Order.objects.get(pk=id) number = data['number'] if int(number[-1]) % 2 != 0 or len(number) != 16: order.status = 'Unpaid' return Response(status=400) data_dict = { "number": number, "name": data['name'], "month": data['month'], "year": data['year'], "code": data['code'] } order.status = 'Paid' order.save() return {'status': order.status, 'data': data_dict} Part of the settings.py code: DRAMATIQ_BROKER = 'dramatiq.brokers.rabbitmq.RabbitmqBroker' DRAMATIQ_BROKER_URL = 'amqp://guest:guest@localhost:5672//' DRAMATIQ_RESULT_BACKEND = "dramatiq.results.backends.redis.RedisBackend" REDIS_HOST = 'localhost' REDIS_PORT = 6379 DRAMATIQ_REDIS_BACKEND_CONFIG = { "url": f"redis://{REDIS_HOST}:{REDIS_PORT}", } However, I get the following error when I try to pay for the order: Internal Server Error: /api/payment/26 Traceback (most recent call last): File "/mnt/c/Users/Victor/PycharmProjects/python_django_diploma/my_venv/lib/python3.10/site-packages/django/core/handlers/exception.py", … -
Many to many field for multiple user type in Django
I am trying to create multiple User types where a single user can be of multiple types. This is the model class I am using: class Role(models.Model): ''' The Role entries are managed by the system, automatically created via a Django data migration. ''' STUDENT = 1 TEACHER = 2 SECRETARY = 3 SUPERVISOR = 4 ADMIN = 5 ROLE_CHOICES = ( (STUDENT, 'student'), (TEACHER, 'teacher'), (SECRETARY, 'secretary'), (SUPERVISOR, 'supervisor'), (ADMIN, 'admin'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True) def __str__(self): return self.get_id_display() class User(AbstractUser): roles = models.ManyToManyField(Role) When I create user from the django admin panel, the roles field should allow me to select multiple user types but instead, it shows me a blank box.Image of the admin panel. -
django all auth file path installed locally?
I am trying to locate the location of django all auth package within my project. I installed it with an active virtual environment and ran a command to see the file path and its file path is /usr/local/lib/python3.11/site-packages/allauth/init.py. This looks like its installed locally. I tried installing with pip3 install django-allauth when virtual environment was active. Why isnt this installed within the lib folder in my virtual environment along with django? -
How to efficiently manage nested serializer in DRF?
This is my overrided get method inside APIView, that returns post's detail page: def get(self, request, *args, **kwargs): post_instance = self.get_object() comments = Comment.objects.detail().filter(post=post_instance, comment_to_reply=None)[:5] post_serializer = self.serializer_class(post_instance) comments_serializer = self.comment_serializer_class(comments, many=True) return Response({ 'post': post_serializer.data, 'comments': comments_serializer.data }) It creates only 13 queries in DB without duplicates, but I want to serialize comments inside PostSerializer without overriding it in APIView every time. detail() here is method inside custom manager that select_related and prefetch_related my query. This is the most important part of my PostSerializer: class PostSerializer(TaggitSerializer, serializers.ModelSerializer): author = LightUserSerializer(read_only=True) ... other fields def get_comments(self, instance): comments = Comment.objects.detail().filter(post=instance, comment_to_reply=None)[:5] comments_serializer = CommentSerializer(comments, many=True) return comments_serializer.data def to_representation(self, instance): representation = super().to_representation(instance) representation['comments'] = self.get_comments(instance) return representation It basically the same lines of code from APIView, but in serializer. I get comments inside get_comments function and include it inside Response object through to_representation. It works, but the problem is that this method creates 16 duplicating queries. 25 queries overall. If I use it like SerializerMethodField it works the same way. -
Backend Deveopment practice project
How can we create a project that can be used to store notes which can be textual, audio or video. Where the system can have many users who can share notes amongst them.Should create a backend project for pratacticing the fucntional REST apis. The database can be sqlite for testing the api functionality.The major functionality i need is to store the notes and query the stored notes. I have been trying to do build a project and need some ideas which will help me to prepare a better product -
Django CustomUser with OneToOne realtion has no USERNAME_FIELD when creating a new one
So I have a CustomUserModel and I'm using that to create my extended models models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' class Role(models.TextChoices): ADMIN = 'ADMIN', 'Admin', COMPANY = 'COMPANY', 'Company', STUDENT = 'STUDENT', 'Student' base_role = Role.ADMIN role = models.CharField(max_length=50, choices=Role.choices) objects = CustomUserManager() def save(self, *args, **kwargs): if not self.pk: self.role = self.base_role return super().save(*args, **kwargs) def __str__(self): return self.email class UserCompanyManager(BaseUserManager): def get_queryset(self, *args, **kwargs): results = super().get_queryset(*args, **kwargs) return results.filter(role=User.Role.COMPANY) class UserCompany(User): base_role = User.Role.COMPANY company = UserCompanyManager() class Meta: proxy = True class Company(models.Model): user = models.OneToOneField(UserCompany, on_delete=models.CASCADE) company_name = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.company_name My form looks like this class CompanySignUpForm(UserCreationForm): company_name = forms.CharField(widget=forms.TextInput) password1 = forms.CharField(label="Password", widget=forms.PasswordInput) password2 = forms.CharField( label="Password confirmation", widget=forms.PasswordInput ) class Meta: model = UserCompany fields = ['email', 'company_name'] def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise ValidationError("Passwords don't match") return password2 @transaction.atomic def save(self, commit=True): # Save the provided password in hashed format user = super().save(commit=False) user.is_active = True user.set_password(self.cleaned_data["password1"]) print('User created! ', user) if commit: user.save() … -
Is it possible to extend or override Wagtail views?
I'm interested in adding some functionality to my wagtail blog to automatically post to social media when a post is published. Normally, the place to do this would be in the view. I did find an app on github called wagtail_share_social but it has not been updated in 2 years, and I would rather not be reliant on a third party solution. The Wagtail documentation has notes on extending views, but they seem to be limited to extending admin views, or views used in the dashboard rather than for serving up pages to non-logged in users. Is it possible to extend or override the Wagtail views for serving non admin pages? If not, what would be the correct approach to add functionality when a page is served via Wagtail? -
Im learning django on Youtube. However, I got the error that i dont know how to solve [closed]
On the terminal, when i type "python3 manage.py runserver", and it appears this /Library/Frameworks/Python.framework/Versions/3.11/Resources/Python.app/Contents/MacOS/Python: can't open file '/Users/daotronggiabao/Downloads/PyShop/manage.py': [Errno 2] No such file or directory here is a manage.py: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pyshop.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == "main": main() it supposes to show me the link of the web as the video shows. please someone help me, im desperately with this problem and have no clues why it happens. Thank you so much for your help -
Django form not updating files/images
I've build a form that works just fine for creating new objects. I can also update all the text fine. It does not let me update images. I am using Crispy Forms to build the form. Where did I make a mistake? My model looks like this: class Bottle(models.Model): class displaySorting(models.IntegerChoices): Lighthouse = 1 Regular = 2 name = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE) sorting = models.IntegerField(choices = displaySorting.choices,verbose_name='Sort order') brand = models.ForeignKey(Brand, on_delete=models.CASCADE) bottle_size = models.IntegerField(validators=[MaxValueValidator(9999)]) info = HTMLField() tasting_notes = HTMLField() abv = models.DecimalField(max_digits=3, decimal_places=1, verbose_name='Alcohol %') image = ResizedImageField(size=[1000,1000], upload_to=image_upload_handler) thumbnail = models.ImageField(upload_to='thumbnails') shop_link = models.URLField() consumer_shop_link = models.URLField() website_link = models.URLField() def save(self, *args, **kwargs): self.slug = slugify(f"{self.brand}-{self.name}") output_size = (300, 169) output_thumb = BytesIO() img = Image.open(self.image) img_name = self.image.name.split('.')[0] if img.height > 300 or img.width > 300: img.thumbnail(output_size) img.save(output_thumb,format='JPEG',quality=90) self.thumbnail = InMemoryUploadedFile(output_thumb, 'ImageField', f"{self.brand}-{img_name}_thumb.jpg", 'image/jpeg', sys.getsizeof(output_thumb), None) super(Bottle, self).save() My view looks like this: @login_required def bottle_update_view(request, id=None): object = get_object_or_404(Bottle, id=id) form = BottleForm(request.POST or None, instance=object) context = { 'form':form, 'object':object } if form.is_valid(): form.save() context['message'] = 'Data saved' return render(request,'Academy/bottle_crud.html',context) and finally my template like this: {% block content %} <div class='container'> <div class='row form'> <h1 class='text-center my-5'>Add & Update bottle</h1> … -
How to resolve django rest_framework error "Method \"POST\" not allowed."?
sorry I'm still a beginner on django I would like to create an enpoint with django rest_framework allowing me to create an HD wallet and backup in database, but I have an error: "Method "POST" not allowed ." So I created this model that represente hdwallet: from typing import Any from django.db import models, transaction from django.contrib.auth.models import User class HDWallet(models.Model): """HDWallet class""" date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) name: str = models.CharField(max_length=255, unique=True) private_key: str = models.CharField(max_length=100, unique=True) address: str = models.CharField(max_length=100, unique=True) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="wallet", ) active = models.BooleanField(default=True) def __str__(self) -> str: return self.name @transaction.atomic def disable(self) -> Any: if self.active is False: # Ne faisons rien si la wallet est déjà désactivée return self.active = False self.save() self.currencies.update(active=False) also I created my serializers class: class HDWalletSerializer(ModelSerializer): class Meta: model = HDWallet fields = "__all__" def post(self, request: Request) -> Any: user = User.objects.get(username=request["username"]) name = f"{user.username}_{user.id}" wallet = Wallet.create(name) if user is not None: hdwallet = HDWallet.objects.create( { "name": name, "private_key": wallet.get_key(), "address": wallet.get_key().address, "user": user.id, } ) else: raise Exception("use do not exist") return Response( { "status": 201, "message": "wallet have been successfully created!", "data": hdwallet, } ) and my view in … -
How to create a swagger hub service in django
I have a django project that contains multiple django microservices. Let's say that there are two services named "base" and "order" these two services have paths like this: in "base" microservice: from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView path('base/schema/', SpectacularAPIView.as_view(), name='schema'), path('base/swagger/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), and in "order" microservice: from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView path('order/schema/', SpectacularAPIView.as_view(), name='schema'), path('order/swagger/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), I want to create a new django microservice that collect all these documentations and put them in one url. how can I do this? -
ModuleNotFoundError: No module named 'core' in django
i installed latest version of django and created project and when i run server than this error occure may be its latest verion of django problem but how to solve this i try to find solution but not able to solve ModuleNotFoundError: No module named 'core' ModuleNotFoundError: No module named 'core' -
Django admin filter tabularInline field choices based on modelAdmin field
I am using this post to limit the choices in my related "tabularInline" field. class inlineUsages(admin.TabularInline): model = Usage extra = 0 def formfield_for_foreignkey(self, db_field, request=None, **kwargs): print(db_field.name) print(kwargs) if db_field.name == "project": kwargs["queryset"] = Project.objects.filter(task='Project 3') return super(inlineUsages, self).formfield_for_foreignkey(db_field, request, **kwargs) class fteAdmin(admin.ModelAdmin): inlines = (inlineUsages,) admin.site.register(FTE, fteAdmin) Both the FTE model and Usage model reference a foreign key "project" on the "Project" model. My filtering is correctly working, but currently (as you see in the code) I can only hard code the Project name (field is called "task"). I want to be able to filter the choices of my Usage project field based on the value of the FTE project field. I am not sure how to pass the relation between models. Any help is appreciated! Below is the current view in the django admin portal -
Advice sought on obsolete application in Django
We have a Django app without any content now (we have moved the models to another app), and the only thing left is the migrations I tried removing the migrations, however we have migrations in other apps that have dependancies on the app we wish to remove Is there any advice / guidance on removing apps in Django? -
How to deploy django app with channels and websocket on cpanel?
i have a django with websocket and channels wokring locally using daphne and i want to deploy it to cpanel ? I try to use : a2wsgi but it didn't work i want to know if cpanel works with asgi application? and if there is another way to deploy it with cpanel -
ModelChoiceField shows objects instead on contents
How can I change my code to show contents instead of objects ? forms.py: unit_set = AnalysisVariableUnit.objects.all() for unit in AnalysisVariableUnit.objects.all(): print(unit.__dict__) class AnalyysimuuttujaForm(forms.Form): technical_name = forms.CharField(required=False, widget=forms.TextInput( attrs={ 'class':'readonly_able tn' } )) decimals = forms.ChoiceField(choices=CHOICES_DS) decimals_format = forms.ChoiceField(choices=CHOICES_DS) units = forms.ModelChoiceField( required=False, widget=forms.Select, queryset=unit_set, ) this outputs: {'_state': <django.db.models.base.ModelState object at 0x7f2038ea51d0>, 'id': 1, 'contents': 'indeksipisteluku'} {'_state': <django.db.models.base.ModelState object at 0x7f2038ea5240>, 'id': 2, 'contents': '%'} I want to have 'indeksipisteluku' and '%' as selectables in my drop down, which now shows: -
Pytest and playwright - multilpe browsers when using class-scoped fixtures
I want to run a pytest playwright test with multiple browsers - e.g. pytest --browser firefox --browser webkit This works for function-based tests like this one: import pytest from playwright.sync_api import Page @pytest.mark.playwright def test_liveserver_with_playwright(page: Page, live_server): page.goto(f"{live_server.url}/") # etc. The test is executed twice, once per browser setting. However, I also want to use class-based tests, for which I use a fixture on a base class: import pytest import unittest from playwright.sync_api import Page @pytest.mark.playwright class PlaywrightTestBase(unittest.TestCase): @pytest.fixture(autouse=True) def playwright_liveserver_init(self, page: Page, live_server): self.page = page # etc. class FrontpageTest(PlaywrightTestBase): def test_one_thing(self): self.page.goto("...") # etc The test runs, but only once - the multiple browser settings are ignored. What am I missing - is there a way to get the multiple runs in such a setup as well ?