Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Correct loading of jquery and usage of extended base.html templates within Django framework
I think this is not very related to Django more to jQuery and html behavior however what is the problem statement: Using a more or less standard base.html template base.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> {% block stylesheets %} <!-- load Stylesheets --> {% endblock stylesheets %} <title> {% block title %} Base Title {% endblock title%} </title> </head> <body> <header> {% block header %} {% endblock %} </header> <main> {% block body %} {% endblock %} </main> <footer> {% block footer %} {% endblock %} </footer> {% block scripts %} <!-- Jquery 3.5.1 CDN --> <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <!-- Popper 1.12.9 CDN --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <!-- Bootstrap 4.0.0 CDN --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> {% endblock %} {% block extrascripts %} {% endblock %} </body> </html> From this dashboard.html is derived by extension of base.html {% extends 'base.html' %} {% block title %}Dashboard{% endblock %} {% block body %} <div class="navbar navbar-expand justify-content-end"> some navigation bar content </div> some else stuff <div class="container"> <div class="row" style="margin-top: 1em"> {% include 'dash_cards/dash_card.html' %} </div> </div> some more content {% endblock %} {% block extrascripts %} {% endblock %} This works all fine … -
ftps in django app is not working after deploying on Apache2?
I am facing a problem after deploying my django project on apache2 server. In my django project I have connected to a remote ftp server using ftp with tls form ftplib. Which is working perfectly while I am running on development. Issue created after deploying it on apache2 server. Here ftps connection is not working. Can anyone help me to sort out this issue. -
celery_1 | ImportError: No module named 'hh_ru_django'
Watched many tutorials with dockerize celery + django, did like in the video.I think the problem is in docker-compose file, but i didn't found the solution.It took to much time, and i couldn't solve the problem. Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /usr/src/hh_ru_django COPY requirements.txt /usr/src/hh_ru_django/ RUN pip install -r requirements.txt COPY . /usr/src/hh_ru_django docker-compose.yml version: '3.9' services: pgdb: image: postgres container_name: pgdb environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - pgdata:/var/lib/postgresql/data/ django: build: . container_name: django command: python manage.py runserver 0.0.0.0:80 volumes: - .:/usr/src/hh_ru_django ports: - "80:80" environment: - DEBUG=1 - DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 - CELERY_BROKER=redis://redis:6379/0/ depends_on: - pgdb - redis redis: image: redis ports: - '6379:6379' celery: image: celery command: celery worker -A hh_ru_django --loglevel=info volumes: - .:/usr/src/hh_ru_django depends_on: - django - redis volumes: pgdata: hh_ru_django/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hh_ru_django.settings") app = Celery("hh_ru_django") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() hh_ru_django/settings.py just the variables with broker CELERY_BROKER = os.environ.get("CELERY_BROKER", "redis://redis:6479/0") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BROKER", "redis://redis:6479/0") -
Modern method to run Django scripts as alternate user in Apache deployment
I have seen a number of similar questions, however none seem to have current solutions. I have a Django deployment running on Apache and mod_wsgi, as outlined in the Django guides here, hosted on an Ubuntu 20.04 LTS server. By default, Apache, and hence any python script run by it, is run as the www-data user. I have some scripts on my website that require privileged access to run, and for security reasons I would like to avoid granting the necessary privileges to www-data to run these scripts directly. Ideally I'd like a solution I can implement directly in the relevant views.py file to run the privileged script as a user with the permissions to do so only after inputs have been sanitized. What are my options to achieve this? As an example of a script requiring privileged access: my company uses this web portal for (among other things) setting up remote servers at client sites. That setup requires ssh access, which is restricted to certain users, and should not be granted to the www-data user. I have considered recreating the privileged scripts as daemon processes, however they do not need to be run frequently so I don't feel it's … -
Wagtail adds '#' to {{page.slug}} in address bar
I'm using Wagtail for a blog site with auto-populating blog links on a listing page. However, when I click the link for the blog page, it adds a '#' to the address bar. So, for example, I am working on localhost with the blog address of http://127.0.0.1:8000/blog/ and once I click on the blog link, with slug blog-slug, I get http://127.0.0.1:8000/blog/#/blog-slug. I am not sure why it is adding the hash tag at a location even behind the parent page 'blog'. This is the code I have on the blog listing template: {% for post in all_posts %} <figure class="item standard" data-groups='["all"{% for tag in post.tags.all %},"{{tag}}"{% endfor %}]'> <div class="portfolio-item-img"> {% image post.blog_image max-350x200 as img %} <img src="{{img.url}}" alt="{{img.alt}}" title=""> <a href="{{post.slug}}" class="ajax-page-load"></a> <!-- Blog slug --> <br> <i class="{{post.icon}}"></i> <p>{{post.gallery_text|safe|truncatewords:30}}</p> </div> <h4 class="name"> {{post.title}} </h4> <div class="post-info"> <div class="post-date"> <strong>Tags:</strong> {% for tag in post.tags.all %}| {{tag}} |{% endfor %} </div> <div class="post-date">{{post.published_date}}</div> </div> </figure> {% endfor %} Any ideas what could be going wrong? -
Django by Example Chapter 5. urllib.error.URLError
I am stuck on chapter 5 on the bookmarks tools that I followed in the book. I am using Django 3.1 and following (I have checked evrything almost 10 times) this version on github : [https://github.com/PacktPublishing/Django-3-by-Example/tree/master/Chapter05][1] But I still have this error : urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)> File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 1319, in do_open h.request(req.get_method(), req.selector, req.data, headers, File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1230, in request self._send_request(method, url, body, headers, encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1276, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1225, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1004, in _send_output A message_body may be specified, to be appended to the request. """ self._buffer.extend((b"", b"")) msg = b"\r\n".join(self._buffer) del self._buffer[:] self.send(msg) if message_body is not None: # create a consistent interface to message_body if hasattr(message_body, 'read'): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 944, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1399, in connect self.sock = self._context.wrap_socket(self.sock, File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 500, in wrap_socket return self.sslsocket_class._create( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 1040, in _create self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 1309, in do_handshake self._sslobj.do_handshake() During handling of the above exception, another exception occurred: File "/Users/ricardoponce/Documents/WebSocial/venv/lib/python3.8/site-packages/django/contrib/staticfiles/handlers.py", line 76, in __call__ return self.application(environ, start_response) File "/Users/ricardoponce/Documents/WebSocial/venv/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = … -
CORS problem with Django setup in Digital Ocean Spaces
I have a django website hosted inside a Digital Ocean Droplet and we decided recently to move all static and media files to a Digital Ocean Spaces. So far it's working under some situations and not working for others. I added my origin and allowed headers to CORS configuration in Spaces as below: When I run "collectstatic" from my Droplet its copying my files to Spaces and it's working perfectly for the website. When I go to admin, icons and some other static resources are not being loaded, getting a 403 error (FORBIDDEN), as below: Looking more in deep I went to Digital Ocean Spaces to check files permissions, all files have the same permission (private) and all are stored correctly. So, first question, why some of them work for the main website and others specially in admin don't? However, other weird things are happening also when I try to load some files via XMLHttpRequest using THREE.js. All I get is this message: Access to XMLHttpRequest at 'https://nyc3.digitaloceanspaces.com/MYSPACE/file.stl?AWSAccessKeyId=2I6LYDQXCYZWQHXJVRSO&Signature=4lnHY7WnPh5jracKZoEj7jqKAGc%3D&Expires=1612816348' from origin 'https://shopping.mydomain.com.br' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Why I'm getting this error if CORS are set in Digital Ocean Spaces and … -
trouble with unit testing graphene-django schema
when i run this test def test_get_all_messages(mock_resolve): assert mock_resolve is Query.resolve_all_messages MSG_TXT = 'abc' mock_resolve.return_value = [Message(id=1, text=MSG_TXT)] query = ''' query{ allMessages{ id } } ''' result = schema.execute(query) assert mock_resolve.called_once() assert not result.errors EXPECTED_DATA = { 'allMessages': { 'id': 1 } } assert result.data == EXPECTED_DATA I get this error RuntimeError('Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it i'm trying to run the unit test in isolation and not using the db Adding pytest.mark.django_db @pytest.mark.django_db @patch(RESOLVE_ALL_MESSAGES) def test_get_all_messages(mock_resolve): assert mock_resolve is Query.resolve_all_messages MSG_TXT = 'abc' mock_resolve.return_value = [Message(id=1, text=MSG_TXT)] query = ''' query{ allMessages{ id } } ''' result = schema.execute(query) assert mock_resolve.called_once() assert not result.errors EXPECTED_DATA = { 'allMessages': { 'id': 1 } } assert result.data == EXPECTED_DATA Now i get this error E Differing items: E {'allMessages': []} != {'allMessages': {'id': 1}}``` -
Django select_related/prefetch_related not working as expected
In my Admin page I have Order model with TabularInline of OrderItem model class OrderItemStackAdmin(admin.TabularInline): model = OrderItem extra = 0 fieldsets = ( (_('Product'), { 'fields': ('product', 'variant') }), (_('Add-Ons'), { 'fields': ('product_add_ons', 'add_ons_note') }), (_('Price'), { 'fields': ('quantity', 'product_price', 'add_ons_total_price') }), (_('Discount'), { 'fields': ('discount',) }) ) def get_queryset(self, request): qs = super().get_queryset(request) return qs.select_related( "customer_order", "product", "variant" ).prefetch_related('product_add_ons') Two FK are given: Product, Variant One Many to Many given: product_add_ons With select_related/prefetch related i manage to reduce queries, however, 35 duplicate/similar queries are found. all duplicated queries share this NO SCROLL CURSOR WITH HOLD FOR SELECT Please note removing the inline removes all duplicated queries. -
Why can't object_set get unique items?
I am trying to pull a user's objects viewed from the Product model. It's pulling all of the user's viewed products right now but with duplicates. I have tried putting .distinct() in views = request.user.objectviewed_set.by_model(Product, model_queryset=False).distinct() but it does not work, I think because that is just pulling the rows for Object viewed, not the products themselves. Appreciate the help! from html {% for obj in object_list %} <div class='col-xl-12'> {% include 'products/card.html' with instance=obj.content_object %} </div> {% endfor %} from products/card.html <div class="card" style="width: 20rem;"> <a href="{{instance.get_absolute_url}}"> <img style="width:30%;" src="{{instance|get_thumbnail:'sd'}}" alt="{{instance.title}} logo"> </a> <div class="card-body"> <h4 class="card-title">{{ instance.title }}</h4> <p class="card-text">{{ instance.description|linebreaks|truncatewords:14 }}</p> </div> from products models.py class Product(models.Model): seller = models.ForeignKey(SellerAccount, null=False, on_delete=models.CASCADE) title = models.CharField(max_length=30, blank=False) slug = models.SlugField(unique=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): #defining str as self and returning self, which is used ie in admin.py return self.title def get_absolute_url(self): view_name = "products:detail" return reverse(view_name, kwargs={"slug": self.slug}) from analytics models.py class ObjectViewedQuerySet(models.query.QuerySet): def by_model(self, model_class, model_queryset=False): c_type = ContentType.objects.get_for_model(model_class) qs = self.filter(content_type=c_type) if model_queryset: viewed_ids = [x.object_id for x in qs] return model_class.objects.filter(pk__in=viewed_ids) return qs class ObjectViewedManager(models.Manager): def get_queryset(self): return ObjectViewedQuerySet(self.model, using=self._db) def by_model(self, model_class, model_queryset=False): return self.get_queryset().by_model(model_class, model_queryset=model_queryset) class ObjectViewed(models.Model): user = models.ForeignKey(CustomUser, … -
How to create a middleware to intercept request before url discovery so that unauthorized users cannot learn urls?
I was requested to write a middleware for my company's Django project to avoid repeating code for user authentication when accessing admin/ pages. For this, I wrote a basic LoginRequiredMiddleware. I exhausted my knowledge on this middleware thing and now I have to give it some steroids to it so it can avoid external parties discovering existing views in our project especially for our /api/. Right now, when someone tries to access something like: api/v1/existing-page, Django, goes through the URLs and when it finds a url-view pair, it then goes through authentication and the middleware comes in the picture. However, if an unauthenticated user tries to access: api/vi/foo-does-not-exist/ page, then I get a Not Found page (error 404). What I would like to do is have a middleware intercepting the request and asking for user authentication (error 401 unauthorized) before Django can start scanning for an existing URL. This is a security measure to prevent anyone from learning the existing URLs/views of the project. The thing is that I don't know where to begin. Is this possible to accomplish with a middleware? If yes, can I use the same middleware or it would be better to write a separate one? … -
Increasing image size after uploading React js + Django
I have a react frontend backed by Django rest API. I use react-cropper to crop and upload images. When I upload images, the image size gets increased. Ex:- When I upload 149.5kb image it increases to 1.5MB. I notice that size in my API calls. But when I directly upload images to Django admin it remains in the same size. I can not figure out the exact reason for this. Photos are saved in DIgitalOcean Spaces. Cropper <div className="cropper_be"> <Cropper style={{ height: '100%', width: "100%" }} initialAspectRatio={16 / 9} aspectRatio={16 / 9} preview=".img-preview" src={image} viewMode={1} guides={true} minCropBoxHeight={10} minCropBoxWidth={10} background={false} responsive={true} autoCropArea={1} checkOrientation={false} onInitialized={(instance) => { setCropper(instance); }} /> </div> //function for base64 to blob const b64toBlob = (b64Data, contentType='', sliceSize=512) => { const byteCharacters = atob(b64Data); const byteArrays = []; for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } const blob = new Blob(byteArrays, {type: contentType}); return blob; } -
Django. How i can run my function every 5 second and update the page
I have a Django app. I want that every 5 seconds, the script will update DB dates and reload my page. I tried with a simple: while(), but this stopped all code. I tried with async function, but nothing is working My code: `from django.shortcuts import render from django.http import HttpResponse from django.db import models from main.models import Prices import requests from bs4 import BeautifulSoup import time # Create your views here. timeout = 5 def parseSite(): Prices.objects.all().delete() URL = "https://www.coindesk.com/price/bitcoin" page = requests.get(URL) soup = BeautifulSoup(page.content, 'html.parser') cont = soup.find(class_="coin-info").find_all(class_="coin-info-block") final_price = cont[0].find(class_="price-large").text bitoc = Prices(curency_type = "bitcoin", curency_price = final_price) bitoc.save() parseSite() def dates(): bitoc2 = Prices.objects.get(curency_type= "bitcoin") return bitoc2 def index(request): data = dates() return render(request, 'main/index.html', {'data': data}) ` -
¿Cómo puedo utilizar el username de un usuario como campo de una tabla en sqlite3?
I'm new in this and I'm trying to use in Django the username as id in other model. I import the base model for User in Django, but when i'm doing: author = User().get_username() The field doesn't appear. Is there any method to use the "username" from the User model? Thanks for your help and sorry for my English. -
Django and Celery - Insert action when user goes previous page
I would like to stop a certain task when a user opens the edit page for this certain task. What I would like to avoid is that when the user opens the edit page and goes to the previous page without saving that the task remains disabled. Is there a way to put an action, to re-activate the task, in case the user pushes the return button on his webpage? Thank you! -
Issues with Django deployed on the server only
This is the error message Exception while resolving variable 'name' in template 'unknown'. Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 165, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 288, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 576, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <module 'api.urls' from '/app/api/urls.py'> (None:None) 'api/'>], [<URLResolver <URLPattern list> (admin:admin) 'admin/'>]], 'path': ''} During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] TypeError: 'URLResolver' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 837, in _resolve_lookup current = getattr(current, bit) AttributeError: 'URLResolver' object has no attribute 'name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 843, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 848, in _resolve_lookup raise VariableDoesNotExist("Failed lookup for key " django.template.base.VariableDoesNotExist: Failed lookup for key [name] in <URLResolver … -
How to upload multiple files asynchronously before form submit in Django?
Intro: I have Django web app where users are allowed to create posts. Each post has multiple images that are associated with that post. What I want to do: I want such that when the user uploads each image to a form. I want to use Filepond javascript library for remove image, add more image and previews of selected images. The issue: The code below is getting error Reason given for failure: CSRF token missing or incorrect. I want to add multiple images to a django form asynchronously before form submit.I have the Javascript code for uploading of the images on the client side and asynchronously adds it to my server. All I need to do is give it a endpoint, which is a simple url I have a rough idea of how I plan to achieve this. I would be grateful for any help. MODELS class FileModel(models.Model): post = models.ForeignKey(Article, on_delete=models.CASCADE) file = models.FileField(upload_to='stories', blank=True, null=True) VIEWS def post_image_create(request, post): for f in request.FILES.getlist('file'): FileModel.objects.create(file=f) f.save() if post: post = f class NewsCreateView(CreateView): form_class = FileForm template_name = 'news/news_create.html' success_url = '/' def form_valid(self, form): post = form.save(commit=False) post.author = self.request.user post_image_create(request=self.request, post=post) # This function is defined above … -
Extracting a variable in Django / Python to display a live counting
what i want is to have a "dynamic" counter (like a loading bar %) that counts up as the "prog" variable increases to 100 views.py: ... qb = Client("http://www.on-demandlogistics.com:8080/") qb.login("admin", "adminadmin") qb.download_from_link(torrentLink) prog = 0 while prog < 100: prog = int(float(qb.get_torrent("cca0bf46ce95c802e6a8f0e1f353978d12da6997")['total_downloaded']) / float(qb.get_torrent("cca0bf46ce95c802e6a8f0e1f353978d12da6997")['total_size']) * 100) return render(request, "movies/dbsearch.html", { "movie_name": "Downloading " + movie_name[0].title() + " now!", "progress": prog } ) dbsearch.html: <!DOCTYPE html> <html> <head> <title>dbSearch</title> </head> <body> <h1>{{movie_name}}</h1> <h2>{{progress}}</h2> </body> </html> I'm not sure how to have the number return live (ie count up with out hitting refresh) any information you could provide would be great I'm a rookie at this stuff Thanks, littlejiver -
Django Nginx Uwsgi Supervisord don't send email message using threading
I have a django app running with Nginx+ Uwsgi+ Supervisord. With current email send settings EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my email' EMAIL_HOST_PASSWORD = 'my pass' EMAIL_PORT = 587 It does not send message when i run app using supervisord. When i try service supervisord stop all email messages sent immediately I use threading to send messages. import threading from django.core.mail import EmailMessage class EmailThread(threading.Thread): def __init__(self, email): self.email = email threading.Thread.__init__(self) def run(self): self.email.send() class Util: @staticmethod def send_email(data): email = EmailMessage( subject=data['email_subject'], body=data['email_body'], to=[data['to_email']] ) EmailThread(email).start() Do i need to specify something in supervisord config to work it properly? -
How to use Field.disabled in Django
I would like to have the slug input field be set to read only but can't seem to utilize "Field.disabled" properly. How can I do that in a simple Django form? This is my model class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() thumb = models.ImageField(default='default.png', blank=True) This is my forms.py class CreateArticle(forms.ModelForm): class Meta: model = models.Article fields = ['title', 'body', 'slug', 'thumb'] -
How can I properly use iterator in Django query set?
I want to show 20 reviews per page based on the search. Whole review count is about 260,000 so I first used reviews = Review.objects.all[(page_num-1)*20:20*page_num] But it has a huge offset problem at page 13000~ I used pagination next, but a offset problem still remained query_set = Review.objects.all[(page_num-1)*20:20*page_num] p = Paginator(query_set, 20) searched_results = p.page(page_num) Finally I used Django chunked iterator searched_results = [] for review in batch_iterator(query_set, limit=20, start_with=(page_num-1)*20): searched_results.append(review) It seem to be worked, but I got a new problem.. To use start_with for max efficiency, knowing searched results's id(it's default, other condition is possible) is needed, but the way to know also caused response delay(I think) Is there a another way to know the searched review's id(pk) or different way?? Please help me.. ㅠ_ㅠ -
Django REST serializer.is_valid() returns False
I want to handle creator field in my view @api_view(['POST', ]) def api_create_news_post_view(request): user = User.objects.get(pk=1) news_post = NewsPost(creator=user) if request.method == 'POST': serializer = NewsPostSerializer(news_post, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I complement request with needed data and pass it to serializer class NewsPostSerializer(serializers.ModelSerializer): class Meta: model = NewsPost fields = ['title', 'content', 'date_created', 'creator'] For this model class NewsPost(models.Model): title = models.CharField(max_length=100, unique=True) content = models.TextField() date_created = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name = ("News Post") verbose_name_plural = ("News Posts") def __str__(self): return self.title def get_absolute_url(self): return reverse("NewsPost_detail", kwargs={"pk": self.pk}) I send "title": "Lansino dores amores devacia ", "content": "Apollo antro" and in my view I get user object from database, create NewsPost based on it and pass it to NewsPostSerializer along with request data, but it doesn't pass validation and returns "creator": ["This field is required."] Can't figure out why it behaves like that. -
django models.ImageField not reusable
I have a very simple ImageField class as follows: class Image(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='images/', height_field='width', width_field='height', help_text = 'Please upload .png, .jpg and .jpeg extensions only') def __str__(self): return self.title with the following form class: class ImageForm(forms.ModelForm): """Form for the image model""" class Meta: model = Image fields = ('image', ) with the following template: <div> <form action='{% url "image-search" %}' method="post" enctype="multipart/form-data"> {% csrf_token %} <p > {{ form.file }} </p> <input type="submit" value="Upload" /> </form> </div> When nothing is selected, I see the page as follows, i.e. all normal behaviour: But once I upload an image, the button just disappears and nothing is select able anymore. This is how it looks: I am stuck here from quite some time, please guide. -
How to set a field of a user, a default for another field?
I have a model that I want connected to all models. I did that using foreinkeys. I don't want the user to fill out that field by himself, that's because the user model has that field too therefore I want the data to be filled in automatically using request.user.that_field. I am using CreateView for creating model instances, i am pretty sure there is a way to do what I want but am not clear about what it is. Any help is appreciated. Thank you. -
Is there a general EMT program in python code for nodal analysis for linear and non-linear circuits?
I do my final thesis for my degree and I am trying to make a general electromagnetic Transient Program (EMT) from Matlab to python? Can anyone help? The following code is the EMT program in Matlab, I want a similar code in python...If anyone cal help please tell me!! You can check the general EMT program at Power Systems Electromagnetic Transients Simulation N. Watson, J. Arrillaga book https://pdfs.semanticscholar.org/7cc4/c22f9b6c792e11e9375ebd34464701ffe2b2.pdf?_ga=2.142182970.900690170.1612704649-1978088677.1606542049 on pages 376-384 of the book you will find the code in matlab. You can find in this link my code in python http://pythonpowerelectronics.com/?page=softwaredownloads .The code is the version 3.1.1- command line, so i will do my changes here at my python code. The changes will based at the general EMT program of the book I mentioned above.So i want a general EMT program in python.