Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django MultiValueDictKeyError at /accounts/login/
so I got a code error MultiValueDictKeyError at /accounts/login/. MultiValueDictKeyError picture The error appears when I'm trying to send password reset email. Here's my code: views.py: from email.policy import default from django.http import HttpResponse from django.shortcuts import redirect, render from accounts.forms import registrationForm from accounts.models import Account from django.contrib import messages, auth from django.contrib.auth.decorators import login_required #verification stuff from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.encoding import force_bytes from django.contrib.auth.tokens import default_token_generator from django.core.mail import EmailMessage # Create your views here. def register(request): if request.method == 'POST': form = registrationForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] phone_number = form.cleaned_data['phone_number'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] username= email.split("@")[0] user = Account.objects.create_user(first_name=first_name, last_name=last_name, email=email, username=username, password=password) user.phone_number = phone_number user.save() #Account activation current_site = get_current_site(request) mail_subject = 'Please activate your account' message = render_to_string('accounts/account_verification.html', { 'user': user, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) to_email = email send_email = EmailMessage(mail_subject, message, to=[to_email]) send_email.send() return redirect('/accounts/login/?command=verification&email='+email) else: form = registrationForm() context = { 'form': form, } return render(request, 'accounts/register.html', context) def login(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = auth.authenticate(email=email, password=password) if user is not None: auth.login(request, user) messages.success(request, … -
Unable to join static file to root directory in Django
To join the static file in Django, STATIC_URL = "os.path.join(BASE_DIR, '/static/')" print("static file : ", (os.path.join(BASE_DIR, '/static')), ) This is producing : static file : C:/static But in the same document I had joined template folder: print("Path is : ", os.path.join(BASE_DIR, 'myproject/template')) Which produces this: Path is : C:\Users\user\Desktop\django\myproject\myproject/template Is this the reason Django is producing this error: ERRORS: ?: (urls.E006) The STATIC_URL setting must end with a slash. Could you please advise how can i resolve this error? -
Django views receives incomplete POST data
I am sending Axios post data from React app to Django views, However, some of the data is missing when receiving it in the Django view. here is my code : axios .post("http://127.0.0.1:8000/vrp-api/solver/", serverData) .then((response) => { const activeArcs = JSON.parse(response.data).activeArcs; const nodes = createLocations(); const routes = generateVehicleDelivery(activeArcs); let pathIndex = 1; Object.keys(routes).forEach((key) => { let route = routes[key]; route.forEach((arc, i) => { const formattedLocation = `${nodes[arc[0]].lng},${ nodes[arc[0]].lat }:${nodes[arc[1]].lng},${nodes[arc[1]].lat}`; setTimeout(() => { tServices.services .calculateRoute({ key: "I6kBz902v7AXAGvD9J7DNysPz9DkfQMP", locations: formattedLocation, }) .then((routeData) => { pathIndex++; const geoJson = routeData.toGeoJson(); console.log("calculateRoute ===>>", geoJson); drawRoute(geoJson, pathIndex); }); }, i * 3000); }); }); }) .catch((error) => { console.log(error); }); Django code : @api_view(['POST']) @permission_classes([AllowAny]) def solve_vrp(request): data = json.loads(request.body) print(data) an example of what I'm sending is : {"0,1": 5291, "0,2": 5291, "0,3": 5291, "1,0": 4795 ,"1,2": 0, "1,3": 0, "2,0": 4794, "2,1": 0, "2,3": 0, "3,0": 4795, "3,1": 0, "3,2": 0} but actually, I'm receiving only : {"0,1":5291, "0,2":5291, "0,3":5291, "1,0":4794, "1,2":0, "1,3":0, "2,0":4795, "2,1":0, "2,3":0} -
I can't get product vendor id in django
I am working on an e-commerce project. But the product vendor id is not registered in the database. I've tried many ways. I would be glad if you help. seller_id always comes empty What are your suggestions? models.py class Product(models.Model): name = models.CharField(verbose_name="Məhsulun adı", max_length=150) description = models.TextField( verbose_name="Məhsul haqda məlumat", null=True) price = models.FloatField(verbose_name="Məhsulun Qiymət") quantity = models.IntegerField(verbose_name="Məhsulun sayı",) seller = models.ForeignKey( Shop, on_delete=models.CASCADE, verbose_name="Məhsulun satıcısı", null=True ) categories = models.ManyToManyField( Category, verbose_name="Məhsulun kateqoriyaları", related_name='categories') tags = models.ManyToManyField(Tags, verbose_name="Məhsulun etiketləri") discount = models.IntegerField( null=True, blank=True, verbose_name="Endirim", default=0) active = models.BooleanField(default=True, verbose_name="Mağazada göstər",) created_at = models.DateTimeField(auto_now_add=True, null=True) colors = models.ManyToManyField(Colors, verbose_name='Məshulun rəngləri') views.py if request.method == 'POST' and 'addProduct' in request.POST: main_image = request.FILES['main_image'] # form = AddProductForm(request.POST) images = request.FILES.getlist('images') if form.is_valid(): form.seller = request.user.id print(request.user.id) form = form.save(commit=False) form.save() # Product.objects.create(seller=request.user) ProductImages.objects.create(product=form, image=main_image) ProductInfo.objects.create(product=form) for image in images: print(image) ProductImages.objects.create(product=form, image=image) return redirect('shop:shopProducts') else: print(form.errors) forms.py class AddProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddProductForm, self).__init__(*args, **kwargs) self.fields['price'].widget.attrs.update( {'placeholder': 'Qiymət'}) self.fields['name'].widget.attrs.update( {'placeholder': 'Məhsulun Adı'}) for field in self.fields: self.fields[field].widget.attrs.update({'class': 'form-control'}) self.fields['active'].widget.attrs.update( {'class': ''}) class Meta: model = models.Product fields = ['name', 'description', 'price', 'colors', 'discount', 'quantity', 'active', 'categories', ] #'thumbnail','images', widgets = { 'price': forms.TextInput(), 'off': forms.TextInput(), } -
How to test the data with original data taken from user
I really need your help guys. I am working on a project and really confuse. Using Python, Jupyter Notebook Want to give the model inputs from the user to check what the model will predict (by giving them the original values[Text format + Numerical ] ) but for training I changed the test data below: I have trained the model by pre process it with Removing outliers-> Factorize(Converting to numerical) -> Normalize During Factorization I used this code def factorize_fun(df): obj_cols = df.loc[:, df.dtypes == object].columns for col in obj_cols: df[col] = pd.factorize(df[col])[0] +1 return df df6=factorize_fun(df6) In factorization it makes the data like 1,2,3,4 for any different values found in a column. Knn Imputer to complete the missing values import numpy as np from sklearn.impute import KNNImputer def knn_null(df): imputer = KNNImputer(n_neighbors=2) df1 = imputer.fit_transform(df) df2 = pd.DataFrame(df1, columns = df.columns) return df2 df6=knn_null(df6) It changed the date from this this I trained my model on numerical values and got good results. X_train, X_test, y_train, y_test = train_test_split(normalize(df6), y, test_size=0.2, random_state=0) rfc=RandomForestClassifier() rfc1=RandomForestClassifier( random_state=42, max_features='auto', n_estimators= 90, max_depth=8, criterion='gini' ) rfc1.fit(X_train, y_train) y_pred=rfc1.predict(X_test) print("Accuracy for Random Forest on CV data: ",accuracy_score(y_test,y_pred)) print(metrics.classification_report(y_test,y_pred)) df_cm = pd.DataFrame(confusion_matrix(y_test,y_pred), index = [i for … -
I want to write a if condition based in what url my user was before being took for the specific cart view
I'm building an ecommerce site and I built a specific view to handle with adding products in a cart, and after the product is added, my user is redirect to a store. But here is the thing, I want to see if my user was in the store view, where are all the products, of if he was in the product_detail view, where it shows only a specific user. So, if the user was in the store view, I want him to be redirected, after the product was added in the cart, to the store view. But if he was in the product_detail view, I want him to be redirected to this product_detail view. So basically I want to find a way to see in what view, or url, my user was, and then redirect in this way. I also would like to only use Django and no JavaScript, if it's possible. Here is my view that add a product to cart. def add_to_cart(request, slug): product = get_object_or_404(Product, slug=slug) order_item, created = OrderItem.objects.get_or_create( product=product, user=request.user ) order_qs = Order.objects.filter(user=request.user, complete=False) if order_qs.exists(): order = order_qs[0] if order.products.filter(product__slug=product.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, 'This item quantity was updated') else: order.products.add(order_item) messages.info(request, … -
How to redirect user to requested url after login? (LoginRequiredMixin Django)
I don't know how to properly redirect user. I've tried so many solutions from the internet that I can't remember them now coz of my frustration. These solutions use def views but I have class views in my app and I don't know how to get this next parameter. I have a class view which requires login: class EditSportFieldView(LoginRequiredMixin, View): login_url = "/sign-in/" (...) I am at the url http://127.0.0.1:8000/sign-in/?next=/sport-field/edit/1/ and after login in I want to go to http://127.0.0.1:8000/sport-field/edit/1/ but instead I go back to the main page http://127.0.0.1:8000/ Here is my sigin in view class: class SignInView(LoginView): template_name = "sign-in.html" redirect_field_name = "sign-in" # def get_success_url(self): # return ("/") def get_redirect_url(self): redirect_to = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name, "") ) return redirect_to Why I am such a noob? and how to solve it please? P.S. erros change so fast that I missed that now this redirection takes me to Page not found http://127.0.0.1:8000/accounts/profile/ -
How To Successfully Install Django Using PyCharm Terminal
PS C:\Users\ISAAC EDOKA\Desktop\pilot> pip install django Requirement already satisfied: django in c:\users\isaac edoka\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\p ython310\site-packages (4.0.4) -packages\python310\site-packages (from django) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\isaac edoka\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-p ackages\python310\site-packages (from django) (0.4.2) Requirement already satisfied: tzdata in c:\users\isaac edoka\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\p ython310\site-packages (from django) (2022.1) WARNING: You are using pip version 22.0.4; however, version 22.1 is available. You should consider upgrading via the 'C:\Users\ISAAC EDOKA\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe -m pi p install --upgrade pip' command. django : The term 'django' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django --version + CategoryInfo : ObjectNotFound: (django:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException django : The term 'django' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path At line:1 char:1 django --version + CategoryInfo : ObjectNotFound: (django:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
How to convert svg to json and return it with JsonResponse in Django framework?
I got a view that takes JSON and converts it to.SVG file Next, I have to display this .svg image in my HTML file Using JsonResponse is mandatory because it returns other data not related to this question P.S. I'm using AJAX on the frontend to get some data from that view Is it possible to do this kind of manipulation with files or do you have other ideas on how to return SVG file to HTML? Thanks in advance -
Python Unittest: combine two tests into one subTest
i have two similar tests: def test_group_posts_context(self): response = self.author_client.get( reverse('posts:group_posts', kwargs={'slug': self.group.slug}) ) self.assertEqual(response.context.get('group'), self.group) def test_author_profile_context(self): response = self.author_client.get( reverse('posts:profile', kwargs={'username': self.user.username}) ) self.assertEqual(response.context.get('author'), self.user) Both tests work fine but I am trying to merge them in one single subTest. But construction, like this raises a ValueError: too many values to unpack (expected 2). def test_both_profile_and_group_show_correct_context(self): templates_page_names = { reverse('posts:index'), reverse('posts:group_posts', kwargs={'slug': self.group.slug}), reverse('posts:profile', kwargs={'username': self.post.author}), } for reverse_name in templates_page_names: with self.subTest(reverse_name=reverse_name): response = self.author_client.get(reverse_name) context_fields = { 'group': self.group, 'author': self.user, } for value, expected in context_fields: with self.subTest(value=value): context_field = response.context.get(value) self.assertEqual(context_field, expected) My reviewer says, that I should try to use a Tuple like (page_address, context name, expected object), but I actually cant figure out how to use it here :(. Views.py: def group_posts(request, slug): group = get_object_or_404(Group, slug=slug) page_obj = get_paginate( request.GET.get('page'), group.posts.select_related('author') ) context = { 'group': group, 'page_obj': page_obj, } return render(request, 'posts/group_list.html', context) def profile(request, username): author = get_object_or_404(User, username=username) page_obj = get_paginate( request.GET.get('page'), author.posts.select_related('group') ) context = { 'author': author, 'page_obj': page_obj, } return render(request, 'posts/profile.html', context) -
How to pass env variables to django in production
I'm deploying a Django application using Gunicorn. In my Dev setup I used dotenv library to import environment variables in top my settings.py as follows: from dotenv import load_dotenv load_dotenv() I have two setting files; one is the base settings (settings.py) and the other file is the production one (settings_prod.py) that overrides some variables this way: from .settings import * DEBUG = False ALLOWED_HOSTS = [ 'subdomain.example.com', ] AUTH_PASSWORD_VALIDATORS = [ # ... ] STATIC_URL = os.environ.get('STATIC_URL', '/static/') STATIC_ROOT = os.environ.get('STATIC_ROOT', BASE_DIR / 'static') I'm loading this file in Gunicorn Service as follows: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=user Group=user-group WorkingDirectory=/home/myApp/core/app Environment="DJANGO_SETTINGS_MODULE=application.settings_prod" ExecStart=/home/myApp/core/app/venv/bin/gunicorn \ --log-level=debug \ --error-logfile /home/myApp/core/database/logs/gunicorn.errors.log \ --access-logfile /home/myApp/core/database/logs/gunicorn.log \ --workers 3 \ --bind unix:/run/gunicorn.sock \ application.wsgi:application [Install] WantedBy=multi-user.target I tried adding EnvironmentFile=/home/myApp/core/app/.env to the service file but it didn't help -
running django inside docker image : connection to server at "localhost" (127.0.0.1), port 5432 failed
I m new to docker. I ve downloaded a docker image at docker pull lambci/lambda:build-python3.8 which is a aws image to run lambda functions. I ve a Dockerfile that is : Dockerfile: FROM lambci/lambda:build-python3.8 WORKDIR /var/task EXPOSE 8000 RUN echo 'export PS1="\[\e[36m\]zappashell>\[\e[m\] "' >> /root/.bashrc CMD ["bash"] I've run docker build -t zappa-docker-image . docker run -ti -p 8000:8000 -e AWS_PROFILE=zappa -v "$(pwd):/var/task" -v ~/.aws/:/root/.aws --rm zappa-docker-image When I run django inside my docker image (python manage.py runserver), i get the following error: OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address Is the server running on that host and accepting TCP/IP connections? I guess it's related to postgresql in my django settings : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbtest', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST': 'localhost', 'PORT': '5432', } } When I run the django server outside docker i dont get the error ... How can i solve this error in docker? -
How to check if URL is in Model/DB already on a URL Shortener? Django
i've been learning Django for these past days and i'm trying to develop an url shortener. It's functional and works great but it misses something: Check if the URL already exists so it can return the short URL stored in db. At this moments it's just checks if the short url is unique and does not exist already, so it always create a new and unique short url for the same URL. I've tried to use queryset's exists() in if ShortenerForm.objects.filter(url = cleaned_info['url']).exists(): but it always gave me an error object has no attribute 'cleaned_data' How can i do that? There are my files: views.py from django.http import Http404, HttpResponse, HttpResponseRedirect from django.shortcuts import render from utils.shorty.form import ShortenerForm from shorty.models import Shortener # Create your views here. def home(request): template = "shorty/pages/index.html" context = {} context["form"] = ShortenerForm() if request.method == "GET": return render(request, template, context) elif request.method == "POST": used_form = ShortenerForm(request.POST) if used_form.is_valid(): shortened_object = used_form.save() new_url = request.build_absolute_uri("/") + shortened_object.shortcode long_url = shortened_object.url context["new_url"] = new_url context["long_url"] = long_url return render(request, template, context) context["errors"] = used_form.errors return render(request, "shorty/pages/index.html") def redirect_url_view(request, shortened_path): try: shortener = Shortener.objects.get(shortcode=shortened_path) shortener.redirectCount += 1 shortener.save() return HttpResponseRedirect(shortener.url) except: raise Http404("Sorry this … -
Can I use python fastapi for large and complex web development project?
I am an django developer. Now I want to move fastapi but I am not fully confident. I have few question. question 1: Can fast api handle huge number of visitor like django? question 2: How strong fast api security level if we compare it with django? does it provide same level of security like django? Django provide security against sql injection, cross site scripting etc. question 3 Does fastapi scalable like django? question 4 Can we use fast api for build complex website where we have to do lot of background task? question 5 How fastapi user authentication work? is it similar to django? question 6 if you move to fastapi web framework? then what was the main reason for moving fastapi? which feature do you like most of fastapi? question 7 How big is fastapi community? is it large community like django? -
How can I post a variable from a python file to an html file in Django?
I am trying to make a face recognition page using PyTorch. When the face is recognized, I want to go to the next page and print the name of the recognized person. I wrote the code, but on the next page, None is printed. In my terminal, "POST / HTTP/1.1" 200 532 is printed repeatedly sometimes "GET /page HTTP/1.1" 200 308 is printed. That is, I want to output the name and min_dist from the get_frame of camera2.py in the page.html file. (camera2.py) name, min_dist ---post---> (page.html) name, min_dist urls.py from . import views urlpatterns = [ path('', views.home, name='home'), path('detectme', views.detectme, name='detectme'), path('page', views.get_post, name='page') ] views.py from django.shortcuts import render from django.views.decorators import gzip from django.http import StreamingHttpResponse from detectme.camera2 import FaceDetect def home(request): return render(request, 'home.html') def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def detectme(request): return StreamingHttpResponse(gen(FaceDetect()), content_type="multipart/x-mixed-replace;boundary=frame") def check(request): return render(request, "page.html") def get_post(request): if request.method == 'POST': student = request.POST.get('student') pred = request.POST.get('pred') data = { 'name' : student, 'pred' : pred } return render(request, 'page.html', data) if request.method == 'GET': student = request.POST.get('student') pred = request.POST.get('pred') data = { 'name' : student, 'pred' : pred } … -
Django with mysql database always return (2013, 'Lost connection to MySQL server during query')
I have a django app that was working perfectly until today. It is connected to a mysql database I was doing some tests in the python console and it started giving me the error (2013, 'Lost connection to MySQL server during query'). The problem now is that I have no way to access the application. It always returns the same error. It is very rare because it has started to happen suddenly. I've searched the stackoverflow questions but haven't been able to figure it out or find the error. This is error: The above exception ((2013, 'Lost connection to MySQL server during query')) was the direct cause of the following exception: File "/var/www/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/var/www/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 202, in _get_response response = response.render() File "/var/www/env/lib/python3.8/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/var/www/env/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/var/www/env/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/var/www/env/lib/python3.8/site-packages/django/template/base.py", line 170, in render return self._render(context) File "/var/www/env/lib/python3.8/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/var/www/env/lib/python3.8/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/var/www/env/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/var/www/env/lib/python3.8/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/var/www/env/lib/python3.8/site-packages/django/template/base.py", line 162, … -
Audio cannot pass from model to template - DJANGO
i want to pass audio file to template html from url. but when i add source, the audio controls doesn't work. i was copy how to pass audio file, but i don't know where's wrong. so please help me to fix this. at my terminal and console, there's no error message. here's my html : {% for record in rec %} <audio controls> <source src=" {% if record.audio %} {{ record.audio.url }} {% endif %}" type="audio/mp3"> </audio> {% endfor %} views.py : def mp3_audio(request): rec = Audio_store.objects.all() return render(request, 'homepage.html' , {'rec': rec }) urls.py : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), url(r'^$', views.homepage), path('audio', views.Audio_store), path("", views.homepage, name="homepage"), ] models.py : from django.db import models from django.core.files.storage import FileSystemStorage from django.forms import widgets fs = FileSystemStorage(location='media/mp3') fss = FileSystemStorage(location='media/txt') class Audio_store(models.Model): password=models.FileField(storage=fss, null=True) audio=models.FileField(storage=fs, null=True) -
How to get image from django inline ModelAdmin
I have such structure models.py: class Image(models.Model): article = models.ForeignKey('article', on_delete=models.CASCADE, null = True) image = models.ImageField(upload_to = "images/") class Article(models.Model): title = models.CharField(max_length = 255) admin.py: class ImageInline(admin.StackedInline): model = Image class ArticleAdmin(admin.ModelAdmin): inlines = [ ImageInline, ] How can I get images from ImageInline in ArticleAdmin for further use in template? P.S. I need these images to create a slider -
Django signal - Not Triggered
Hi all I am using the Django request_started signal to log django request from django.core.signals import request_started from django.dispatch import receiver logger = logging.getLogger(__name__) @receiver(request_started) def log_request(sender, environ, **kwargs): method = environ['REQUEST_METHOD'] path = environ['PATH_INFO'] logger.info(f"{method} {path}") but Diango signals are not logged -
How to display items individually django/javascript
So I'm coding a quiz app in django and I want to display the questions individually and once the user seleect an answer and click Next the next question will be displayed how can I do this models.py: class Question(models.Model): text = models.CharField(max_length=200) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.text) def get_answers(self): ''' Get the set of all the answers to the questions ''' return self.answer_set.all() class Answer(models.Model): text = models.CharField(max_length=200) correct = models.BooleanField(default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"question: {self.question.text}, answer: {self.text}, correct: {self.correct}" -
Django model, integers as choices
could you tell me if the following code is correct? I want to create a drop down that in the django admin will show a dropdown with a selection of integer: class Test(TimeStampedModel): """ Test specifications """ TIME_INTERVALS = Choices( ('SECONDS_30', 30) ('SECONDS_60', 60) ('SECONDS_90', 90) ('SECONDS_120', 120) ('SECONDS_150', 150) ('SECONDS_300', 300) ) sample_time = models.PositiveSmallIntegerField(choices=TIME_INTERVALS, default=TIME_INTERVALS.SECONDS_30) Thank you -
Django REST Framework how to output a cropped copy of an image in the serializer?
I have a question when working with images. I've overridden the save method in models, in order to save multiple versions of images. Now I want to use a second resized saved version of the image in the Serializer. Please advise how I can do this and is such a scenario possible? def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image) thumbnail_size = (500, 500) img.thumbnail(thumbnail_size) image_name, image_ext = os.path.splitext(self.image.path) custom_path1 = '{}_500{}'.format(image_name, image_ext) img.save(custom_path1, "JPEG", optimize=True, quality=75) -
Why create() method not being called in ViewSet when using "raw data"?
I'm having some trouble to identify what's wrong; I have an API that receives a POST with some information: then they are used as params to run some code and save an image. So far, all things were working correctly until I stumbled across this: When I use the "HTML Form" the 'create()' method in my 'views.py' works fine, but when I use the 'Raw Data' it also works but it don't trigger the 'create()' method in my ViewSet... Any idea on why is this happening? And, if I need to only use the 'HTML Form', how other services may post to my API in order to it runs the code accordinly? Here are my: models.py usuario = models.CharField(max_length=50) codigo = models.CharField(max_length=30) ambiente = models.CharField(max_length=30) itens = models.CharField(max_length=10000) imagem = models.ImageField(default='placeholder.jpg') def __str__(self): return self.codigo def nome_imagem(self): self.imagem = self.codigo + "_" + self.usuario + "_" + self.ambiente + ".jpg" def save(self, *args, **kwargs): self.nome_imagem() return super(Imagem, self).save(*args, **kwargs) serializer.py class Meta: model = Imagem fields = ['id','usuario','codigo','ambiente','itens','imagem'] views.py class ImagemViewSet(viewsets.ModelViewSet): queryset = Imagem.objects.all() serializer_class = ImagemSerializer def create(self, request, *args, **kwargs): informacao = request.data msglist = [] try: for value in informacao.values(): msglist.append(value) codigo = msglist[2] usuario = msglist[1] … -
I can't save Many to Many with through model, using ModelMultipleChoiceField
I'm stuck trying save many to many relationship through custom model, using ModelMultipleChoiceField. Django shows this error: Cannot assign "<QuerySet [<Project: MARKETING 7>]>": "ProjectEmployee.project" must be a "Project" instance. I can't find solution for this. models.py class Department(models.Model): name = models.CharField('Name', max_length=200, unique=True) class Employee(models.Model): department = models.ManyToManyField(Department, through='DepartmentEmployee') name = models.CharField('Name', max_length=200, unique=True) lastname = models.CharField('Last Name', max_length=200, unique=True) class DepartmentEmployee(models.Model): department = models.ForeignKey(Department, on_delete=models.PROTECT) employee = models.ForeignKey(Employee, on_delete=models.PROTECT) date_joined = models.DateField() forms.py class ProjectEmployeeForm(forms.ModelForm): project = forms.ModelMultipleChoiceField( required=True, queryset=Project.objects.all(), ) class Meta: model = ProjectEmployee fields = '__all__' views.py def project_employee(request, id): employee = get_object_or_404(Employee, id = id) if request.method == 'POST': form = ProjectEmployeeForm( request.POST or None, ) if form.is_valid(): f = form.save(commit=False) f.employee = employee f.save() redirect('employe:list') else: form = ProjectEmployeeForm() template = 'prject_employee.html' context = { 'form': form, } return render(request, template, context) urls.py path('<int:id>/project_employee/', project_employee, name='project_employee'), -
Displaying Image in Django
I have the following code which is suppose to print an image. from email.mime import image from django.http import HttpResponse import datetime from django.template.loader import render_to_string import base64 import math import random import matplotlib.pyplot as plt no_of_balls = 25 x = [random.triangular() for i in range(no_of_balls)] y = [random.gauss(0.5, 0.25) for i in range(no_of_balls)] colors = [random.randint(1, 4) for i in range(no_of_balls)] areas = [math.pi * random.randint(5, 15)**2 for i in range(no_of_balls)] plt.figure() plt.scatter(x, y, s=areas, c=colors, alpha=0.85) plt.axis([0.0, 1.0, 0.0, 1.0]) plt.xlabel("X") plt.ylabel("Y") plt.savefig('test.png') # with open("test.png", "rb") as image: # b64string = base64.b64encode(image.read()) def math_is_fun(request): now = datetime.datetime.now() with open("test.png", "rb") as image: b64string = base64.b64encode(image.read()) with open('encode.bin', "wb") as file: file.write(b64string) # file = open('encode.bin', 'rb') # byte = file.read() # file.close() # decodeit = open('test.png', 'wb') # decodeit.write(base64.b64decode((byte))) # decodeit.close() context = { 'time' : now, 'image' : decodeit, } HTML_STRING = render_to_string("home-view.html", context = context) return HttpResponse(HTML_STRING) Just some background. What I had done is created an image from some math formula and saved it to disk. Then since I am using render_to_string in django views, I assumed that the image has to be converted to string. Which I did using base64. I am having …