Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Platform.sh CLI Login Fails with HTTP 500 Error and Symfony Console Error
I’m encountering issues while trying to log in to Platform.sh using the command-line interface (CLI). When I run platform login, the CLI opens a URL in my browser (http://127.0.0.1:5000), but the browser displays an error: “This page isn’t working. 127.0.0.1 is currently unable to handle this request.” The CLI output is: Opened URL: http://127.0.0.1:5000 Please use the browser to log in. Help: Leave this command running during login. If you need to quit, use Ctrl+C. If I try to run platform create without logging in, the CLI prompts me to log in. When I confirm, I receive a fatal error: If I try to run platform create without logging in, the CLI prompts me to log in. When I confirm, I receive a fatal error: Fatal error: Uncaught Error: Class "Symfony\Component\Console\Event\ConsoleErrorEvent" not found in phar://C:/Users/Макар/AppData/Local/Temp/platformsh-cli-8.2.26-4.22.0/phar-4.22.0/vendor/symfony/console/Application.php:1027 Stack trace: #0 phar://C:/Users/Макар/AppData/Local/Temp/platformsh-cli-8.2.26-4.22.0/phar-4.22.0/src/Application.php(429): Symfony\Component\Console\Application->doRunCommand() #1 phar://C:/Users/Макар/AppData/Local/Temp/platformsh-cli-8.2.26-4.22.0/phar-4.22.0/vendor/symfony/console/Application.php(255): Platformsh\Cli\Application->doRunCommand() #2 phar://C:/Users/Макар/AppData/Local/Temp/platformsh-cli-8.2.26-4.22.0/phar-4.22.0/vendor/symfony/console/Application.php(148): Symfony\Component\Console\Application->doRun() #3 phar://C:/Users/Макар/AppData/Local/Temp/platformsh-cli-8.2.26-4.22.0/phar-4.22.0/bin/platform(37): Symfony\Component\Console\Application->run() #4 C:\Users\Макар\AppData\Local\Temp\platformsh-cli-8.2.26-4.22.0\phar-4.22.0(10): require('...') #5 {main} thrown in phar://C:/Users/Макар/AppData/Local/Temp/platformsh-cli-8.2.26-4.22.0/phar-4.22.0/vendor/symfony/console/Application.php on line 1027 I’ve tried: Checking if port 5000 is in use (it doesn’t seem to be). Using a different browser. Disabling browser extensions. Temporarily disabling my firewall. I am using Windows. I am trying to deploy a Django project. Any suggestions on … -
RTSP Live Camera in Django Server or React App
I wanna stream camera live videos in my website using django and react. in VLC -> Media -> Open Network Stream I set this RTSP url in Network tab and I can see live camera video perfectly: rtsp://user:password%40123@ip:port But I can't do it in django. or maybe I don't need to do this on django and can do it on react only. best I could achieve was this code which only worked in local with a VPN: class VideoCamera: def __init__(self): url = "rtsp://user:password%40123@ip:port" self.video = cv2.VideoCapture(url, cv2.CAP_FFMPEG) if not self.video.isOpened(): print("Failed to open RTSP stream") self.running = False return self.running = True self.grabbed, self.frame = self.video.read() self.lock = threading.Lock() # Prevents race conditions self.thread = threading.Thread(target=self.update, daemon=True) self.thread.start() def update(self): while self.running: grabbed, frame = self.video.read() if not grabbed: print("Failed to grab frame, retrying...") continue # Prevents self.frame from being None with self.lock: self.frame = frame def get_frame(self): with self.lock: if self.frame is None: return None success, jpeg = cv2.imencode('.jpg', self.frame) if not success: print("Encoding failed") return None # Prevent sending invalid data return jpeg.tobytes() def stop(self): self.running = False self.thread.join() # Ensures clean exit self.video.release() def get_camera(camera): while camera.running: frame = camera.get_frame() if frame: yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' … -
How to make django form dropdown shows items created by the author only not by all the users?
I have created two models Topics and entries. User can create topic and also create the entries for each topic they created. In Create Topic Entry class, the fields 'topic' showing all topics created by all users in the form dropdown menu. However, I just want the form dropdown shows topics created by the author only so that user can only create the entry for their topic but not others topic. How to do that? models.py: class Topic(models.Model): '''A topic that user will add the content about.''' title = models.CharField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) class Entries(models.Model): '''Entries and Topic will have many to one relationship''' topic = models.ForeignKey(Topic, on_delete=models.CASCADE) name = models.CharField(max_length=100) text = models.TextField() entries_image = models.ImageField(default= 'default.jpg', upload_to ='images') date_added = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) views.py class CreateTopic(LoginRequiredMixin, CreateView): model = Topic fields = ['title'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class CreateTopicEntry(LoginRequiredMixin, CreateView): model = Entries fields = ['topic', 'name','text','entries_image'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Topic_form.html: <div> <form method="POST"> {% csrf_token %} {% if object %} <h4 class="mb-4">Update your Topic &#128071</h4> {{ form|crispy }} {% else %} <h4 class="mb-4">Create your new Topic &#128071</h4> {{ form|crispy }} {% endif %} <div … -
Assistance Needed: MySQL Access Denied and User Privileges Error
Despite following the standard setup instructions, I am encountering an "Access denied for user" error when trying to perform database migrations.the error encountered is 'django.db.utils.OperationalError: (1045, "Access denied for user 'Nooshin'@'10.0.5.126' (using password: YES)")' my database configuration in setting.py file is : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Nooshin$ads', 'USER': 'Nooshin', 'PASSWORD': 'ads123', 'PORT': '3306', 'HOST': 'Nooshin.mysql.pythonanywhere-services.com', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, } } and here is my database interface in pythonanywhere please help me solve the issue I am facing. -
Access to XMLHttpRequest at ' ' from origin ' ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No
Access to XMLHttpRequest at ' ' from origin ' ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. i am facing this issue while i am trying to host my project from vercel I got everything right in my settings.py file but got this error over and over while i tried to host my project from vercel . I am using django 5.1.6 django-cors-headers: 4.6.0 djangorestframework: 3.15.2 i am also using react as my frontend framework. i also put this file as vercel.json in my backend directory but still got this error { “builds”: [ { “src”: “backend/wsgi.py”, “use”: “@vercel/python”, “config”: { “maxLambdaSize”: “15mb” } } ], “routes”: [ { “src”: “/(.*)”, “dest”: “backend/wsgi.py” } ] } this is my setting file please someone help me through this error CORS_ALLOW_ALL_ORIGINS =True ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'corsheaders', 'rest_framework', 'rest_framework_simplejwt', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
Django Rest API : ValueError: badly formed hexadecimal UUID string
I'm getting the following error while attempting to create a superuser on Django 5.0.4 Rest API ValueError: badly formed hexadecimal UUID string Here is the stack trace : File "/home/ubuntu/myapi_aws/my_auth/models.py", line 55, in get_by_natural_key uuid = UUID(uuid) File "/usr/lib/python3.10/uuid.py", line 177, in __init__ raise ValueError('badly formed hexadecimal UUID string') ValueError: badly formed hexadecimal UUID string Model definitions: from uuid import UUID class UserManager(DjangoUserManager): def get_by_natural_key(self, uuid): if not isinstance(uuid, UUID): uuid = UUID(uuid) return self.get(uuid=uuid) class User(AbstractUser): """" Custom user model to change behaviour of the default user model such as validation and required fields. """ uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True,verbose_name=_("UUID")) What I've tried delete migrations flush database using flush command reset database using reset_db command -
How can I send data to intermediate page when using custom django action?
I want to add custom django action that allows to change choice field for my model. I want intermediate page, where user can set the new value for this field. This field should be on another URL. The problem is that I need somehow send selected ids to this intermediate page, and GET params is not an option, because the amount of ids can be too big, and I have project restriction of url length to be strictly less then 8000 symbols. Right now I have this setup and it works great, but I have no clue how can I send selected object ids without GET params. forms.py class MyModelChangeStepForm(Form): _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) step_code = forms.ChoiceField(choices=...) admin.py @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): actions = ('change_mymodel_step',) @admin.action(description='') def change_mymodel_step(self, request, queryset): selected_mymodel_ids = list(queryset.values_list('id', flat=True)) mymodels_count = len(selected_mymodel_ids) if 'apply' in request.POST: form = MyModelChangeStepForm(request.POST) if form.is_valid(): new_step_code = form.cleaned_data['step_code'] # use `filter` instead of `queryset` to prevent FieldError because queryset has annotations MyModel.objects.filter(pk__in=selected_mymodel_ids).update(step_code=new_step_code) for mymodel in queryset: self.log_change(request, mymodel, '...') self.message_user(request, '...') return None self.message_user( request, '...', level=messages.ERROR, ) return None form = MyModelChangeStepForm(initial={ '_selected_action': selected_mymodel_ids, 'action': request.POST['action'], }) return render( request, 'mymodel_change_step_code.html', {'form': form, 'objects': queryset, 'mymodels_count': mymodels_count}, ) mymodel_change_step_code.html {% … -
Django model formset to update objects with user input
Having some troubles with understanding objects update using model formset. Creation of objects is not a problem as flow is clear. Updating predefined objects is not a problem as well as we use instance to pass instances. However the question is : How to update objects which user inputs in model formset fields? Let's say I have some dummy code: models: class Product(models.Model): serial_number = Charfield() config = ForeignKey(Configuration) class Configuration(models.Model): items = ManyToMany(Item) forms: class ProductFormset(forms.BaseModelFormSet): def __init__(self, *args, **kwargs): super(ProductFormset, self).__init__(*args, **kwargs) self.queryset = models.Product.objects.none() class ProductForm(forms.ModelForm): class Meta: model = Product fields = ["serial_number"] ProductFormSet = modelformset_factory(Product, ProductForm, ProductFormset, min=1, extra=0) So whenever user inputs some serial_number(s) on creation page I'm able to use clean_data to process new objects and save(). Whenever I use object's DetailView to redirect to update link I'm able to pass object id and use it to assign as instance and all works fine for save(). But on update page I want to let user decide which products to edit. So until form submitted the serial_number(s) are unknown and can't be used as initial. Formset is_valid() returns False as well as field error risen Object already exists. I'm also using JS to dynamically … -
Prometheus can't scrape Django metrics (400 Bad Request) when running in Docker container
I'm trying to collect prometheus-django metrics from a Django application running inside a Docker container. The metrics are exposed at http://127.0.0.1:8888/prometheus/metrics, and I can access them from my local machine. However, when Prometheus (running in another container) tries to scrape them, I get a 400 Bad Request response. 400 Bad Request docker-compose: backend: build: ./store/ container_name: store_backend env_file: .env volumes: - static:/backend_static/ - media:/app/media/ nginx: build: ./nginx/ container_name: store_nginx env_file: .env volumes: - static:/staticfiles/ - media:/app/media/ ports: - ${PORT}:80 depends_on: - backend prometheus: build: ./monitoring container_name: store_prometheus volumes: - prometheus_data:/prometheus command: - "--config.file=/etc/prometheus/prometheus.yml" ports: - "9090:9090" prometheus.yml: global: scrape_interval: 5s scrape_configs: - job_name: 'django' static_configs: - targets: ['store_backend:8888'] metrics_path: '/prometheus/metrics' nginx.conf: location /prometheus/metrics/ { proxy_set_header Host $http_host; proxy_pass http://backend:8888/prometheus/metrics/; } While troubleshooting this issue, I set ALLOWED_HOSTS = ['*'], but it doesn't work. So Prometheus can connect to the Django container, but the Django app rejects the request. Can you help me to understand what might be causing this issue? -
Django - pagination for inline models
I realize this is probably a beginner level error, but I'm out of ideas. I need to add pagination to Inline model for admin page. I'm using Django 1.8.4 ( yup, I know it's really old ) and python 3.6.15. Inside admin.py: class ArticleInline(GrappelliSortableHiddenMixin, admin.TabularInline): model = ArticleSection.articles.through raw_id_fields = ("article",) related_lookup_fields = { 'fk':['article'], } extra = 1 class ArticleSectionsAdmin(reversion.VersionAdmin): list_display = ('name','slug','template_file_name') inlines = [ArticleInline] admin.site.register(ArticleSection,ArticleSectionsAdmin) Inside models.py: class ArticleSection(Section): articles = models.ManyToManyField(Article, verbose_name=_("article"), through="M2MSectionArticle", related_name="sections") limit = models.PositiveSmallIntegerField(default=10) class Meta: db_table = 'sections_article_section' verbose_name = _("article section") verbose_name_plural = _("articles sections") def content(self, request): query = Q(m2msectionarticle__visible_to__isnull=True) & Q(m2msectionarticle__visible_from__isnull=True) query.add(Q(m2msectionarticle__visible_to__gte=timezone.now(), m2msectionarticle__visible_from__lte=timezone.now()), Q.OR) limit = self.limit_override if hasattr(self, 'limit_override') and self.limit_override is not None else self.limit return self.articles.filter(query).published().prefetch_related('images').order_by('m2msectionarticle__position')[:limit] class M2MSectionArticle(models.Model): section = models.ForeignKey(ArticleSection, related_name='section_articles') article = models.ForeignKey(Article, verbose_name=_('article')) position = models.PositiveSmallIntegerField(_("position"), default=0) visible_from = models.DateTimeField("Widoczne od", null=True, blank=True) visible_to = models.DateTimeField("Widoczne do", null=True, blank=True) class Meta: db_table = 'sections_section_articles' ordering = ["position"] I found django-admin-inline-paginator and it seems to work for everyone else, but I get "Function has keyword-only parameters or annotations, use getfullargspec() API which can support them" when I use TabularInlinePaginated instead of admin.TabularInline. from django_admin_inline_paginator.admin import TabularInlinePaginated class ArticleInline(GrappelliSortableHiddenMixin, TabularInlinePaginated): model = ArticleSection.articles.through raw_id_fields = … -
Using special characters in a Django template tags
I am trying to make a field with Django Tweaks and I am trying to add some HTMX attributes. I want to use the following syntax: {% render_field field <other attributes> hx-vals='{"country": this.value}' %} However, if I use this syntax, I get an rendering error. This is because it tries to interpret the brackets. I have searched a lot on the internet, and each answer for escaping characters in Django Templates, suggests using the verbatim tag or something similar. The problem is that that only allows you to render special characters, not use them in a variable. Is there a solution that allows me to escape special characters in Django template variables? Right now I am sending the string in the context, but that is not ideal. Thanks in advance! -
how to Add microsoft login to python django web app
The web app works with a basic user management service. Im trying to add microsoft authentication through 365. After attempting to log in there is always an error "AADSTS700016: Application with identifier 'None' was not found in the directory 'University Of x'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.' I cannot figure out how to get the URL to include the client ID. I have already created the microsoft social app in the web app's django admin pannel and already tried many syntaxes for putting it in the settings.py. I also just manually put it in the URL and then it crashes the website, Im pretty sure this is because i manually put the client_ID and the backend isnt reading it to process it in the next page. -
drf url parameter lookup
I'm creating an endpoint api/users/ with Django REST framework which should return some data about the user by id. It's all good, but I want to obtain a lookup parameter for my User model from the url's parameters. There are lookup_field and lookup_url_kwarg attributes of GenericAPIView, but they seem to be useless here, because they work with parameters specified in URLConf, if I understand it right. So, my question is how to get object from the db when I go to like /api/users?uid=123? There is surely a way where we override get_object() or get_queryset() or any other stuff like this: class UserAPIView(RetrieveUpdateDestroyAPIView, CreateAPIView): serializer_class = users.serializers.UserSerializer queryset = users.models.User.objects.all() def get_object(self) -> User: uid = self.request.query_params.get('uid', None) if uid is None or not uid.isdigit(): raise Http404 self.kwargs.update({self.lookup_field: uid}) return super().get_object() but it looks kind of ugly, isn't it? I believe there should be a better way of dealing with it.. -
Conditional aggregate and distinct
Using StringAgg with the distinct=True argument works under normal circumstances, e.g.: entities = entities.annotate(roles=StringAgg( "credits__role__name", delimiter=", ", distinct=True, ordering="credits__role__name" )) But when used with a conditional expression, it throws the exception django.db.utils.ProgrammingError: in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list, e.g.: releases = releases.annotate(credits_primary=StringAgg( Case(When(credits__type="primary", then="credits__entity__name")), delimiter=", ", distinct=True, ordering="credits__entity__name" )) Why is this, and is there a way to make the second example work? -
How to sign an XML document with Python?
I am doing a project in Django (full Python) specifically a sales system. Now, I want to incorporate electronic invoicing to the system, focusing only on the electronic sales receipt for now. In my country, the regulatory entity requires that to send the invoice, it must be done in an XML file (with a specific format), then, it must be signed with the digital certificate of the company, packed in a .zip file and sent to the testing web service of the entity. But, I don't know how to do the signature using only Python. I was researching and I noticed that most of them choose to use languages like Java or C#, mainly. I also found the lxml and cryptography libraries, with which I could make the signature, but when I send it to the web service, I get the error: Error of the web service: The entered electronic document has been altered - Detail: Incorrect reference digest value I was trying to find out how to fix this error, I don't know if it has to do with the way I'm signing the XML document or the method I'm using. I share with you the code to give … -
Custom template conditon in Django
In my Django project I want to hide menu option under a custom built condition. In my base.html I want a construction like this: {% if my_condition %} <a class="dropdown-item" href="...">New article</a> {% endif %} How to write 'my_condition'? I searched for 'custom template condition', but they all the answers direct me to the 'custom template tags and filters' of the Django documentation, but I can't find a satisfying solution. -
Django persistent connections with PgBouncer?
We have database performance issues and I am looking into adding PgBouncer to handle connections more efficiently and hopefully solve the issue. However, after configuring it, I am not sure how to tell whether PgBouncer is handling connections as intended (if at all) and in a healthy and effective way. I think the key is deciding whether Djang's CONN_MAX_AGE setting should be set to 0 or to None. This answer says it should be None for persistent connections. But wouldn't this defeat the purpose of PgBouncer's connection pooling? Wouldn't we want to set it to 0 and release connections back to the pool instead? I set PgBouncer's verbosity level to 3, let me paste my log when CONN_MAX_AGE is None and when it is 0, hopefully it tells you something relevant that I myself can't see: CONN_MAX_AGE = None 2025-02-27 12:15:02.832 UTC [3336] NOISE safe_send(23, 577) = 577 2025-02-27 12:15:02.832 UTC [3336] NOISE sbuf_process_pending: end 2025-02-27 12:15:02.832 UTC [3336] NOISE resync(20): done=577, parse=577, recv=577 2025-02-27 12:15:02.832 UTC [3336] NOISE S-0x1a8a698: dbname/dbuser@127.0.0.1:5432 release_server: new state=12 2025-02-27 12:15:02.832 UTC [3336] DEBUG S-0x1a8a698: dbname/dbuser@127.0.0.1:5432 reuse_on_release: replication 0 2025-02-27 12:15:02.836 UTC [3336] NOISE resync(23): done=0, parse=0, recv=0 2025-02-27 12:15:02.836 UTC [3336] NOISE safe_recv(23, 4096) … -
Unable to create a django.conf file for nginx
I am trying to deploy my django app on aws ec2 and i created a django.conf file for nginx this is my django.conf file server{ listen 80; server_name 15.206.160.34; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/{project}/app.sock; } } but when i try to run the command sudo nginx -t i get this error 2025/02/27 10:40:17 [emerg] 15034#15034: directive "proxy_pass" is not terminated by ";" in /etc/nginx/sites-enabled/django.conf:10 nginx: configuration file /etc/nginx/nginx.conf test failed How do i fix this, please help. -
How to set the media path to root media folder in Django?
I have a media folder outside the APP, in the project folder (to share media with other apps). How to set up Django, to set media path to a folder in the project folder? Problem: I'm getting error: "GET /soupiska/pic/hraci/download_6BVC8qn.jpeg HTTP/1.1" 404 2971 but "soupiska" is the APP folder. The path saved in the database is: pic/hraci/download_6BVC8qn.jpeg And settings.py includes: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') print(MEDIA_ROOT) -
weasypring-django __init__() takes 1 positional argument but 3 were given
I am facing problems trying to generate pdf from my django views using weasyprint-django views.py def schoolSequenceReportpdf(request,slug,pk,seq): host=request.META['HTTP_HOST'] if request.user.is_authenticated: skoll = None valuecheck = None admin_check = False statistics = None if request.user.is_school: #Calling the check school profile obj. skoll,valuecheck = check_for_skolProfile(request.user) # Calling the check accademic year object. accademic_yearObj,acc_valuecheck= check_for_accademicYear(skoll) else: try: valuecheck= True skoll= schoolProfile.objects.get(slug=slug) accademic_yearObj,acc_valuecheck= check_for_accademicYear(skoll) admin_check = adminCheck(request.user,skoll) if admin_check is False: return redirect('main:wrongpage') except: return redirect('main:wrongpage') if accademic_yearObj: #get classroom instance try: classroomobj = Level.objects.get(id=pk) sequence = Sequence.objects.get(id=seq) term = sequence.term except: term = None classroomobj = None else: term = None classroomobj = None sequence_report_cards = FinalTermReport.objects.filter(sequence=sequence,classroom=classroomobj).order_by("-studentavg") statistics = ClassroomResultStatistics.objects.filter(sequence=sequence,classlevel=classroomobj,seqstate=True).order_by("-created") terms = Term.objects.filter(year=accademic_yearObj) sequences = Sequence.objects.filter(year=accademic_yearObj).order_by('-created') color = ReportCardColor.objects.filter(skoll=skoll) if color: color= color.first filling_session = FillMarksDateScheduling.objects.filter(year=accademic_yearObj,skoll=skoll,active=True,delete=False) context = {'color':color,'host':host,'statistics':statistics,'sequence_report_cards':sequence_report_cards,'sequence':sequence,'term':term,'filling_session':filling_session,'sequences':sequences,'statistics':statistics,'terms':terms,'admin_check':admin_check,'classroomobj':classroomobj,'name':classroomobj.name,'accademic_yearObj':accademic_yearObj,'accyear':acc_valuecheck,'skollobj':skoll,'valuecheck':valuecheck} html_string = render_to_string("main/sequencereportcardpdf.html", context) pdf = HTML(string=html_string).write_pdf() response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename="{classroomobj.name}.pdf"' return response urls.py url(r'^sequence/report/pdf/(?P<slug>[\w-]+)/(?P<pk>[0-9]+)/(?P<seq>[0-9]+)$',views.schoolSequenceReportpdf,name="sequencereportpdf"), I have tried changing errors i got File "/mnt/e/digolearnsms/smsdigo/main/views.py", line 4460, in schoolSequenceReportpdf pdf = HTML(string=html_string).write_pdf() File "/mnt/e/digolearnsms/myenvubuntu/lib/python3.8/site-packages/weasyprint/__init__.py", line 259, in write_pdf self.render(font_config, counter_style, **options) File "/mnt/e/digolearnsms/myenvubuntu/lib/python3.8/site-packages/weasyprint/document.py", line 390, in write_pdf pdf = generate_pdf(self, target, zoom, **options) File "/mnt/e/digolearnsms/myenvubuntu/lib/python3.8/site-packages/weasyprint/pdf/__init__.py", line 127, in generate_pdf pdf = pydyf.PDF((version or '1.7'), identifier) TypeError: __init__() takes 1 positional argument … -
Working directory structure for a Django-Python project used as an API backend only
I'm a newbie in Django Python and I need to create an API backend for a frontend done in React. I'm forced by the customer to use Django Python, no options on this! The project is very simple: it needs to expose ~15 endpoints, use Django ORM to connect to a PostgreSQL database, and have basic business logic. I must have a minimum of 80% unit tests coverage of the code and expose a swagger UI. My problem is to create a "standard", well-defined, wisely organized structure of the working directory structure as defined by the best practice. In .NET I put my endpoints in the controllers, then I create the business logic with interfaces and the data layer where I have the model and the entities, so everything is all well organized and separated. How can I achieve a similar organization in Django? I've seen that some people use DRF (Django RESTful framework), is it good for my purpose? is it a best practice for projects like mine? -
I need to create a system that has custom views for my users
how do large companies or large systems to have several views (screens or UI's) for their different types of users, for example, having a UI for the admin panel, another UI for employee profile and that average users do not enter the admin panel? I know with authorization and authentication, but how do you program it? How do they do it? I'm using Django and I'm using a decorator login required and user_passes_test(lambda u: check_group(u, 'RRHH'), login_url='/denegado/'). and what that does is see if the user who is logged in belongs to HR shows the view, if not, it redirects him to denied and denied redirects him to the view to which he belongs, look: def redirigir_por_grupo(request): if request.user.groups.filter(name='RRHH').exists(): return redirect('sucursales') elif request.user.groups.filter(name='Gerentes').exists(): return redirect('gerencia') elif request.user.groups.filter(name='Empleados').exists(): return redirect('perfil') but I don't know, I feel that it is not the safest and most optimal way, I think right. To tell the truth, it is the first time that I have made such a complex and full stack system and I am interested in it being extremely secure and following the best practices. I want HR to have access to all apps and managements only to incidents and employees only to … -
How to resolve circular dependency error in django models
I have 2 apps in my django project 1.customer app 2.trades app Customer app has following tables in models.py 1.customer_table 2.trade_plan_table 3.service_plan_table 4.customer_payments trades app has following table in models.py 1.trade_details_table 2.service_details_table Below are my dependencies: 1.service_plan_table has foreign key ref to service_details_table 2.customer_payments has foreign key ref to customer_table, trade_plan_table, service_plan_table trade_details_table has foreign key ref to customer_table service_details_table has foreign key ref to customer_table Since there is dependency from customer model to trades model and vice versa, I'm facing circular dependency error. Instead of importing I tried 'string reference' but it did not help. Can some one please suggest how to solvethis issue -
Django form field labels are not displaying in the template
whats wrong with this code? labels are not displaying in the 'single-project.html' template. can anyone tell the mistake in this code.what should i correct it to display my labels in my template. My forms file class ReviewForm(ModelForm): class Meta: model = Review fields = ['value', 'body'] labels = { 'value' : 'Place your vote', 'body' : 'Add a comment with your vote' } def __init__(self, *args, **kwargs): super(ReviewForm, self).__init__(*args, **kwargs) for name,field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) My views file def project(request,pk): projectObj = Project.objects.get(id=pk) form = ReviewForm() return render(request,'projects/single-project.html', {'project' : projectObj, 'form':form,}) My template file {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#textarea">{{field.label}}</label> {{field}} </div> {% endfor %} solution to this problem -
REACT Component for Car Dealerships Page Not Visible
I am working through IBM Coursera's Full Stack Developer course and am stuck on the Car Dealership application Capstone Project. Specifically, I am struggling to make the car dealerships visible on the dealers page. A semicolon appears on the page. This makes it seem as though the Dealers.jsx React component is not correctly rendering, but that was provided by IBM so I would not think that contains any errors. Current output of Dealerships page Dealers page output Dealers.jsx React component (provided by IBM) import React, { useState, useEffect } from 'react'; import "./Dealers.css"; import "../assets/style.css"; import Header from '../Header/Header'; import review_icon from "../assets/reviewicon.png" const Dealers = () => { const [dealersList, setDealersList] = useState([]); // let [state, setState] = useState("") let [states, setStates] = useState([]) // let root_url = window.location.origin let dealer_url ="/djangoapp/get_dealers"; let dealer_url_by_state = "/djangoapp/get_dealers/"; const filterDealers = async (state) => { dealer_url_by_state = dealer_url_by_state+state; const res = await fetch(dealer_url_by_state, { method: "GET" }); const retobj = await res.json(); if(retobj.status === 200) { let state_dealers = Array.from(retobj.dealers) setDealersList(state_dealers) } } const get_dealers = async ()=>{ const res = await fetch(dealer_url, { method: "GET" }); const retobj = await res.json(); if(retobj.status === 200) { let all_dealers = Array.from(retobj.dealers) let …