Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error code=H10 desc="App crashed" method=GET I Have Installed Gunicorn But Its Showing Error
S:\commerce>heroku logs --tail 2021-05-21T10:25:33.854236+00:00 heroku[web.1]: Starting process with command gunicorn commerce.wsgi 2021-05-21T10:25:43.278367+00:00 app[web.1]: bash: gunicorn: command not found 2021-05-21T10:25:43.400110+00:00 heroku[web.1]: Process exited with status 127 2021-05-21T10:25:43.568812+00:00 heroku[web.1]: State changed from starting to crashed 2021-05-21T14:59:02.000000+00:00 app[api]: Build started by user sasikiran9008@gmail.com 2021-05-21T14:59:24.997986+00:00 app[api]: Deploy 87eb2006 by user sasikiran9008@gmail.com 2021-05-21T14:59:24.997986+00:00 app[api]: Release v7 created by user sasikiran9008@gmail.com 2021-05-21T14:59:25.349888+00:00 heroku[web.1]: State changed from crashed to starting 2021-05-21T14:59:29.813084+00:00 heroku[web.1]: Starting process with command gunicorn commerce.wsgi 2021-05-21T14:59:32.842749+00:00 app[web.1]: bash: gunicorn: command not found 2021-05-21T14:59:32.923810+00:00 heroku[web.1]: Process exited with status 127 2021-05-21T14:59:33.030602+00:00 heroku[web.1]: State changed from starting to crashed 2021-05-21T14:59:33.034357+00:00 heroku[web.1]: State changed from crashed to starting 2021-05-21T14:59:34.000000+00:00 app[api]: Build succeeded 2021-05-21T14:59:37.919248+00:00 heroku[web.1]: Starting process with command gunicorn commerce.wsgi 2021-05-21T14:59:41.312865+00:00 app[web.1]: bash: gunicorn: command not found 2021-05-21T14:59:41.391741+00:00 heroku[web.1]: Process exited with status 127 2021-05-21T14:59:41.491046+00:00 heroku[web.1]: State changed from starting to crashed 2021-05-21T14:59:42.648833+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=bidnow.herokuapp.com request_id=8e722e31-cb06-464b-97e5-93ee64ca52cc fwd="183.82.159.32" dyno= connect= service= status=503 bytes= protocol=https 2021-05-21T14:59:43.208695+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=bidnow.herokuapp.com request_id=a5875b3e-c7e1-475a-938b-f5d919302466 fwd="183.82.159.32" dyno= connect= service= status=503 bytes= protocol=https 2021-05-21T15:00:34.201010+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=bidnow.herokuapp.com request_id=e4e5f718-dace-4847-b085-94339c7eb82b fwd="183.82.159.32" dyno= connect= service= status=503 bytes= protocol=https 2021-05-21T15:00:34.827530+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=bidnow.herokuapp.com request_id=7069f835-7bcd-40d6-a5df-5ef5a5e34582 fwd="183.82.159.32" dyno= connect= service= … -
How to get the action name, and the new value in django singals
Goal: I am trying to get the new value and the name of the fields after changing a field and the new values of all the fields after changing multiple fields and the new values of all the fields after creating a new model from the instance variable in the signal receiver @receiver(signals.post_save) def __init__(instance, sender, signal, *args, **kwargs): print('======================') print({'actoin':instance.<somthings.somthigs>}) # get the action type like, change, create, delete print({'field/s':instance.<somthings.somthigs>}) # when you change a field value it returns to me the new value of the field print({'model':instance.<somthings.somthigs>}) # get the model that has beend changed print({'user':instance.user}) # I already now how to do this I can get the user how made the changes print({'final model':sender.objects.all()}) #I know how to do this as welll -
http python youtube video downloader error
File "C:\Users\dilkh\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 641, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 404: Not Found -
How to loop over Chart.js with Django list view
I am using a Django List View, and I am trying to iterate through multiple objects and display percentage values in a Chart.JS gauge. However, although I am iterating the names of the gauge id's by using a for loop counter, I am only ever getting the first iteration of the chart.js object rendering on my screen. My initial thoughts are that similar to how I am dynamically creating new canvas ids for the chart.js objects, I should be doing a similar thing for the variable I am trying to pass into the chart object e.g. reduction overall, but I am not having any luck. Your feedback is welcome. Views.py class PerformanceDetailView(ListView): template_name = 'performance_detail.html' model = Performance context_object_name = 'performance' def get_queryset(self, **kwargs): code = self.kwargs.get('code') return Performance.objects.filter(code=code) Performance_detail.html <section class="projects pt-4 col-lg-12"> {% for item in performance %} <div class="container-fluid pt-2 col-lg-12"> <!-- Project--><div class="project" > <div class="row bg-white has-shadow" style="height: 14rem"> <div class="left-col col-lg-2 d-flex align-items-center justify-content-between"> <div class="project-title d-flex align-items-center"> <div class="has-shadow"><img src="{% static 'img/avatar-2.jpg' %}" alt="..." class="img-fluid"></div> </div> </div> <div class="right-col col-lg-2 align-items-center vertical-center"> <div class="text"> <h3 class="h2 pt-2">{{item.brand}} {{item.style}}</h3> <p class="text-muted">{{item.package_type| capfirst}} package, round {{item.testing_round}}</p> <p class="text-muted">Item size: {{item.size}}</p> </div> </div> <div class="right-col col-lg-8 … -
DJANGO DATABASE AND PRODUCT DETAILS
HI, I'm walking with django creating ecommerce store, I have created a a product list page called index.html, now I'm trying to create a detail page so than when a customer click on the product the detail page will open...One one to help I cant view the database of my project -
How can I disable inline css input at WYSIWYG editor created with iframe?
I have created simple WYSIWYG editor with javascript execCommand. It works fine for me. But what if user edit the content before submitting form through elements section in browser. How to protect this these html elements before submitting? If user add inline style to some of the elements like position fixed? Then it will save the post with these changes in database which will cause problem in showing the data. I am working with django. -
Got django.db.utils.OperationalError: could not connect to server: Connection refused
I found a Django project and failed to get it running in Docker container in the following way: git clone git clone https://github.com/NAL-i5K/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y postgresql-client WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ RUN mkdir -p /var/log/django RUN mkdir -p /var/log/i5k For docker-compose.yml I use: version: "3" services: dbik: image: postgres volumes: - ./data/dbik:/var/lib/postgresql/data - ./scripts/install-extensions.sql:/docker-entrypoint-initdb.d/install-extensions.sql environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres ports: - 5432:5432 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - dbik links: - dbik $ cat scripts/install-extensions.sql CREATE EXTENSION hstore; I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } Next, I ran docker-compose up --build web_1 | System check identified no issues (0 silenced). web_1 | Unhandled exception in thread started by <function wrapper at 0x7f9bd41d26d0> web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 229, in wrapper web_1 | fn(*args, **kwargs) web_1 | … -
How to filter SUM(flag) OVER (...) with having in sqlite
WITH cte AS ( SELECT Q.Question_id, Q.Question, PMA.part_model_ans, QP.part_total_marks, MA.answer_mark, Q.rowid, Q.Question <> LAG(Q.Question, 1, '') OVER (PARTITION BY Q.Question_id ORDER BY Q.rowid) flag FROM QUESTIONS Q LEFT JOIN QUESTIONS_PART QP ON QP.question_id = Q.question_id LEFT JOIN PART_MODEL_ANSWER PMA ON PMA.part_id = QP.part_id LEFT JOIN MODEL_ANSWER MA ON MA.question_id = Q.question_id ) SELECT Question_id, Question, part_model_ans, part_total_marks, answer_mark, SUM(flag) OVER (PARTITION BY Question_id ORDER BY rowid) part FROM cte having part = 1 ORDER BY question_id What i would like to do is filter the part so that it only shows the rows with 1 in it however after using having part == 1 the expected result is still the same i do not know why it does not filter, where clause cannot be used due to misuse of aggregate -
Order_by the First Value in a Many to Many Field without duplicate entries
I have seen similar questions being asked for the same like Django order_by many to many relation and order_by on Many-to-Many field results in duplicate entries in queryset. But both of them and many more can't seem to answer my question.I have my models as follows. class TeamMember(common_models.CreateModifyModel): user_id = models.CharField(max_length=50, validators=[validate_ObjectId]) lms_user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) team = models.ManyToManyField(Team) class Team(common_models.CreateModifyModel): name = models.CharField(max_length=50) team_type = models.IntegerField(choices=team_type_choices, null=True, blank=True) is_active = models.BooleanField(default=True) The team variable has a many-to-many relationship with my model. I want to order_by the users where name inside the Team model is empty. My first approach was a naive one i.e queryset = self.get_queryset().filter(lms_user__email__in=[item.get('email') for item in email_res['response']]).order_by('team__name') the order_by in the end is not working and is giving duplicate entries for a user with multiple teams as it should. I came across Annotate and Subquery methods in Django and some of them introduced the Case-When to deal with this problem. The only thing that I NEED is to list the users with empty team names on the top AND for users that are assigned to multiple teams I want to get the first_instance of their team object which will avoid the duplicate user entries that … -
How to pass my data frame from one function to another function
I need to pass my dataframe from my panddf function to graphview function..How can i achieve this?? Am getting chart for all values from my db,I filtered out my data and i need to pass my data to graphview function!!!! from django.http import JsonResponse from django.shortcuts import render from board.models import userboard from.utils import get_plot import pandas as pd from sqlalchemy import create_engine def graphview(request): qs = userboard.objects.all() x=[x.Month for x in qs] y=[y.Bp_Values for y in qs] chart = get_plot(x,y) return render(request, 'piechart.html' ,{'chart':chart}) def panddf(request): username = None if request.user.is_authenticated: username = request.user.username print(username) engine=create_engine('postgresql+psycopg2://postgres:xxxxxx@localhost/vijay') df = pd.read_sql_query('SELECT * FROM public."board_userboard"',con=engine) filt = (df['User_name'] == username) print(df[filt]) return render(request, 'abc.html') -
i want to Show a "Thanks for voting" message after a user votes for all the positions and then it will show that message
after a user votes for all the available positions then its just redirecting to the Position page , and i want to show a Message or a alert that "the user has voted for all the positions". help me out how to do that? view.py: def home(request): return render(request, 'home.html') def registration(request): if request.method == "POST": form = RegistrationForm(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data if cd['password'] == cd['confirm_password']: obj = form.save(commit=False) obj.set_password(obj.password) obj.save() messages.success(request, 'You have been registered.') return redirect('home') else: return render(request, "registration.html", {'form':form,'note':'password must match'}) else: form = RegistrationForm() return render(request, "registration.html", {'form':form}) def login(request): if request.method == "POST": usern = request.POST.get('username') passw = request.POST.get('password') user = authenticate(request, username=usern, password=passw) if user is not None: dj_login(request, user) return redirect('dashboard') else: messages.success(request, 'Invalid username or password!') return render(request, "login.html") else: return render(request, "login.html") @login_required def candidate(request, pos): obj = get_object_or_404(Position, pk = pos) if request.method == "POST": temp = ControlVote.objects.get_or_create(user=request.user, position=obj)[0] if temp.status == False: temp2 = Candidate.objects.get(pk=request.POST.get(obj.title)) temp2.total_vote += 1 temp2.save() temp.status = True temp.save() return HttpResponseRedirect('/position/') else: messages.success(request, 'Thanks for voting, you have already been voted this position.') return render(request, 'candidate.html', {'obj':obj}) else: return render(request, 'candidate.html', {'obj':obj}) HTML: this is my HTML HOME Template {% load … -
Django Error "django.core.exceptions.ValidationError: ['“h” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']"
I added a DateTimeField to one of my models but forgot to provide a default value in my models. When I ran the command python manage.py makemigrations it asked for a default value and I mistakenly gave 'h' as my default value, completely forgetting that it was a datetime field. Now I am getting this error. I deleted that line and also deleted the dbsqllite3 file, but the problem still persists. What can I do now to get rid of this error? -
I want to display those images on next page :Django
i want to open those images on next pagebut showing me this error : page not found -
Es mi primer proyecto con django y me aparece este error Not Found: /serviceworker.js
este es el views enter image description here y este el urls.py enter image description here -
Flutter google sign in authenticate django social auth for google
I am creating a flutter android app which uses google sign in. Once logged in, I recieve accesstoken and idtoken. I want to use this token to authenticate my backend which uses django social auth and Login and return the authoken, if the user has already signed up, or Register the user , login and return the user id and authtoken. Is this possible ? If so please suggest any documents online or please explain how should I approach this. -
Error Showing whenever I try to post without img Django
I'm trying to create a social media but whenever I try to post some post without an image field it's throwing me an Error saying "The 'post_img' attribute has no file associated with it.". It works fine when I post something with the image but I want it to be like Twitter where you can post a blog and Image. So I don't know what's going on. Models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model User = get_user_model() from PIL import Image # Create your models here. class PostTag(models.Model): tag = models.CharField(max_length=10) def __str__(self): return self.tag class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField(null = True, blank=True) post_img = models.ImageField(upload_to = "posts_img", null = True, blank = True) pub_date = models.DateTimeField(default = timezone.now) post_tag = models.ForeignKey(PostTag, on_delete=models.SET_NULL, null= True,blank=True) author = models.ForeignKey(User, on_delete= models.CASCADE) def __str__(self): return f"{self.title} / {self.author}" if post_img: def save(self,*args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.post_img.path) if img.height > 600 or img.width > 600: output_size = (600, 600) img.thumbnail(output_size) img.save(self.post_img.path) views.py from django.shortcuts import render,redirect from django.contrib.auth.decorators import login_required from .forms import PostCreateForm from django.contrib import messages # Create your views here. @login_required(login_url="users:index") def posts_view(request): form = PostCreateForm(request.POST or None, request.FILES … -
Django cumulative value displayed in template
I’m new to Django and Python and have been plugging through Python Crash Course. I have finished that and now have been making my own Django project, adding some extra bits in. Currently, I have a table of entries from my model which I am displaying with a template, each entry in the table has a time and some other data. What I would like is the value for the cumulative time in a column, next to each entries time ie Lesson Lesson time cumulative time Lesson1 0.5 0.5 Lesson2 1 1.5 Lesson3 1.3 2.8 I’m just really stuck on how to get this done, I have looked at lot’s of stack overflow and tried various ways that I just can’t get to work correctly. Looking at other examples they use annotate() and cumsum, but I’ve not been able to get that to work. I’ve done count and sum of other values but this has got me stuck. I think I need to loop over it in my view, but not sure how to associate each value to a cumulative time. Any help would be greatly received. Also, sorry this isn't very well written or succinct, programming doesn't come naturally … -
Error when deploying python app on heroku
I am trying to deploy my Python app on Heroku, but have been unsuccessful. It seems that a problem is occurring with the PyICU package, which I'm unsure how to correct. But that is probably not the only error. Here is an excerpt from the log: -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt -----> Installing python-3.7.10 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing SQLite3 -----> Installing requirements with pip .... WARNING: The candidate selected for download or install is a yanked version: 'python-Levenshtein' candidate (version 0.12.0 at https://files.pythonhosted.org/packages/42/a9/d1785c85ebf9b7dfacd08938dd028209c34a0ea3b1bcdb895208bd40a67d/python-Levenshtein-0.12.0.tar.gz#sha256=033a11de5e3d19ea25c9302d11224e1a1898fe5abd23c61c7c360c25195e3eb1 (from https://pypi.org/simple/python-levenshtein/)) Reason for being yanked: Insecure, upgrade to 0.12.1 Collecting python-Levenshtein==0.12.0 Downloading python-Levenshtein-0.12.0.tar.gz (48 kB) Collecting python-monkey-business==1.0.0 Downloading python_monkey_business-1.0.0-py2.py3-none-any.whl (5.5 kB) Collecting python-utils==2.4.0 Downloading python_utils-2.4.0-py2.py3-none-any.whl (12 kB) Collecting pytz==2019.3 Downloading pytz-2019.3-py2.py3-none-any.whl (509 kB) Collecting PyYAML==5.3.1 Downloading PyYAML-5.3.1.tar.gz (269 kB) Collecting regex==2020.6.8 Downloading regex-2020.6.8-cp37-cp37m-manylinux2010_x86_64.whl (661 kB) Collecting requests==2.24.0 Downloading requests-2.24.0-py2.py3-none-any.whl (61 kB) Collecting rutermextract==0.3 Downloading rutermextract-0.3.tar.gz (8.1 kB) Collecting six==1.13.0 Downloading six-1.13.0-py2.py3-none-any.whl (10 kB) Collecting soupsieve==2.0 Downloading soupsieve-2.0-py2.py3-none-any.whl (32 kB) Collecting sqlparse==0.3.1 Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Collecting tablib==2.0.0 Downloading tablib-2.0.0-py3-none-any.whl (47 kB) Collecting tqdm==4.46.1 Downloading tqdm-4.46.1-py2.py3-none-any.whl (63 kB) Collecting unicodecsv==0.14.1 Downloading unicodecsv-0.14.1.tar.gz (10 kB) … -
django deployment on-premise with license
I've developed a Django webapp that I have hosted on Azure. Now, my customer wants to deploy it in his customer environment at enterprise level. So, I want to add a license to this on-premise webapp. The problem is that since I've to deploy the python code itself adding a license check is almost useless. I could not find a way to compile the Django python code either. Does anybody have a solution to this licensing issue and, on-premise Django webapp deployment experience/suggestions? Can using docker be a solution? -
django activation field does not change
I've succeeded to send email for activation. However, when user click on the link, the signup_confirmation field does not change. Here's my model: class UserProfile(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(blank=True, max_length=20) address = models.CharField(blank=True, max_length=150) city = models.CharField(blank=True, max_length=20) country = models.CharField(blank=True, max_length=20) image = models.ImageField(blank=True,storage = PrivateMediaStorage()) language = models.CharField(blank=True, max_length=20) gender = models.CharField(max_length=10, choices=GENDER,default="Other") signup_confirmation = models.BooleanField(default=False) def __str__(self): return self.user.username def user_name(self): return self.user.first_name + ' ' + self.user.last_name + ' [' + self.user.username + '] ' Here's my activated field: def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None # checking if the user exists, if the token is valid. if user is not None and account_activation_token.check_token(user, token): # if valid set active true user.is_active = True # set signup_confirmation true user.userprofile.signup_confirmation = True user.save() login(request, user) return redirect('activated') else: return render(request, 'user/activation_invalid.html') Somehow the code user.userprofile.signup_confirmation = True does not work. Please have a look -
Django clean method() raises 'Bid' object has no attribute 'kwargs'
I'm trying to restrict a bidder that bids on certain project via a form from bidding neither less than the minimum budget that the project publisher has specifies neither greater than the maximum budget. After checking similar problems i found that overriding the clean method is the most suitable, but i'm facing " 'Bid' object has no attribute 'kwargs' " error This is the clean method: def clean(self): if Project.objects.get(pk=self.kwargs['pk']).budget_min >= self.bid_amount or self.bid_amount >= Project.objects.get(pk=self.kwargs['pk']).budget_max: raise ValidationError('the bid amount should be between the minimum and maximum project budget') This is my models.py # projects/models.py from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.db import models from django.urls import reverse from django.core.validators import MaxValueValidator, MinLengthValidator, MinValueValidator from upload_validator import FileTypeValidator from .validators import user_directory_path, validate_file_size from multiselectfield import MultiSelectField class Project(models.Model): title = models.CharField( 'Choose a title for your project', max_length=255, validators=[ MinLengthValidator( 15, 'Title must be descriptive and greater than 15 characters') ] ) body = models.TextField('Tell us more about your project', max_length=3000, validators=[ MinLengthValidator( 10, 'Must be descriptive and greater than 10 characters') ] ) upload_file = models.FileField( upload_to=user_directory_path, verbose_name="upload file:(Max file size: 2.5 MB)", validators=[ validate_file_size, FileTypeValidator( allowed_types=[ 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'image/tiff', … -
CSRF validation works from Postman but not React/Axios
It's honestly a catastrophic blow to the ego I haven't already figured this out--spent 6 hours so far... I have a React app running off a Django Rest Framework backend. For the password reset functionality I am using Django's builtin view (auth_views.PasswordResetView). I have a form in React that accepts an email and sends a post request to reset the users password. The way I send the data in postman is: Url: http://192.168.0.85:8000/reset_password Body: {'email': 'blabla@bla.com'} Headers: {'X-CSRFToken': OGH9iUEtGPqntMYifQ5kiin2ufV9tK39tbp9Wmh6tLST0DXCXSkY8mOvyq5AjjnZ} ...and it works like a charm! Until I try to replicate the same exact call using axios in React: axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; axios.post('http://192.168.0.85:8000/reset_password',{'email': 'blabla@bla.com'},{headers})) ...this results in a 403 error with this message from the backend: WARNING:django.security.csrf:Forbidden (CSRF cookie not set.): /reset_password I've spent 6 hours googling and experimenting and can't figure out for the life of me why the Axios request would be any different than the Postman one. This problem is particularly infuriating because @csrf_exempt won't work on the django builtin views. -
CropperJS : Images stored in server (Django)
How to crop Images stored in server? I'm not using a form since I'm not uploading the image. How can this be done? Django View from .models import Image def main_view(request): obj = Image.objects.get(pk=1) context = {'obj':obj} return render(request, 'main.html',context) HTML + CROPPERJS <div> <img src="{{obj.file.url}}" id="image" width="400px" > <button id="button">Crop</button> </div> <script> const image = document.getElementById('image'); const cropper = new Cropper(image, { aspectRatio: NaN, crop(event) { console.log(event.detail.x); console.log(event.detail.y); console.log(event.detail.width); console.log(event.detail.height); console.log(event.detail.rotate); console.log(event.detail.scaleX); console.log(event.detail.scaleY); }, }); (Ajax logic to send the cropped image to the server) -
what makes FormView a better fit/choice than Createview?
just in general, i usually use and see people use "CreateView" that saves automatically to the data base, while the save "FormView" needs to be triggered in form_valid function, But, beside that i was wondering: is there other uses of "FormView"? better uses of form_valid? does both "CreateView", and "FormView" do the same job (in general)? what are the mean differences/cases? thanks for the explanations. -
How to submit create view with ManytoMany model
so I am trying to do a CreateView class which saves recipe entered by user, however instead of using a textfield, I am trying to capture each measurement of each ingredient. My models: I am not sure if the problem lies here class IngredientList(models.Model): ... class Recipe(models.Model): cuis = [ ('Italian', 'It'), ('French', 'Fr'), ] title = models.CharField(max_length=100) ingredients = models.ManyToManyField( IngredientList, through='ShoppingList') instructions = models.TextField(max_length=3000) serving_size = models.IntegerField(default=0) cuisine_type = models.CharField( max_length=100, choices=cuis, blank=True, null=True) image = models.ImageField(default='recipe.jpg', blank=True, null=True) duration = models.IntegerField(blank=True, default=0) def __str__(self): return self.name def get_absolute_url(self): return reverse('recipe-detail', kwargs={'pk': self.pk}) class RecipeList(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredients = models.ForeignKey(IngredientList, on_delete=models.CASCADE) measurement = models.FloatField(default=1) def __str__(self): return self.recipe.title My form: class RecipeForm(forms.Form): name = forms.CharField() ingredient = forms.ModelMultipleChoiceField( IngredientList.objects.all(), widget=forms.CheckboxSelectMultiple) measurement = forms.IntegerField() instructions = forms.CharField(widget=forms.Textarea) serving_size = forms.IntegerField() cuisine_type = forms.ChoiceField(choices=RecipeList.cuis) duration = forms.IntegerField() And the views : class RecipeCreateView(FormView): template_name = "recipe/recipeList_form.html" form_class = RecipeForm success_url = reverse_lazy('recipes') def form_valid(self, form): self.name = form.cleaned_data['name'] self.ingredient = form.cleaned_data['ingredient'] self.measurement = form.cleaned_data['measurement'] self.instructions = form.cleaned_data['instructions'] self.serving_size = form.cleaned_data['serving_size'] self.cuisine_type = form.cleaned_data['cuisine_type'] self.duration = form.cleaned_data['duration'] recipe = Recipe(name=self.name, instructions=self.instructions, serving_size=self.serving_size, cuisine=self.cuisine_type, duration=self.duration) recipe.save() ingredient_list = IngredientList.objects.filter(pk__in=self.ingredient) for i in ingredient_list: recipe.ingredients.add(i) return super(RecipeCreateView, self).form_valid(form) The problem is, …