Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to start threads and wait for their end without blocking a Django server?
I have a problem with Django. I have a function that does heavy processing (dataframe manipulation). This task is executed after sending a form containing the necessary information to launch the processing which is heavy. I tried to create a thread for this function with Threading. The problem is that the process is well sent in background not to block the server except that an error appears. I think this error is normal. There are dash components (django-plotly-dash) that depend on the result of the heavy processing and since this heavy processing is sent in background django passes directly to the dash components that have no information to display and therefore returns an error. So I used Threading.join() to wait for the heavy processing to finish but it paralyzes the whole server. How can I avoid blocking the server and allow the user to navigate between pages without blocking the whole server because a heavy processing is in progress? Here is an example of execution : def read_csv(request): heavy_treatment(some_args) # <-- this block the server and return a dash componant return redirect(other_function_for_view) # <-- this loads the view containing the result of the heavy processing Then I decided to create … -
Looking up value in JSONField with unaccent and icontains
I have a Model with a JSONField: class MyModel(models.Model): locale_names = models.JSONField() The shape of the JSON Field is simple: keys are language codes (en, fr...) and values are translated strings. I'm trying to build a search query that does an unaccented icontains search on a translated value: MyModel.objects.filter(locale_names__en__unaccent__icontains="Test") This does not give the expected results, because Django interprets "unaccent" as a key to look up in the JSON, rather than the unaccent PostgreSQL function: -- Expected SQL query: something like SELECT "app_model"."*" ... FROM "app_model" WHERE UPPER(UNACCENT("messaging_blueprint"."locale_names" ->>'en')::text)) LIKE UPPER(UNACCENT('%Test%')) LIMIT 21 -- Actual SQL query SELECT "app_model"."*" ... FROM "app_model" WHERE UPPER(("messaging_blueprint"."locale_names" #>> ARRAY['en','unaccent'])::text) LIKE UPPER('%Test%') LIMIT 21 How can I tel Django to interpret __unaccent as the PostgreSQL function rather than a JSON path? -
How to access same uploaded file in memory throughout several different API calls in Django
I'm building a React/DRF app that should allow the user to upload an Excel file, then select a sheet from all available sheets in the file, and then select a column of data from the selected sheet before the processing of data takes place. I don't need to save down the file but only the final data that will be sent to the database. As there will be at least 3 separate API calls - upload file, selected sheet, select column - I'm wondering how to maintain access to that same file during the whole time in Django. Here's my frontend code: const DataProcessing: NextPage = () => { const [selectedFile, setSelectedFile] = useState<File>(""); const [isSelected, setIsSelected] = useState<boolean>(false); const [availableSheets, setAvailableSheets] = useState<Array<string>>([]); const [selectedSheet, setSelectedSheet] = useState<string>(""); console.log(availableSheets); console.log(selectedSheet); const changeHandler = (event: any) => { setSelectedFile(event.target.files[0]); setIsSelected(true); }; const handleSubmission = () => { const formData = new FormData(); formData.append("File", selectedFile); axios .post("http://localhost:8000/api/upload-file/", formData, { headers: { "Content-Type": "multipart/form-data", }, }) .then((response) => setAvailableSheets(response.data.available_sheets)) .catch((error) => { console.error("Error:", error); }); }; const handleSubmissionSheet = () => { axios .post("http://localhost:8000/api/selected-ar-sheet/", selectedSheet, { headers: { "Content-Type": "application/json", }, }) .then((response) => console.log(response)) .catch((error) => { console.error("Error:", error); }); }; … -
Use model method in class and override that method
I have a method called complete in my model, how can i use that in my class view, in my model method there is one parameter called person which is being passed i do not want my overriden method to use that parameter how can i acheive that. class Mymodel(models.Model): is_done = model.BooleanField() def complete(self, person): self.is_done = True self.save(update_fields=['is_done']) self.done_by.add(person) class MyView(SomeView): def complete_record(self): return Mymodel.complete(here it expects two arguments i need only self) and i want to get rid of self.done_by.add(person) in model's complete method -
problem while registering user in db django rest framework
hello i have a rest_framework project and this is the problem : and this is code (serializer and function in views.py) why username is like that? -
when using pipenv to create a virtual env I am getting this error
#Pipenv not working# ###when I try to use pipenv in my wsl shell this happens now! I have used pipenv in the past but all of for sudden today it isn't working. I tried uninstalling and reinstalling pipenv but it isn't working.### pipenv install django /usr/local/lib/python3.10/dist-packages/pkg_resources/__init__.py:123: PkgResourcesDeprecationWarning: 0.1.43ubuntu1 is an invalid version and will not be supported in a future release warnings.warn( /usr/local/lib/python3.10/dist-packages/pkg_resources/__init__.py:123: PkgResourcesDeprecationWarning: 1.1build1 is an invalid version and will not be supported in a future release warnings.warn( Creating a virtualenv for this project... Pipfile: /mnt/d/Projects/To-do-list/Pipfile Using /usr/bin/python3 (3.10.4) to create virtualenv... ⠸ Creating virtual environment...created virtual environment CPython3.10.4.final.0-64 in 445ms creator CPython3Posix(dest=/home/edzy/.local/share/virtualenvs/To-do-list-JHrSlGzr, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/edzy/.local/share/virtualenv) added seed packages: pip==22.2.2, setuptools==63.4.1, wheel==0.37.1 activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator ✔ Successfully created virtual environment!''' '''Traceback (most recent call last): File "/usr/local/bin/pipenv", line 8, in <module> sys.exit(cli()) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/vendor/click/core.py", line 1128, in __call__ return self.main(*args, **kwargs) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/cli/options.py", line 56, in main return super().main(*args, **kwargs, windows_expand_args=False) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/vendor/click/core.py", line 1053, in main rv = self.invoke(ctx) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/vendor/click/core.py", line 1659, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/vendor/click/core.py", line 1395, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/vendor/click/core.py", line 754, in invoke return __callback(*args, **kwargs) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/vendor/click/decorators.py", line 84, in new_func return … -
How to put csrf_token inside django form view
I am new in django and have faced a strange problem. If I create django template and insert {% csrf_token %} inside, it works well, but if I put @csrf_protect decorator to view, it gives me Forbidden 403 (CSRF verification failed. Request aborted). As I understand from django documentation, I can`t use both CsrfViewMiddleware and @csrf_protect. So here is the question: Is it possible to do csrf verification inside a view or should I always write templates in such situations? @csrf_protect def create_group(request): if request.method == "POST": Group.objects.create(**{key: request.POST[key] for key in request.POST}) return HttpResponseRedirect(reverse("groups:groups")) elif request.method == "GET": pass return HttpResponse(create_group_form) create_group_form = """ <form method="POST"> <label for="course">Course:</label><br> <input type="text" id="course" name="course"><br><br> <label for="length_in_months">Length in months:</label><br> <input type="number" id="length_in_months" name="length_in_months" min=1 max=12 required><br><br> <label for="price">Price:</label><br> <input type="number" id="price" name="price" min=1000 max=50000 required><br><br> <label for="number_of_students">Number of students:</label><br> <input type="number" id="number_of_students" name="number_of_students" min=3 max=30 required><br><br> <label for="lesson_duration">Lesson duration:</label><br> <input type="number" id="lesson_duration" name="lesson_duration" min=1 max=5 required><br><br> <label for="website">Website:</label><br> <input type="url" id="website" name="website"><br><br> <input type="submit" value="Submit"> </form> """ -
django email why should send both text and HTML versions of a message [duplicate]
This is an example of sending email from django document: from django.core.mail import EmailMultiAlternatives subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() why it sends both text and HTML versions of the message? I tried and send something else in text_content (like a digit or a letter ) and it still worked properly I can not get the role of text_content in this code -
Pass arguement to custom permision class in django
I have a custom permission class that extends the rest framework base permission. I am trying to pass an argument allowed_groups that will be a list of all the groups that have access to the particular view. This is my current custom permission implementation. class CustomUserPermisions(BasePermission): message = "Ooops! You do not have permissions to access this particular site" def has_permission(self, request, view): allowed_groups = [ 'group_hr', 'super_admin', 'employee'] user1 = Employee.objects.filter(user__email=request.user).first() user_groups = user1.user_group.all() for group in user_groups: if group.title in allowed_groups: return True return False I have tried adding an argument as follows. class CustomUserPermisions(BasePermission, allowed_groups): message = "Ooops! You do not have permissions to access this particular site" def has_permission(self, request, view): allowed_groups = [ 'group_hr', 'super_admin', 'employee'] user1 = Employee.objects.filter(user__email=request.user).first() user_groups = user1.user_group.all() for group in user_groups: if group.title in allowed_groups: return True return False but this is the error I am currently receiving. class CustomUserPermisions(BasePermission, allowed_groups): NameError: name 'allowed_groups' is not defined Is there a better way that I can do this? -
the password is not hashed when registering using AbstractBaseUser
I created expanded the base user using AbstractBaseUser created my UserManager and added it to the new user model. when registering with createsuperuser, everything goes fine, but if I manually create a user, his password is not hashed.\ managers.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username=None, email=None, phone=None, \ password=None, **extra_fields): """ Creates and saves a User with the given email and password. """ if not username: if not email and not phone: raise ValueError('The given email/phone must be set') if email: email = self.normalize_email(email) if not username: username = email user = self.model( email=email, username=username, **extra_fields ) if phone: if not username: username = phone user = self.model( username=username, phone=phone, **extra_fields ) if extra_fields.get('is_superuser'): user = self.model( username=username, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(username=username, email=email, password=password, **extra_fields) def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user( username=username, password=password, **extra_fields ) models.py from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser # from django.utils.translation import ugettext_lazy as _ from custumuser.managers import UserManager class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(verbose_name='username', … -
Django permissions and content_type objects after model deletion
When a Django model is deleted, its permissions and content_type objects related to it keep on existing, do they have any other purpose too? or should they have been deleted with the model? -
Using Tempfile as intermediate storage before uploading to model
My Django app takes the context file, and converts it into pdflatex file. The output directory is given as f'{current_path}/media/pdf'. Everything works as expected. rendered_file = template.render(context).encode('utf-8') process = subprocess.Popen( ['pdflatex', '-output-directory', f'{current_path}/media/pdf'], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_file) A problem arises when I try to run it on Heroku server. I use AWS S3 as storage. The file can not be saved with an url like this. But I need to use a model to upload the pdf file. This is the model: class pdfUploadModel(models.Model): auto_increment_id = models.AutoField(primary_key=True, default=True) image = models.ImageField(null=True, blank=True, upload_to="pdf/") As soon as the file is saved in my directory, I could upload it to the model. But as long as I can not save it in a directory, there is no way to upload it to the model. My idea is to use a temporary directory which will be created on heroku and deleted afterwards again. I do not know if this is the right approach, or if there is a more elegant solution to my problem. It would look something like this: with tempfile.NamedTemporaryFile() as name: rendered_file = template.render(context).encode('utf-8') process = subprocess.Popen( ['pdflatex', '-output-directory', ---tempdirectory--], #here should be the tempdirectory stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_file) with … -
Safaricom Daraja: Duplicate json key detected
I am implementing Lipa na M-Pesa online by Safaricom. However, when I make the request, I get an error saying duplicate json keys detected. The Payload: payload = { "BusinessShortCode": 174379, "Password": "the password", "Timestamp": "20220817050503", "TransactionType": "CustomerPayBillOnline", "Amount": 5, "PartyA": 254714895622, "PartyB": 174379, "PhoneNumber": 254714895622, "CallBackURL": "https://58fa-102-68-78-50.in.ngrok.io/api/v1/payments/callback/", "AccountReference": "Payment", "TransactionDesc": "Payment for K" } The headers: headers = { "Content-Type": "application/json", "Authorization": "Bearer access_token", } The request: response = requests.request("POST", 'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest', headers=headers, data=payload) The response I get: { 'responseId': '82699-21939686', 'responseCode': '400', 'responseDesc': 'Duplicate json key detected' } What could be the cause of this error and how can I go about solving it? -
(DJANGO + S3) + ZAPPA An error occurred (400) when calling the HeadObject operation: Bad Request
I have a project with django and s3(acl enable private, public), the deployment is done with zappa when i try to upload a file to a specific s3 bucket through the django admin. i got the following error error: ClientError at /admin/main/document/1/change/ An error occurred (400) when calling the HeadObject operation: Bad Request Request Method: POST Request URL: https://xxxxx.execute-api.us-east-1.amazonaws.com/prd/admin/main/document/1/change/ Django Version: 3.2.3 Exception Type: ClientError Exception Value: An error occurred (400) when calling the HeadObject operation: Bad Request Exception Location: /var/runtime/botocore/client.py, line 719, in _make_api_call Python Executable: /var/lang/bin/python3.8 Python Version: 3.8.13 Python Path: ['/var/task', '/opt/python/lib/python3.8/site-packages', '/opt/python', '/var/runtime', '/var/lang/lib/python38.zip', '/var/lang/lib/python3.8', '/var/lang/lib/python3.8/lib-dynload', '/var/lang/lib/python3.8/site-packages', '/opt/python/lib/python3.8/site-packages', '/var/task', '/var/task/odf', '/var/task/odf', '/var/task/odf', '/var/task/odf', '/var/task/odf', '/var/task/odf', '/var/task/odf'] Server time: Wed, 17 Aug 2022 05:20:25 +0000 /var/task/storages/backends/s3boto3.py, line 469, in exists self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) zappa_settings.json { "prd": { "aws_region": "us-east-1", "django_settings": "xxx.settings", "profile_name": "default", "project_name": "xxxx", "runtime": "python3.8", "s3_bucket": "zappa-xxx-prd", "environment_variables": { "AWS_DEFAULT_REGION": "us-east-1", "AWS_S3_ACCESS_KEY_ID": "xxxxxxx", "AWS_S3_SECRET_ACCESS_KEY": "xxxxxx", "AWS_ACCESS_KEY_ID": "xxxxx", "AWS_SECRET_ACCESS_KEY": "xxxxxx" } } } user -> aws configure had a next general policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": [ "lambda:*", "s3:*", "events:*", "iam:CreateServiceSpecificCredential", "iam:GetRole", "iam:CreateRole", "iam:PutRolePolicy", "iam:PassRole", "iam:CreateServiceLinkedRole", "apigateway:PUT", "apigateway:DELETE", "apigateway:PATCH", "apigateway:POST", "apigateway:GET", "logs:DescribeLogStreams", "logs:FilterLogEvents", "cloudformation:DescribeStackResource", "cloudformation:DescribeStacks", "cloudformation:CreateStack", "cloudformation:DeleteStack", "cloudformation:UpdateStack", "cloudformation:ListStackResources" ], … -
how to ip proxy in django route
There are websites like, "XYZ.com" and "ABC.com" and those websites can only accessible with such range of ip address. we have public IP and using that public IP website's accessible. (with only office premises we can access those website) I have to develop a website in django using that i can access those websites out side that public ip range. plan to access those website like, (djangoproxy.com is my website) XYZ.djangoproxy.com ABC.djangoproxy.com but that access only based on authenticate user so i have logic on djangoproxy.com for authentic user but after successfully login open third party website in same browser tab. Had checked some python packages for vpn, https://gist.github.com/Lazza/bbc15561b65c16db8ca8 Reference: Python requests, change IP address can you guid me if this functionality can develop using python code or any web-server configuration. i am using Nginx as a web-server to host djangoproxy.com. -
Relation does not exist "userAuthentication_user" when migrate Django
I am trying to install my Django project on an Ubuntu 20.04 instance on AWS. I have done the necessary configurations. But when I go to perform the migrations, I get this error. The userAuthentication_user are internal tables that are managed for authentication in Django. -
How to make an intuitive form field for a M2M relationship with many options in Django?
Apologies if the title is poorly worded, I couldn't figure out a succinct way to describe this issue. I've been working with a client who uses the Django form library to allow users to create/edit model instances. I've recently added a many to many relationship between model A and model B, and I want there to be an input on the model A form that allows users to connect instances of model B to it. The SelectMultiple widget used by Django by default is unintuitive, and the alternative CheckboxSelectMultiple widget seems like it wouldn't be great once there are 100s of options (which is a likely scenario). What complicates this further is that there's also a M2M relationship between model C and D, connected by a through table that determines a D instance's order on a C instance, and neither of those widgets work well with through tables. My initial thought was to use CheckboxSelectMultiple and just order the already selected options at the top, wrapping the widget in a scroll overflow container. I unfortunately don't know how to order options in that way though, since the accepted queryset parameter is inherently unordered. For the case with the through table, … -
Django formset missing id for manually rendered template
I am using django formset to submit a dynamically generated form (based on a file uploaded by the user). The template renders this form manually (I prefer this because it's easier for me to work on style+HTML together in template). On submitting the form, I get an error that id is a required field. My form looks like this after rendering: <form method="post" id="add3"> {{ formset.management_form }} {% csrf_token %} <table id="forms"> <tbody> {% for lst in result %} <input type="hidden" name="form-{{ forloop.counter0 }}-id" value="{{ forloop.counter }}" id="id_form-{{ forloop.counter0 }}-id"> <tr> <td> <input type="hidden" name="form-{{ forloop.counter0 }}-expense" id="id_form-{{ forloop.counter0 }}-expense" value="{{lst.0}}"/> </td> <td> <input type="hidden" name="form-{{ forloop.counter0 }}-amount" id="id_form-{{ forloop.counter0 }}-amount" value="{{lst.1}}"/> </td> {% endfor %} </tbody> </table> </form> This is a short version. I have 6 fields in each row. I am able to get all 6 fields but it complains about the id. I have added the hidden id input type in each row but that doesn't work. How can I fix this? -
How to fix Modulenotfounderror when using external files with os.environ.setdefault in Django
I put my module in a folder and tried to use it in conjunction with Django. my_module folder is not django app this is my project example structure: mysite |-- my_module | |-- __init__.py | |-- mymodule1.py | |-- mymodule2.py | |-- mymodule3.py |-- mysite | |-- settings.py | |-- base.py | |-- dev.py | |-- production.py | |--wsgi.py |-- myapp |-- manage.py in my_module/mymodule1.py import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") django.setup() if if __name__ == '__main__': # my code... When I run this python file in Pycharm, it runs without any problem. but, when I run this terminal command, it occurs error which "ModuleNotFoundError: No module named 'mysite'" How can I fix this problem? and What is the diffrence between runining at Pycharm and terminal command? -
django 4.1 polls tutorial, all done Admin working fine but index not found
ok polls tutorial is done and can enter questions, vote, etc. but from the admin pages View site aka localhost:8000 gives... Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: dose/ admin/ The empty path didn’t match any of these. Now I have polls/views.py... from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.utils import timezone from django.views import generic from .models import Choice, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Question.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] and mysite/urls.py set to ... from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] and polls/urls.py set to... from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] The only hint I can find is that all the imports show error highlights in VSCode with the Error "reportMissingModuleSources" But python and django run perfectly well everywhere but index.html -
Converting object to an encodable object failed due to 404
Receiving 404 error while writing the data in json format. var response = await http.post(Uri.parse(url + "/api/register"), body: jsonEncode({ "username": _username.text, "first_name": _fname.text, "last_name": _lname.text, "password": _password.text, "email": _email.text, "usertype": _userDropdown.toString(), "gender": _genderDropdown.toString(),`enter code here` "bloodgroup": _bloodDropdown.toString(), "phone_no": _contact.toString() }), headers: {"Content-Type": "application/json"}); print("Status Code : " + response.statusCode.toString()); -
Django insert from data from another table using sql
I'm not so familiar in sql that execute in django. My database is PostgreSQL, now I want to insert selected data from One table to another in same database base on created date. But I got this error:IndexError: string index out of range Please help me to save my time. Thank you Here's my code: def insert(): now = datetime.today() - timedelta(days=1) now = str(now) created = datetime.strptime(date_now[:-7],'%Y-%m-%d %H:%M:%S') created= created.strftime('%Y-%m-%d') with connections['database_2'].cursor() as cursor: cursor.execute('''INSERT INTO Item .......some sql condition here..... AND date_created::date = %s ''', (''.join(created))) row = cursor.fetchone() return row The problem is here AND date_created::date = %s ''', (''.join(created))), I don't know the right way to call variable inside a sql. If I change like this AND date_created::date = %s ''', (created)throw another error TypeError: argument 1 must be a string or unicode object: got tuple instead. The date_created format from the table where I get the data is 2022-08-15 00:00:00.000 +0700. -
Django. Add foreign key to another model in view
Suppose, i have two models: Model Basket Model Apple One basket can have many apples in it, so there is one-to-many relationship between Basket and Apple. For example, here is my models: class Basket(models.Model): backet_name = models.CharField(max_length=150) owner = author = models.ForeignKey(get_user_model(), on_delete = models.CASCADE) class Apples(models.Model): apple_sort = models.CharField(max_length=150) apple_size = models.CharField(max_length=150) basket = models.ForeignKey(Basket, on_delete=models.CASCADE, related_name="apple_in_basket") I want to create a page to add basket and then to add apples to it at the same page, so i created a following forms, using formsets: class NewBasketForm(ModelForm): class Meta: model = Basket exclude = ['owner'] class AddAppleToBasket(ModelForm): class Meta: model = Apple exclude = ['basket'] AppleFormSet = modelformset_factory(Apple, form=AddAppleToBasket, extra=1, max_num=10) I want my apples to automaticly set foreign key to basket that i just created. So i created a view to insert Basket and Apple objects to the database: class BascketAddView(View): form_class_for_basket = NewBasketForm form_class_for_apples = AppleFormSet template_name = 'buskets/add.html' def get(self, request, *args, **kwargs): basket_form = self.form_class_for_apples() apples_form = self.form_class_for_answers() return render(request, self.template_name, {'basket_form': basket_form, 'apples_form': apples_form}) def post(self, request, *args, **kwargs): basket_form = self.form_class_for_basket(request.POST) apple_form = self.form_class_for_apples(request.POST) if basket_form.is_valid() and apple_form.is_valid(): print("form is valid!!!") new_basket = basket_form.save(commit=False) new_basket.owner = request.user new_basket.save() instances = apple_form.save(commit=False) for instance … -
NoReverseMatch error when trying to use Google OAuth 2.0
I am stuck on [Step 2: Redirect to Google's OAuth 2.0 server][1] of Google's Using OAuth 2.0 for Web Server Applications Guide. I have registered my application, got my client id and secret, and have the same authorized Redirect URIs in Google Developer Console than in my app. I am getting this error when I try to redirect the user to the google consent form. NoReverseMatch at /login/ Reverse for '?response_type=code&client_id=&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2F&scope=profile+openid+email&state=NZkfzNYMEqWIY1YG07eFxE6VL2YSip&access_type=offline&prompt=consent&include_granted_scopes=true' this is the function that is giving the error on the return: import google_auth_oauthlib.flow from django.shortcuts import redirect def authorize(): """ Set authorization parameters and redirect to Google's OAuth 2.0 server to prompt user for consent """ flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( client_config=client_secret.json, scopes=['profile', 'openid', 'email'] ) # Indicate where the API server will redirect the user after the user completes # the authorization flow. The redirect URI matches one of the authorized # redirect URIs for the OAuth 2.0 client in the API Console. flow.redirect_uri = 'http://localhost:8000/' authorization_url, state = flow.authorization_url( access_type='offline', prompt='consent', include_granted_scopes='true') return redirect(authorization_url) -
Why don't aggregations work correctly in Django migrations?
When I import the real model and run the query on it, I get the right answer. When I use the fake "historical" model from apps.get_model(), I get the wrong answer. Migration from django.db import migrations from django.db.models import Count from advisors.models import PlanShareRequest print(PlanShareRequest.objects.values("advisor_id", "plan_id").annotate(cnt=Count('id')).filter(cnt__gt=1)) def forward(apps, schema_editor): PlanShareRequest = apps.get_model("advisors", "plansharerequest") print(PlanShareRequest.objects.values("advisor_id", "plan_id").annotate(cnt=Count('id')).filter(cnt__gt=1)) class Migration(migrations.Migration): dependencies = [ ('plans', '0037_autoshare'), ("advisors", "0046_drop_advisor_logout"), ] operations = [ migrations.RunPython(forward, migrations.RunPython.noop), ] Output odigity@mypc:~/src/proj$ ./manage.sh migrate advisors 0047 <QuerySet [{'advisor_id': UUID('46bb6c3c-dfb6-40b2-9fd3-4cb5c413bf8a'), 'plan_id': UUID('9c789523-3319-4b2c-8192-27b43b2d5991'), 'cnt': 2}]> Operations to perform: Target specific migration: 0047_plansharerequest_unique, from advisors Running migrations: Applying advisors.0047_plansharerequest_unique...<QuerySet []> OK