Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does Django store charfield as a tuple?
Say I have a simple model in django class Customer(models.Model): session_id = models.CharField(max_length=200) nuts3 = models.CharField(max_length=200) To save a model object I will do this Customer.create(session_id = "unique_session_id", nuts3 = "some text") Now say that I need to overwrite the nuts3 in the saved model object with some other text customer = Customer.objects.filter(session_id = "unique_session_id") customer = customer[0] customer.nuts3 = "some new text" customer.save() When viewing the saved customer object in admin, I see a tuple in the nuts3 charfield ('some new text',). I have expected in the field only to have the string without a tuple. How come that Django added the string as a tuple? -
How to Convert This Sql Query TO Django Query
I want Get UID Based on Email Filtering Like "(select Uid From User_master where email = 'xyz.gmail.com')" How to Convert This Sql Query TO Django Query -
"version" key not founded in connect django and elastic-apm
i want to connect my django project with elastic apm but when i run my project, i see this line : No version key found in server response but my elastic server response have this key : { "name" : "something", "cluster_name" : "elasticsearch", "cluster_uuid" : "ikPV-LjKQ2mxKz3Nr0pNTQ", "version" : { "number" : "7.16.2", "build_flavor" : "default", "build_type" : "deb", "build_hash" : "2b937c44140b6559905130a8650c64dbd0879cfb", "build_date" : "2021-12-18T19:42:46.604893745Z", "build_snapshot" : false, "lucene_version" : "8.10.1", "minimum_wire_compatibility_version" : "6.8.0", "minimum_index_compatibility_version" : "6.0.0-beta1" }, "tagline" : "You Know, for Search" } and this is my django settitngs : ELASTIC_APM = { 'SERVICE_NAME': 'apm-inolinx', 'DEBUG': env('DEBUG'), 'SERVER_URL': 'http://127.0.0.1:9200', } -
Optimizing Database Population with Django
I have a 10GB csv file (34 million rows) with data(without column description/header) that needs to be populated in a Postgres database. The row data has columns that need to go in different Models. I have the following DB schema: Currently what I do is: Loop through rows: Create instance B with specific columns from row and append to an array_b Create instance C with specific columns from row and append to an array_c Create instance A with specific columns from row and relation to B and C, and append to an array_a Bulk create in order: B, C and A This works perfectly fine, however, it takes 4 hours to populate the DB. I wanted to optimize the population and came across the psql COPY FROM command. So I thought I would be able to do something like: Create instance A with specific columns from the file for foreign key to C create instance C with specific columns from the row for foreign key to B create instance B with specific columns from the row Go to 1. After a short research on how to do that, I found out that it does not allow table manipulations while copying … -
How to not change value if an input is empty
I have wrote this code for a form I was working on. <div class="col-md-6"><label class="labels">Doğum Günü:</label><input method="POST"name="birtdate" class="form-control" {% if student.birtdate%} type="text"value="{{student.birtdate}}" onfocus="(this.type='date')"onblur="(this.type='text')" {%else %}type="date" {% endif %}></div></div> It should show the initial value when blur and turn into a date field when focused. The problem is when I click on it and then click away it shows an empty value. I need to somehow check that and make it not change the value if the input is empty. How can I do that? -
Why am I not able to click my InlineRadios with CrispyForms?
For some reason I can't click the InlineRadio buttons that I'm creating with my crispy forms. When i click on them, nothing happens. I don't have any error messages in the console in the browser. Can someone help me figure out what is causing this? Forms.py class NewsEmailForm(forms.ModelForm): class Meta: model = NewsEmail fields = ('province', 'municipality', 'areas', 'interval', 'ad_type') help_texts = { 'areas': 'Håll in cmd (mac) eller ctrl (windows) för att markera flera', 'interval': 'Hur ofta du vill få ett mail med nya annonser i valt område.', } def __init__(self, *args, **kwargs): super(NewsEmailForm, self).__init__(*args, **kwargs) self.fields['province'].required = True self.fields['municipality'].required = True self.fields["interval"].choices = list(self.fields["interval"].choices)[1:] self.fields["ad_type"].choices = list(self.fields["ad_type"].choices)[1:] self.helper = FormHelper() self.helper.layout = Layout( Row( Column('province', css_class='form-group col-2 mb-0'), Column('municipality', css_class='form-group col-2 mb-0 ml-4'), Column('areas', css_class='form-group col-3 mb-0 ml-4'), Column( InlineRadios('interval'), css_class='form-group col-1 mb-0 ml-4' ), Column( InlineRadios('ad_type'), css_class='form-group col-1 mb-0 ml-4' ), Column( FormActions( Submit('submit', 'Spara bevakning', css_class='btn btn-sm btn-primary'), ), css_class='form-group col-1 mt-4 mb-0 ml-4' ), ), ) Models.py class NewsEmail(models.Model): INTERVAL_CHOICES = ( (1, "Veckovis"), (2, "Dagligen"), ) AD_TYPES_CHOICES = ( (1, "Hund erbjudes"), (2, "Hund sökes"), ) user = ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) province = ForeignKey(Province, on_delete=models.CASCADE, verbose_name='Landskap', null=True, blank=True) municipality = ForeignKey(Municipality, on_delete=models.CASCADE, verbose_name='Kommun', … -
How to make a query in Django that counts foreign key objects?
Hi all! New in Django, and confused, help is appreciated! I'm trying to create a table, like: Organization Total amount of appeals Amount of written form appeals Amount of oral form appeals Organization 1 3 1 2 Organization 2 2 1 1 Have three models: class Organization(models.Model): organization_name = models.CharField(max_length=50) class AppealForm(models.Model): form_name = models.CharField(max_length=50) class Appeal(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE) applicant_name = models.CharField(max_length=150) Objects of Organization model: organization_name Organization 1 Organization 2 Objects of AppealForm model: form_name In written form In oral form Objects of Appeal model: organization appeal_form applicant_name Organization 1 In written form First and Last name Organization 1 In oral form First and Last name Organization 1 In oral form First and Last name Organization 2 In written form First and Last name Organization 2 In oral form First and Last name How to make a complex query, to retrieve info from Appeal model? And place to exact fields of the table above?:( -
How to prevent direct URL access in Django?
I am new to Django and I am doing a simple web application and I need to force users to enter their usernames and passwords to access the next page. I do not want them to get direct access to any page without logging in. I used the @login_required decorator, however, when I write (http://127.0.0.1:8000/logindata/) in the browser it gives me an error "Page not found". Would you help me, please? views.py: from django.shortcuts import render from django.http import HttpResponse from django.db import connection from django.contrib.auth.decorators import login_required import pyodbc def index(request): if 'Login' in request.POST: rows = [] username = request.POST.get('username') if username.strip() != '': rows = getLogin(username) if len(rows) > 0: return render(request, 'login/welcome.html') else: return render (request, 'login/index.html') else: return render (request, 'login/index.html') else: return render (request, 'login/index.html') def getLogin(UserName=''): command = 'EXEC GetLogin\'' + UserName + '\'' cursor = connection.cursor() cursor.execute(command) rows = [] while True: row = cursor.fetchone() if not row: break userName = row[0] password = row[1] name = row[2] email = row[3] rows.append({'userName': userName, 'password': password, 'name': name, 'email': email}) cursor.close() return rows @login_required(login_url='/index/') def readLogin(request): rows = getLogin() return render(request, 'login/loginsdata.html', {'rows': rows}) The app urls.py: from django.urls import path from . … -
Django Strawberry Graphql Bad request 'str' object has no attribute 'execute_sync'
So I have a simple django model class County(models.Model): '''County''' name = models.CharField(max_length=100, null=False, blank=False) class Meta: verbose_name_plural = "Counties" ordering = ['name'] def __str__(self): return self.name here is my types.py import strawberry from strawberry.django import auto from . import models @strawberry.django.type(models.County) class County: id: auto name: auto and my schema.py import strawberry from .types import * @strawberry.type class Query: county: County = strawberry.django.field() counties: List[County] = strawberry.django.field() schema = strawberry.Schema(query=Query) For url.py" from main.schema import schema from strawberry.django.views import GraphQLView urlpatterns = [ path('admin/', admin.site.urls), path('graphql', GraphQLView.as_view(schema='schema'), name='graphql'), ] Running the terminal gives me: Unable to parse request body as JSON Bad Request: /graphql [08/Jan/2022 03:28:08] "GET /graphql HTTP/1.1" 400 113111 When I go into the graphql terminal at http://localhost:8000/graphql there is no documentation in the documentation explorer. If I type a query like: { counties{ id name } } I get this: Internal Server Error: /graphql Traceback (most recent call last): File "C:\Users\00\Envs\eagle\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\00\Envs\eagle\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\00\Envs\eagle\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\00\Envs\eagle\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\00\Envs\eagle\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, … -
Django 3.2 Migrations - "NoneType" object has no attribute "_meta"
$ docker-compose exec myapp python manage.py migrate I've got this error after modifying my model, how can I rollback or fix the issue ? Traceback (most recent call last): File "/src/manage.py", line 21, in <module> main() File "/src/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/opt/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/venv/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/venv/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/opt/venv/lib/python3.10/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/opt/venv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 268, in handle emit_post_migrate_signal( File "/opt/venv/lib/python3.10/site-packages/django/core/management/sql.py", line 42, in emit_post_migrate_signal models.signals.post_migrate.send( File "/opt/venv/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ File "/opt/venv/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/opt/venv/lib/python3.10/site-packages/adminactions/models.py", line 9, in create_extra_permissions_handler p.create_extra_permissions() File "/opt/venv/lib/python3.10/site-packages/adminactions/perms.py", line 34, in create_extra_permissions content_types = ContentType.objects.get_for_models(*models) File "/opt/venv/lib/python3.10/site-packages/django/contrib/contenttypes/models.py", line 89, in get_for_models opts_models = needed_opts.pop(ct.model_class()._meta, []) AttributeError: 'NoneType' object has no attribute '_meta' -
Django REST Framework: COUNT query generated by PageNumberPagination is slow
I don't want to run count queries on views where count is not needed. How can I turn it off? I found the following workaround in another post on stackoverflow. The count query is not fired, but I can see pages that have no data. (I can see up to ?page=10000, even though there are only about 10 pages.) #settings.py REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 20, ... } import sys from django.core.paginator import Paginator from django.utils.functional import cached_property from rest_framework.pagination import PageNumberPagination class CustomPaginatorClass(Paginator): @cached_property def count(self): return sys.maxsize class CustomPagination(PageNumberPagination): django_paginator_class = CustomPaginatorClass -
How to fix this error failed to import test module while testing?
Here I'm writing some TestCase for some queryset to view in api and getting error not a valid function or pattern name. I didn't get any idea what missing here! Is there any solution for this? views.py class StudentView(generics.ListAPIView): queryset = StudentDetails.objects.raw('SELECT * FROM collegedetails.college_studentdetails LIMIT 3;') serializer_class = StudentDetailsSerializers test_views.py from rest_framework.test import APITestCase from rest_framework.reverse import reverse from rest_framework import status STUDENT_URL = reverse('student/') class StudentsDetailsTest(APITestCase): def test_details(self): response = self.client.get(STUDENT_URL, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) college/urls.py urlpatterns=[ path('student/',views.StudentView.as_view(), name='student'), ] traceback error Found 1 test(s). System check identified no issues (0 silenced). E ====================================================================== ERROR: college.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: college.tests Traceback (most recent call last): File "C:\Users\\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "C:\Users\\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 377, in _get_module_from_name __import__(name) File "C:\Users\\collegedjango\MYSITE\college\tests.py", line 33, in <module> STUDENT_URL = reverse('student') File "C:\Users\\collegedjango\venv\lib\site- packages\rest_framework\reverse.py", line 47, in reverse url = _reverse(viewname, args, kwargs, request, format, **extra) File "C:\Users\\collegedjango\venv\lib\site- packages\rest_framework\reverse.py", line 60, in _reverse url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) File "C:\Users\\collegedjango\venv\lib\site- packages\django\urls\base.py", line 86, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\\collegedjango\venv\lib\site- packages\django\urls\resolvers.py", line 729, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'student' not found. 'student' is not a valid view function or pattern … -
How to pass arguments to model save method in django through serializer create method
I am saving a model like this if serializer.is_valid(): message = serializer.save(version_info='55') and I am passing a parameter called version_info and inside my serializer I have the following code class MessageSerializer(serilizer.Serializer): def create(self, validated_data, **kwargs): message = Message.objects.create(**validated_data) return message version_info parameter is inside validated_data dictionary but I want to pass this version_info to save method of my Message model which I have customize it to do some extra work while a message being saved but it gives this error: TypeError: Message() got an unexpected keyword argument 'version_info' how can I pass the version_info parameter to save method of my model? -
A Hello World in django isn't working when deplyed to heroku
I started learning django today and made a hello world thing, and want to deploy it to heroku, the build suceeded but when I enter the app it gives me the error "Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail" I checked the logs and this is what it said 2022-01-08T10:11:47.583930+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=justatest11lmao.herokuapp.com request_id=f1d12c52-396c-4550-b657-488b3c1734cf fwd="122.52.35.99" dyno= connect= service= status=503 bytes= protocol=https 2022-01-08T10:11:48.791011+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=justatest11lmao.herokuapp.com request_id=c6c80d4c-7b46-4614-a606-9c71eb922dac fwd="122.52.35.99" dyno= connect= service= status=503 bytes= protocol=https 2022-01-08T10:17:08.913462+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=justatest11lmao.herokuapp.com request_id=cbe21638-ec17-445e-a037-c2c9d0e09bcb fwd="122.52.35.99" dyno= connect= service= status=503 bytes= protocol=https 2022-01-08T10:17:09.961200+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=justatest11lmao.herokuapp.com request_id=fbe70f09-91f1-4815-9b5b-06475476e3de fwd="122.52.35.99" dyno= connect= service= status=503 bytes= protocol=https 2022-01-08T10:21:40.857058+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=justatest11lmao.herokuapp.com request_id=c631842b-7696-488e-a28c-4efa9782c1b9 fwd="122.52.35.99" dyno= connect= service= status=503 bytes= protocol=https 2022-01-08T10:21:41.924967+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=justatest11lmao.herokuapp.com request_id=3a70e80d-e807-41c3-9bd4-d5f809b3672e fwd="122.52.35.99" dyno= connect= service= status=503 bytes= protocol=https I'm new so I … -
How to write url for testing when using viewsets in Django Restframework
I am really noebie for testing. Actuall, I dont know how to write test url for getting response from viewsets. This is my views, class AppraisalAPI(viewsets.ReadOnlyModelViewSet): queryset = Appraisal.objects.all().order_by('-id') serializer_class = AppraisalSerializer def get_permissions(self): if self.action in ['retrieve']: self.permission_classes = [IsHRUser | IsManagementUser] elif self.action in ['list']: self.permission_classes = [IsUser] return super(self.__class__, self).get_permissions() def retrieve(self, request, *args, **kwargs): instance = self.get_object() data = instance.summary() return Response(data) This is my urls.py, router = routers.DefaultRouter() router.register('appraisal', AppraisalAPI) urlpatterns = [ path('', include(router.urls)), ] This is my test function, def test_appraisal_api_readonly(self): url = reverse('appraisal-list') self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key) resp1 = self.client.get(url, format='json') self.assertEqual(resp1.status_code, 200) This test url only went inside list action. when i give detail insteadof list it went only retrieve action. Here, I want to get Retrive function response, How can i get after getting permission i want to receive retrive function response. Anyhelp Appreciable,.. -
Heroku Django-AuthException at /complete/vk-oauth2/
''' Please help me, I'm new to programming. I need to enter in social net and I have an error(.Please help me how to change the version of the social network in contact in Heroku?AuthException at /complete/vk-oauth2/ Invalid request: versions below 5.81 are deprecated. Version param should be passed as "v". "version" param is invalid and not supported. For more information go to https://vk.com/dev/constant_version_updates ''' -
Can not get comment id with AJAX in django
I'm fighting with this problem during several days and can not find the solution for my case. I'm trying to make system of likes without refreshing the page. In synchronous mode system of likes and dislikes works fine, but when I'm trying to add AJAX, I'm getting 405 and only one last comment is working for one click, I understand problem that Ajax doesn't understand django urls with id or pk like my variant {% url 'store:like' comment.pk %} , but how it can be solved? There is this part from the template: {% for comment in comments %} <h6 class="card-header"> {{ comment.author }}<small> добавлен {{ comment.created_at|date:'M d, Y H:i' }} </small> </h6> <div class="card-body"> <h4>{{ comment }}</h4> <form id="like" method="POST" data-url="{% url 'store:like' comment.pk %}"> {% csrf_token %} <input type="hidden" value="{{comment.pk}}" name="id"> <input type="hidden" name="next" value="{{ request.path }}"> <button style="background-color: transparent; border: none; box-shadow: none;" type="submit"> <a class="btn btn-success" id="like"> Likes {{ comment.likes.all.count }}</a> </button> </form> </div> {% empty %} <p>Для данного товара ещё нет комментариев.</p> {% endfor %} my ajax call in the same template: <script type="text/javascript"> $(document).ready(function(){ var endpoint = $("#like").attr("data-url") $('#like').submit(function(e){ e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ type: 'POST', url: endpoint, data: serializedData, success: function(response) { … -
Django error trying to run server after installing cors-headers
So I'm trying to make a Django back-end for my project. It's my first time doing something like this, so when I got a CORS error (CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.) I Googled what to do. After doing the steps following the documentation, I've got the following error when trying to run 'python manage.py runserver'. C:\Users\Bence\Documents\Programozás-tanulás\web50\final project\benefactum>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\core\management\commands\runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\core\management\__init__.py", line 381, in execute autoreload.check_errors(django.setup)() File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\apps\config.py", line 300, in import_models self.models_module = import_module(models_module_name) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load … -
Specific Django models relationships
Good day! I'm coding an educational portal on Django and here are the models: class UserRanking(models.Model): user_id = models.ForeignKey(UserCourses, on_delete=models.CASCADE) i_xp = models.IntegerField(default=1) class UserCourses(models.Model): i_subscription_type = models.ForeignKey(SubscriptionType, on_delete=models.CASCADE) i_course_id = models.ForeignKey(CourseInfo, on_delete=models.CASCADE) i_user_id = models.ForeignKey(UserProfile, on_delete=models.CASCADE) dt_subscription_start = models.DateTimeField() dt_subscription_end = models.DateTimeField() class UserProfile(models.Model): i_user_id = models.ForeignKey(UserAuth, on_delete=models.CASCADE) ch_name = models.CharField(max_length=100) ch_surname = models.CharField(max_length=100) url_photo = models.URLField(max_length=250) # the path to the database dt_register_date = models.DateTimeField() dt_total_time_on_the_website = models.FloatField() I need to get such relationships database diagram Can you help me, please? -
How to gracefully restart django gunicorn?
I made a django application using docker. Currently I send hup signal to gunicorn master process to restart. If I simply send a hup signal, the workers are likely to restart without fully completing what they were doing. Does gunicorn support graceful restart just by sending a hup signal to the master process? If not, how can I gracefully restart the Gunicorn? -
How to encrypt data in django
As we know that we had an id in Django for each item in models by using which we can access that item. Now I want to encrypt that while sending to the frontend so that the user can't enter random id in URL to access any note. So how can I encrypt that here is what i want url should look thsi = notes.com/ldsfjalja3424wer0ew8r0 not like this = notes.com/45 class Note(models.Model): title = models.char id = model.primary def create_encryptkey(): And can be decoded in views if needed for any purpose for example to get exact id Thanks! -
passing variable value from django to another python script
I want to run an external python file the Django.view code is as follows: def generate(request): a=int(request.POST["status"]) b=int(request.POST["level"]) run(['python', 'water.py',a,b]) I have imported this water.py file from my app I want to pass these a and b values to my water.py file so that the water.py file can run in the background and can create a CSV file but I don't know how to pass these value my water.py code is as follows from time import time import sys from __main__ import* # trying to pass those values here x,current_level=sys.argv[1],sys.argv[2] but when I try to pass the value in this way I get error list index out of range is there any better way to tackle with this problem please suggest it would be very helpful -
Django ajax upvote downvote function
I'm very new to ajax, need help with implementing ajax to a django upvote-downvote utils function. I have tried doing it on my own but couldn't pull it off, any help will be much appreciated thanks. Here are the code snippets: in my model: models.py class Questions(models.Model): title = models.CharField(max_length=long_len) ques_content = models.TextField() tags = models.ManyToManyField(Tags) upvotes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='user_upvote') downvotes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='user_downvote') answers = models.ManyToManyField('main.Answer', related_name='answers') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False) views = models.IntegerField(default=0) is_answered = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) votes = models.IntegerField(default=0) has_accepted_answer = models.BooleanField(default=False) in my utils: utils.py def performUpDownVote(user,isQuestion,id,action_type): id = int(id) flag = False if isQuestion == 'True': print('------> isQ') q = Questions.objects.get(pk = id) if q.author == user: return False else: print('------> isNotQ') flag=True q = Answer.objects.get(pk = id) if q.answered_by == user: return False existsInUpvote = True if user in q.upvotes.all() else False existsDownUpvote = True if user in q.downvotes.all() else False if existsInUpvote: if action_type == 'downvote': q.upvotes.remove(user) q.downvotes.add(user) reputation(flag,-20, q) q.votes = q.votes - 1 elif existsDownUpvote: if action_type == 'upvote': q.downvotes.remove(user) q.upvotes.add(user) reputation(flag,20, q) q.votes = q.votes + 1 else: if action_type == 'downvote': q.downvotes.add(user) reputation(flag,-10, q) q.votes = q.votes - 1 if action_type == 'upvote': … -
Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name
I Have a project and I want to use Google authentication for signup on my website. This is my signup.html code: {% load socialaccount %} <form class="site-form" action="{% url 'authentication:signup' %}" method="post"> {{ form }} {% csrf_token %} <label> <a href="{% provider_login_url "google" %}">Login With Google</a> <input type="submit" value="submit"> </label> </form> and this is my urls.py file: path('signup/', views.signup_view, name='signup'), path('google-login/', include('allauth.urls')), but when I want to use from singup.html, this error raised: Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name. and when I want to use from google-login, 404 not found displayed: Using the URLconf defined in project.urls, Django tried these URL patterns, in this order: admin/ auth/ login/ [name='login'] auth/ logout/ [name='logout'] auth/ signup/ [name='signup'] auth/ google-login/ signup/ [name='account_signup'] auth/ google-login/ login/ [name='account_login'] auth/ google-login/ logout/ [name='account_logout'] auth/ google-login/ password/change/ [name='account_change_password'] auth/ google-login/ password/set/ [name='account_set_password'] auth/ google-login/ inactive/ [name='account_inactive'] auth/ google-login/ email/ [name='account_email'] auth/ google-login/ confirm-email/ [name='account_email_verification_sent'] auth/ google-login/ ^confirm-email/(?P<key>[-:\w]+)/$ [name='account_confirm_email'] auth/ google-login/ password/reset/ [name='account_reset_password'] auth/ google-login/ password/reset/done/ [name='account_reset_password_done'] auth/ google-login/ ^password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/$ [name='account_reset_password_from_key'] auth/ google-login/ password/reset/key/done/ [name='account_reset_password_from_key_done'] auth/ google-login/ social/ auth/ google-login/ google/ auth/ google-signup/ auth/ ^static/(?P<path>.*)$ The current path, auth/google-login/, didn’t match any of these. Thanks for your help. -
How to manage a redirect after a Ajax call + django
I'm managing my payments using braintree drop in and i'm using django. when the payment is success it should redirect to the payment success page and when it's unsuccess it should redirect to the payment failed page. I define the redirects in my views.py but i don't know how should i handle the redirect in ajax in this code after payment nothing happens and redirect is not working. what should i add to my ajax to handle the redirect? Braintree drop in Javascript code: <script> var braintree_client_token = "{{ client_token}}"; var button = document.querySelector('#submit-button'); braintree.dropin.create({ authorization: "{{client_token}}", container: '#braintree-dropin', card: { cardholderName: { required: false } } }, function (createErr, instance) { button.addEventListener('click', function () { instance.requestPaymentMethod(function (err, payload) { $.ajax({ type: 'POST', url: '{% url "payment:process" %}', data: { 'paymentMethodNonce': payload.nonce, 'csrfmiddlewaretoken': '{{ csrf_token }}' } }).done(function (result) { }); }); }); }); </script> Views.py @login_required def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) total_cost = order.get_total_cost() if request.method == 'POST': # retrive nonce nonce = request.POST.get('paymentMethodNonce', None) # create and submit transaction result = gateway.transaction.sale({ 'amount': f'{total_cost:.2f}', 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: # mark the order as paid order.paid = True # …