Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
what is the most efficient way of running PLaywright on Azure App Service
I am hosting Django application on Azure that contains 4 Docker images: Django, React, Celery beats and Celery worker. I have celery task where use can set up python file and run Playwright. Question What is the best way to run Playwright. Ascan see in my Dockerfile below I am installing chromium usuing playwright install but I am not sure if it is the best approach for this solution: FROM python:3.9 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 RUN apt-get update && apt-get -y install netcat && apt-get -y install gettext RUN mkdir /code COPY . /code/ WORKDIR /code RUN pip install --no-cache-dir git+https://github.com/ByteInternet/pip-install-privates.git@master#egg=pip-install-privates RUN pip install --upgrade pip RUN pip_install_privates --token ${GITHUB_TOKEN} /code/requirements.txt RUN playwright install --with-deps chromium RUN playwright install-deps RUN touch /code/logs/celery.log RUN chmod +x /code/logs/celery.log EXPOSE 80 -
why the signals don't work = create profile when user register
why the signals don't work = create profile when user register i wannt to know the is ----- settings INSTALLED_APPS = [ 'main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -----model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save # Create your models here. class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) music = models.CharField(max_length=50) skils = models.CharField(max_length=50) search = models.CharField(max_length=50) posts = models.CharField(max_length=50) boi = models.TextField() img = models.ImageField(upload_to="profile-img") def __str__(self): return self.user def create_profile(sender, **kwargs): if kwargs['created']: user_profile = profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) why code dont work why code dont work -
Very slow database query migrating from django 1.8 to django 3.2
I migrated a project from django1.8 to django3.2. I'm using the same database but the function I use to build a report is four times slower (8 seconds on Django1.8 and 30/40 seconds with django3.2). The database is MySQL version 5.7 (I also tried version 8.0.32 but nothing changed). This is the query: qs = PartitaDanno.objects.filter(incarico__cliente_intestatario_fattura_id=8006 ).select_related('incarico', 'anagrafica_assctp', 'incarico__naturaincarico' ).prefetch_related('rate' ).order_by('-incarico__anno', '-incarico__numero', 'pk') PartitaDanno is a table with 16000 rows and the model has 215 fields (I know..I didn't write it). The result of this query are just 1700 rows..a very small result. The unusual thing is that even if I use a simple query on this model like qs = PartitaDanno.objects.filter(incarico__cliente_intestatario_fattura_id=8006) It takes 20 seconds to iterate through result of this basic query..I don't understand. The raw sql query is the same in both versions of Django. This is the first queryset raw query: SELECT `sinistri_partitadanno`.`id`, `sinistri_partitadanno`.`created`, `sinistri_partitadanno`.`modified`, `sinistri_partitadanno`.`incarico_id`, `sinistri_partitadanno`.`tipo`, `sinistri_partitadanno`.`tipologia_controparte`, `sinistri_partitadanno`.`fase`, `sinistri_partitadanno`.`competenza_giurisdizionale`, `sinistri_partitadanno`.`soggetto`, `sinistri_partitadanno`.`anagrafica_assctp_id`, `sinistri_partitadanno`.`luogo`, `sinistri_partitadanno`.`compagnia_id`, `sinistri_partitadanno`.`riferimento_compagnia`, `sinistri_partitadanno`.`tipo_di_danno`, `sinistri_partitadanno`.`tipo_lesioni`, `sinistri_partitadanno`.`tipologia_vittima`, `sinistri_partitadanno`.`modello_veicolo`, `sinistri_partitadanno`.`targa_veicolo`, `sinistri_partitadanno`.`riserva_iniziale`, `sinistri_partitadanno`.`riserva_parziale`, `sinistri_partitadanno`.`data_richiesta_danni_ctp`, `sinistri_partitadanno`.`reiezione_cautelativa`, `sinistri_partitadanno`.`data_reiezione_cautelativa`, `sinistri_partitadanno`.`importo_richiesto_da_ctp`, `sinistri_partitadanno`.`data_incarico_nostro_perito`, `sinistri_partitadanno`.`tipologia_perizia`, `sinistri_partitadanno`.`nominativo_perito`, `sinistri_partitadanno`.`data_perizia_negativa`, `sinistri_partitadanno`.`motivazioni_perizia_negativa`, `sinistri_partitadanno`.`data_interlocutoria_inviata_dal_perito`, `sinistri_partitadanno`.`importo_stimato_dal_perito`, `sinistri_partitadanno`.`data_ricezione_perizia_dal_nostro_perito`, `sinistri_partitadanno`.`riparazione_antieconomica`, `sinistri_partitadanno`.`data_incarico_medico_legale`, `sinistri_partitadanno`.`data_ricezione_perizia_dal_nostro_medico_legale`, `sinistri_partitadanno`.`data_invio_offerta_tramite_transazione_quietanza`, `sinistri_partitadanno`.`data_reiezione_indennizzo_risarcimento`, `sinistri_partitadanno`.`pagamento_parziale`, `sinistri_partitadanno`.`capitale`, `sinistri_partitadanno`.`data_pagamento_capitale`, `sinistri_partitadanno`.`anagrafica_patrocinatore_id`, `sinistri_partitadanno`.`tipo_patrocinatore`, `sinistri_partitadanno`.`cf_piva_patrocinatore`, `sinistri_partitadanno`.`numero_rif_patrocinatore`, `sinistri_partitadanno`.`spese_legali`, `sinistri_partitadanno`.`data_pagamento_spese_legali`, `sinistri_partitadanno`.`integrazione_capitale`, `sinistri_partitadanno`.`data_pag_integraz_capitale`, `sinistri_partitadanno`.`integrazione_spese_legali`, `sinistri_partitadanno`.`data_pag_integraz_spese_legali`, `sinistri_partitadanno`.`note_generali`, `sinistri_partitadanno`.`note_pagamenti`, `sinistri_partitadanno`.`cessione_del_credito`, `sinistri_partitadanno`.`veicolo_sostitutivo`, … -
Model not detected by Django, even with `app_label` referencing to an existing app
I have a Django project with an application called data. The app is installed in the INSTALLED_APPS as follows: 'base.apps.MyAppConfig' with the AppConfig: class MyAppConfig(AppConfig): name = 'application' verbose_name = 'My App' label = 'application' path = f"{os.environ.get('APP_DIR')}/application" default = True I have the models defined like this: ### data/models/base/basemodel.py class MyBaseModel(models.Model): # ... fields ... Meta: app_label: `application` However, Django is not finding the models, and if I run makemigrations Django responds No changes detected, and on migrate, the app application does not appear on the Operations to perform. The Model should be detected so the Django detects migrations to apply === Context: Django Application reference: doc Django Models reference: doc -
djagno rest error: Cannot use the @action decorator on the following methods, as they are existing routes
I need to write a viewset for user's profile, in which methods like retrieve do not recieve pk as parameter but get user's id from authentication token. but by writing a new action for this methods: class ProfileViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, GenericViewSet, ): serializer_class = ProfileSerializer def get_object(self): return self.request.user @action(detail=False) def retrieve(self, request, *args, **kwargs): pass this error is raised: Cannot use the @action decorator on the following methods, as they are existing routes ... one way to do this is by writing custom methods: class ProfileViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, GenericViewSet, ): serializer_class = ProfileSerializer def get_object(self): return self.request.user @action(detail=False) def retrieve_profile(self, request, *args, **kwargs): pass but is there a way to avoid this error and still using default methods? -
How to display a docstring in UI with flask?
I am importing a python script into my flask web app as such def register_tasks_in_db(): from haz import tasks as hz tasks = {f'{modname}': importlib.import_module( f'haz.tasks.{modname}') for importer, modname, ispkg in pkgutil.iter_modules(hz.__path__)} with app.app_context(): stored_tasks = Task.query.all() for stored_task in stored_tasks: if stored_task.name in tasks.keys(): _ = tasks.pop(stored_task.name) current_app.logger.info(f'{stored_task.name} already exists in db') for name, obj in tasks.items(): tasks = Task(name=name) tasks.save() app = create_app() app.secret_key = app.config['SECRET_KEY'] worker = create_celery_app(app) # a Celery object register_tasks_in_db() @app.shell_context_processor def make_shell_context(): return {'db': db, 'User': User, 'Institution': Institution, 'Image': Image, 'Series': Series, 'Study': Study, 'Device': Device, 'Task': Task, 'Report': Report} if __name__ == "__main__": app.run(host='0.0.0.0', port=int(os.getenv('PORT', 5001))) Each of this tasks contains a docstring. How do I access and display the dosctring in the UI? -
has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
enter image description here has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response django-restframework -
Django template - global template namespace as parameter value for inclusion tag
I have a Django template for rendering tables which I can successfully include in my other templates. I takes a prefix and a namespace parameter, where the namespace is a key within the rendering context: {% include "table.html" with prefix=name|add:"_" namespace=rubric1 %} and in the template I use e.g.: {% for object in namespace.object_list %} ... {% endfor %} My rendering context looks like this: context = { 'some_var': ..., 'rubric1': { 'object_list': ..., 'direction': ..., 'orderby': ..., 'total': ..., 'page': ..., ... }, 'rubric2': { 'object_list': ..., ... }, } Now I want to use this template in a ListView, where those keys live at the root of the context namespace: context = { 'some_var': ..., 'object_list': ..., 'direction': ..., 'orderby': ..., 'total': ..., 'page': ..., ... } How do I tell the inclusion tag to use the root of the rendering context as namespace? Is there a special variable for this? E.g.: {% include "table.html" with prefix=name|add:"_" namespace=global_template_namespace %} Or can i somehow use a with context? E.g.: {% with global_template_namespace as ns %} {% include "table.html" with prefix=name|add:"_" namespace=ns%} {% endwith%} I have also thought about simple_tag that directly returns the context, but couldn't manage to use … -
How to return form values and upload file at the same time in Django?
I am a beginner at Django. I want to let users fill in Form and upload a file to the specific folder at the same time, and get the form value they filled in. Here is my forms.py from django import forms class UserForm(forms.Form): first_name= forms.CharField(max_length=100) last_name= forms.CharField(max_length=100) email= forms.EmailField() #file = forms.FileField() # for creating file input My functions.py (this function is to let users upload a file to the path 'mysite/upload/'.) def handle_uploaded_file(f): with open('mysite/upload/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) My index.html <head> <meta charset="UTF-8"> <title>User Information Form</title> </head> <body> <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="Submit" name="submit" value="Submit"/> </form> {% if submitbutton == "Submit" %} <h1> Your first name is {{firstname}}</h1> <h1> Your last name is {{lastname}}</h1> <h1> Your email is {{emailvalue}} </h1> {% endif %} </body> <script>'undefined'=== typeof _trfq || (window._trfq = []);'undefined'=== typeof _trfd && (window._trfd=[]),_trfd.push({'tccl.baseHost':'secureserver.net'},{'ap':'cpbh-mt'},{'server':'p3plmcpnl487010'},{'dcenter':'p3'},{'cp_id':'8437534'}) // Monitoring performance to make your website faster. If you want to opt-out, please contact web hosting support.</script><script src='https://img1.wsimg.com/traffic-assets/js/tccl.min.js'></script></html> My views.py from django.shortcuts import render from django.http import HttpResponse from .forms import UserForm from mysite.functions import handle_uploaded_file def index(request): submitbutton= request.POST.get("submit") firstname='' lastname='' emailvalue='' student = UserForm(request.POST, request.FILES) form= UserForm(request.POST or None) … -
Null value error, I am using Django rest framework and when I want to get enrolled data inside login response it gives me null instate of the values
I want to get enrolled courses for individual student with login I put enrolled model inside the login response put it will give me null instate of courses here is me output and code output: { "token": "4b6d75942dbbbcc484fb6c556b1ce6ebf2c73142", "user": { "id": 14, "username": "enrolltestt", "mobile_no": "07746505150", "is_student": true, "device_id": "" }, "is_student": true, "enrolled": [ { "course": null, "student": null, "is_active": false } ] here is my views.py class CustomAuthToken(ObtainAuthToken): def post(self,request,*args,**kwargs): serializer=self.serializer_class(data=request.data, context={'request':request}) serializer.is_valid(raise_exception=True) user=serializer.validated_data['user'] token,created=Token.objects.get_or_create(user=user) enrolled=StudentCourseEnrollSerializer(context=self.get_serializer_context()).data, return Response({ 'token':token.key, 'user':UserSerializer(user, context=self.get_serializer_context()).data, 'is_student':user.is_student, 'enrolled':enrolled }) can someone help me -
Problem serving Django "polls" tutorial under lighttpd: 404 page not found
I am following the Django polls tutorial, which is working 100% with the built-in development server (python3 manage.py runserver). I have set up lighttpd to serve django through UWSGI and that seems to be working fine but for one glitch: the URL passed to django seems to have been modified. My lighttpd configuration is basically this: ... server.modules += ("mod_scgi","mod_rewrite") scgi.protocol = "uwsgi" scgi.server = ( "/polls" => (( "host" => "localhost", "port" => 7000, "check-local" => "disable", )) ) The Django tutorial mapping looks like: # tutorial1/urls.py urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] # polls/urls.py app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] However when I hit http://localhost:8080/polls/ in the address bar, it produces an 404 error. If I add an extra /polls to the URL then it works just fine. My goal with this exercise is to be able to serve this app switching from and to both servers without needing to modify configuration files each time. What do I need to do on the lighttpd.conf side to make lighttpd interchangeable with Django's own internal dev server? I have tried to add the following url.rewrite … -
Django - Iterating over Raw Query is slow
I have a query which uses a window function. I am using a raw query to filter over that new field, since django doesn't allow filtering over that window function (at least in the version I am using). So it would look something like this (simplified): # Returns 440k lines user_files = Files.objects.filter(file__deleted=False).filter(user__terminated__gte=today).annotate( row_number=Window(expression=RowNumber(), partition_by=[F("user")], order_by=[F("creation_date").desc()])) I am basically trying to get the last not deleted file from each user which is not terminated. Afterwards I use following raw query to get what I want: # returns 9k lines sql, params = user_files.query.sql_with_params() latest_user_files = Files.objects.raw(f'select * from ({sql}) sq where row_number = 1', params) if I run these queries in the database, they run quite quickly (300ms). But once I try to iterate over them or even just print them it takes a very long time to execute. Anywhere from 100 to 200 seconds even though the query itself just takes a little bit less than half a second. Is there anything I am missing? Is the extra field row_number in the raw query an issue? Thank you for any hint/answers. (Using Django 3.2 and Python 3.9) -
Django ManyToMany trhough summary calculation
Giving next models: class Question(models.Model): question = models.TextField() output_params = models.ManyToManyField(OutputParam, through='OutputParamWeight') class OutputParam(TimeStampModel): form = models.ForeignKey(Form, on_delete=models.CASCADE, related_name='output_params') name = models.CharField(max_length=255) class OutputParamWeight(models.Model): output_param = models.ForeignKey(OutputParam, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) weight = models.IntegerField() class Answer(TimeStampModel): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') value = models.IntegerField() Every question affects N output params in a form multiplying x1, x2, x3 the associates answer value. For example: Question 1 -> Output param 1 x1 Output param 2 x3 Output param 3 x2 Question 2 -> Output param 1 x2 Output param 3 x3 Answer 1 -> Question 1 Value 2 Answer 2 -> Question 2 Value 3 So, what I'm trying to do now is summarize the form result as follows: Output param 1: 6 (answer1.value * question1.output_param1.weight + answer1.value * question2.output_param1.weight) Output param 2: 15 Which queries should I perform to get the final result in an optimized way? -
ImportError (circular import) in Django
everyone! I need to delete my django app. After I do this, in another app I get ImportError. Apps don't have any connections at all. But if in the first app in models I restore one line with import, everything goes well. My structure app_one/models.py --- need to delete app_two/models.py app_two/service.py app_three/tasks.py When I try to delete everything from app_one/models.py -> ImportError occured. But when I restore one line from app_three.tasks import some_task everything is ok I checked everything - there are no real circular imports in theese three apps If someone faced issue like this, I will appreciate your help I tried to move this import to app_two/apps.py AppsConfig.ready, also I tried to move this import higher to another app which initialized before app_two. Nothing helped -
OpenCV VideoCapture Error in Docker Container (Returns None When Read)
Here is my DockerFile: FROM python:3.10.4 LABEL maintainer="Louis Jefferson Zhang <louis.ljz08@gmail.com>" # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Build Dependencies for Opencv, Dlib and Psycopg2 RUN apt-get update && apt-get install -y \ build-essential \ cmake \ libopencv-dev \ libdlib-dev \ libpq-dev \ && rm -rf /var/lib/apt/lists/* # Installation RUN pip install opencv-python dlib psycopg2 # MAIN WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt COPY ./fr_as . Here is my Docker Compose: version: "3.9" services: web: build: . command: python /code/fr_as/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db devices: - /dev/video0:/dev/video0 privileged: true db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: I built the container using this command: docker-compose up -d --build And an error appeared when running the code below: cap = cv2.VideoCapture(0) _, img = cap.read() Here is the error message: OpenCV(4.7.0) /io/opencv/modules/imgproc/src/resize.cpp:4062: error: (-215:Assertion failed) !ssize.empty() in function 'resize' Looking at the Variable Watch Window, The Values for these variables are: _ = False img = None -
How to filter the latest amended laws in django admin site?
below is the description of models: I have a Law model Each law many Versions Each version has many Translations Each translation has many annotations I want to get the latest amended laws in the django admin site. So, I created a proxy model of Law. and in the the admin file of law I have this: @admin.register(LatestAmendedLaws) class LatestAmendedLawsAdmin(admin.ModelAdmin): list_display = ("id", "rs_number", "created") def get_queryset(self, request): latest_translation_datetime = Translation.objects.latest("created").created return ( super() .get_queryset(request) .filter(created__gte=latest_translation_datetime) ) this script doesn't return the correct latest amended laws. because it filters based on the created field of law. but it should be based on the latest created/updated date of translations that are associated with the law. -
django getlist() function
I have a tags generator for my blog site and every time I enter tags it generates a hidden html input, and it appends whenever I insert a tag like this example below. <input type="hiiden" name="tags" value="<value of inserted tags>"> <input type="hiiden" name="tags" value="<value of inserted tags>"> <input type="hiiden" name="tags" value="<value of inserted tags>"> In my Django view I get all the tags from the form through request.POST.getlist("tags") and save it on database so the inserted tags is like this on database ['value1','value2','value3'] When I fetch the tags in the Django template through for loop to extract the strings from the arrayfield the output shows like this: [ ' v a l u e 1 ' , ' v a l u e 2 ' , ' v a l u e 3 ' ] // one by one character output the code works fine but the problem is it outputs character by character in the array including the brackets and the apostrophe and the commas. What i want to achieve is only the strings which are present in the array field anyone knows what can be the solution for this? any suggestion and help is appreciated. -
django orm group by taking value from order by
query_set = query_set.values('event','cat_type').annotate(cat_count=Count('id')).order_by("event__slug", "cat_type") when I execute the sql query it returns, ... GROUP BY event_id,cat_type,event.slug,cat_type. My question is why it considers the value written in ordey_by as Group by condition?? -
Django - Object of type User is not JSON serializable
I am facing an issue with POSTing data (which has a User object) to a ModelViewSet. Error: "Object of type User is not JSON serializable" data_params = { "log_user_id": user, "device_name": "sampledevice", "log_user_email": "svc.netadc@ads.aexp.com", "feature_name": 'Subnet Automation', } print(data_params, "data_params") response = requests.post("<url>/netadc3/arista/ImplementationLogsAristaViewSet/implementationlogsarista/", auth=(<username>, <password>), headers={"content-type": "application/json"}, data=json.dumps(data_params), verify=False) serializers.py: class ImplementationLogsAristaSerializer(serializers.HyperlinkedModelSerializer): log_user_id = UserSerializer(read_only=True) class Meta: model = ImplementationLogsArista fields = ('log_id','device_name', 'log_user_id','log_user_email','feature_name') Not sure how to successfully POST the data with User into the ModelViewSet. views.py: class ImplementationLogsAristaViewSet(viewsets.ModelViewSet): queryset = ImplementationLogsArista.objects.all().order_by('log_capture_date') serializer_class = ImplementationLogsAristaSerializer permission_classes = (IsAuthenticated,) pagination_class = None -
Optimize Django ORM query to get object if a specific related object does not exist
I have the following table structures: class Library: id = models.CharField(...) bookcase = models.ForeignKey( Bookcase, related_name="libraries" ) location = models.ChoiceField(...) # Other attributes... class Bookcase: # some attributes type = models.ChoiceField(..) class Book: bookcase = models.ForeignKey( Bookcase, related_name="books" ) title=models.CharField(...) status=models.ChoiceField(...) # borrowed | missing | available Say if I want to get all Library objects that does not have a book with title "Foo" that is NOT missing, how can I optimize this query? I have the following: libraries = Library.objects.select_related('bookcase').filter(location='NY', bookcase__type='wooden') libraries_without_book = [] for library in libraries: has_non_missing_book = Book.objects.filter( bookcase=library.bookcase, title="Foo", ).exclude(status='missing').exists() if not has_non_missing_book: libraries_without_book.append(library.id) Unfortunately, this performs an extra query for every Library object that matches the initial filtering condition. Is there a more optimized method I can use here that makes use of prefetch_related in some way? -
Nesting Django QuerySets
Is there a way to create a queryset that operates on a nested queryset? The simplest example I can think of to explain what I'm trying to accomplish is by demonstration. I would like to write code something like MeterReadings.objects.filter(radio=1).objects.filter(meter=1) resulting in SQL looking like SELECT * FROM ( SELECT * FROM MeterReading WHERE radio=1 ) WHERE meter=1; More specifically I have a model representing readings from sensors class Sensor(models.Model): sensor=models.PositiveIntegerField() timestamp=models.DatetimeField() reading=models.IntegerField() With this I am creating a queryset that annotates every sensor with the elapsed time since the previous reading in seconds readings = ( SensorReading.objects.filter(**filters) .annotate( previous_read=Window( expression=window.Lead("timestamp"), partition_by=[F("sensor"),], order_by=["timestamp",], frame=RowRange(start=-1, end=0), ) ) .annotate(delta=Abs(Extract(F("timestamp") - F("previous_read"), "epoch"))) ) I now want to aggregate those per sensor to see the minimum and maximum elapsed time between readings from every sensor. I initially tried readings.values("sensor").annotate(max=Max('delta'),min=Min('delta'))[0] however, this fails because window values cannot be used inside the aggregate. Are there any methods or libraries to solve this without needing to resort to raw SQL? Or have I just overlooked a simpler solution to the problem? -
How to setup django with lighttpd?
I have a live website that is running under lighttpd. I now have a sub-domain that I want to run under django. I do not want to move to Apache as I don't currently have the resources to support two production web servers. The django part is actually working well with the django builtin development server so now I just need to port it into production. It seems that all documentation to setup django with lighttpd is over 10 years old and uses fastcgi that from what I can see was deprecated and removed from django. The new docs point to use wscgi - scgi under lighttpd. But even that is being hard to get any documentation. Do I need to run uwsgi and use that to serve the pages to mod_scgi? Or should I use gunicorn? I am sort of at a loss on what to do. Suggestions welcome! -
Django: How to Filter Model with "where" clause to display in list admin related objects
I have 2 models that depend on each other. One is the "FeatureFilm" model and the other is the "CompanyInvolved" model. In the "FeatureFilm" table I want to store movies and in the "CompanyInvolved" table I want to store the many companies that have contributed to a movie. The "CompanyInvolved" model is attached to the "FeatureFilm" table with a foreignkey. I want to display a column from the CompanyInvolved table in the list view of the FeatureFilm Admin Panel. I have already done that with my code. The only thing I didn't get yet is a filter that filters the CompanyInvolved table on the field "company_role". I want to show only the values that have the company_role = "Production". Can someone please help? many greetings here is my depending code: model.py class ProjectBaseModel(models.Model): title = models.CharField("Titel", max_length=100, blank=False, unique=True) leading_postproduction_id = models.ForeignKey( Company, verbose_name="Federführende Postproduktion", on_delete=models.SET_NULL, blank=True, null=True, ) class FeatureFilm(ProjectBaseModel): class Meta: verbose_name = "Kinofilm" class CompanyInvolved(models.Model): feature_id = models.ForeignKey( FeatureFilm, on_delete=models.CASCADE, null=True, blank=True, ) tv_movie_id = models.ForeignKey( TvMovie, on_delete=models.CASCADE, null=True, blank=True ) company_roll = models.CharField( choices=company_roll, max_length=15, blank=True, help_text="Produktion, Co-Produktion, Kinoverleiher, Sender, Weltvertrieb", ) company_involved = models.ForeignKey( Company, on_delete=models.SET_NULL, null=True, blank=True, ) def __str__(self): return "#" + str(self.pk) … -
TypeError at /crear-cliente/ in Django
Hello there, I'm trying to do a form that can store the customers records, but recently it's throw me this error TypeError at /crear-cliente/ object of type 'int' has no len() C:\Users\G-FIVE\Desktop\practicas y proyectos\mini_erp\MiniErp\customers\views.py, line 43, in register_customer address = address ) customer.save() """ form = FormCustomer(request.POST) if form.is_valid(): … data_form = form.cleaned_data first_name = data_form['first_name'] last_name = data_form['last_name'] cedula = data_form['cedula'] phone_number = data_form['phone_number'] I did the form using the Django classes, I'll show you the code of the form, the view and the model Form code: from django import forms from django.core import validators # Clase para el formulario de registro de clientes class FormCustomer(forms.Form): # Input para el first_name first_name = forms.CharField( label='Nombre', required=True, widget=forms.TextInput( attrs={ 'placeholder':'Ej: John', 'class': 'form-control form-control-user mb-3', 'id': 'first_name' } ), validators= [ validators.MinLengthValidator(3, 'El nombre está incompleto') ] ) # Input para el last_name last_name = forms.CharField( label='Apellido', required=True, widget=forms.TextInput( attrs={ 'placeholder':'Ej: Doe', 'class': 'form-control form-control-user mb-3', 'id': 'last_name' } ), validators= [ validators.MinLengthValidator(3, 'El nombre está incompleto') ] ) # Input para la cédula cedula = forms.IntegerField( label='Cédula', required=True, widget=forms.NumberInput( attrs={ 'placeholder':'xx xxx xxx', 'class': 'form-control form-control-user mb-3', 'id': 'cedula' } ), validators= [ validators.MinLengthValidator(7, 'Faltan números'), validators.MaxLengthValidator(8, 'Has introducido … -
How to make Celery + Django + Pytest work together
Trying to test an endpoint that has a celery task. Celery tasks don't seem to run in the test. django==4.1.5 celery==5.2.7 pytest==7.2.1 pytest-django==4.5.2 An endpoint: def do_some_stuff(blah: Blah) -> Blah: res = cool_task.apply_async(kwargs={ 'cool_id': int(pk), 'config': config, 'name': RESUBMIT.value, }, link=update_status.si( cool_id=int(pk), new_status="why is this so hard", ) ) [...] A test: @pytest.mark.django_db def test_my_thing(django_client: Client) -> None: [...] response = django_client.post(f"/api/myendpoint/{mything.id}/do_some_stuff/") It hits the endpoint. Gets a 202 back as expected. But celery doesn't seem to be picking up the task in the test. The update_status method updates the db, and I'm not seeing that happen. I've tried creating a celery app in the test, creating a worker in the test, changing the test to use the main DB instead of the test db, setting the override_settings to "BROKER_BANDEND='memory'". I'd like a full working example. It seems kind of basic but it's eluding me. I don't understand what combination of fixtures and overrides I need for this to work. Seems to work when I actually call the application.