Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Outer for loop value in inner for loop in Django template
I'm doing Django Project. Here I am trying to use Outer for loop data in inner for loop in Django Template. Help me in that i did mistake in inner for loop i don't know how to solve this. views.py def test_view(request): if 'username' in request.session: if request.method == 'GET': offers_objs = offers.objects.all().values() data = Signup.objects.all().values() return render(request, 'index.html',{'offers_objs':offers_objs, 'data': data}) index.html {% for i in offers_objs %} <div class="divi" style="height: 410px"> <img src="{{ i.image.url }}" alt="Images" width="300px" height="auto"/> <p>Offer Des: {{ i.description }}</p> <p>Address: {{ i.address }}</p> <p>Offer id: {{ i.offer_id }}</p> </div> {% for {{ i.username }} in data %} <p>{{ name }}</p> {% endfor %} {% endfor %} -
Reverse relation of foreign keys in django
I have two tables connected via foreign keys. Models.py class Foo(models.Model): A = models.DateField(default=datetime.now) B = models.IntegerField(default=0) C = models.IntegerField(default=0) class Bar(models.Model): X = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name='foo_a') Y = models.CharField(default=0) Z = models.CharField(default=0) Views.py def foo_details(request): query = Foo.objects.all() return render(request, 'foodetails.html', {'query': inward}) HTML <thead> <tr> <th>A</th> <th>B</th> <th>C</th> <th>Y</th> <th>Z</th> </tr> </thead> <tbody> {% for i in query %} <tr> <td class="align-middle">{{ i.A }}</td> <td class="align-middle">{{ i.B }}</td> <td class="align-middle">{{ i.C }}</td> <td class="align-middle">{{ i.?? }}</td> <td class="align-middle">{{ i.?? }}</td> </tr> How can I show the related field of Bar model in my template? If the query in my views was Bar.objects.all() then in my templates I could easily do <td class="align-middle">{{ i.X.A }}</td> But how can I use the reverse relation? -
I am always getting none from request.POST.get in django
html -customer_view //nam and mob field are userinput fields which i am using for user input and later i am using them for filtering ----- {% block content %} {% csrf_token %} {{ customer.sponsor }} {% for i in sponsor %} {{ i.mobile|add:' - '|add:i.name }} {% endfor %} Please select a valid Existing Customer. Search Urls.py ---- path('customer_view',views.customer_view,name='customer_view') Views.py ---------- def customer_view(request): print(request.method ) name1 = str(request.POST.get('nam')) print(name1) mobile1 = str(request.POST.get('mob')) print(mobile1) customers_list = customer.objects.filter( mobile=mobile1) & customer.objects.filter(name=name1) sponsors = customer.objects.all().distinct('mobile') ctx = { 'customer': customers_list, 'sponsor': sponsors } return render(request, 'pages/customer_view.html', ctx) -
Is it rational to cache result of a filter query?
I want to arrange architecture for my new project. Beside caching result of intensive calculations, I have coded a new model that has caching mechanism as below and when I want to have caching on a model in new model I inherit this model. Is it a rational way to cache result of filter queries or not? Thanks in advance. class CacheQuerySet(models.QuerySet): def get(self, *args, **kwargs): if "pk" in kwargs and len(kwargs) == 1: key = "{cache_key}_PK_{pk}".format(cache_key=self.model.cache_key(), pk=kwargs["pk"]) cached_obj = cache.get(key) if cached_obj is None: db_obj = super(CacheQuerySet, self).get(*args, **kwargs) cache.set(key, db_obj, self.model.CACHE_TIMEOUT) return db_obj return cached_obj return super(CacheQuerySet, self).get(*args, **kwargs) def update(self, **kwargs): super(CacheQuerySet, self).update(**kwargs) keys = cache.keys("%s_*" % self.model.cache_key()) cache.delete_many(keys) def cached_data(self, *args, **kwargs): query_hash = md5(str(self.query).encode()).hexdigest() key = "%s_FILTER_%s" % (self.model.cache_key(), query_hash) cached_objects = cache.get(key) if cached_objects is None: db_objects = list(self.all()) cache.set(key, db_objects, self.model.CACHE_TIMEOUT) return db_objects return cached_objects class CachedModel(models.Model): CACHE_TIMEOUT = 10 * 60 @classmethod def cache_key(cls): return cls.__name__.upper() @property def my_key(self): return "{cache_key}_PK_{pk}".format(cache_key=self.cache_key(), pk=self.pk) objects = CacheQuerySet().as_manager() def save(self, *args, **kwargs): super(CachedModel, self).save(*args, **kwargs) filter_keys = cache.keys("%s_FILTER_*" % self.cache_key()) cache.delete_many(filter_keys) cache.set(self.my_key, self, self.CACHE_TIMEOUT) def delete(self): cache.delete(self.my_key) filter_keys = cache.keys("%s_FILTER_*" % self.cache_key()) cache.delete_many(filter_keys) super(CachedModel, self).delete() class Meta: abstract = True -
google login with Django rest api (android and ios)
I am writing backend for Google Login for both android and ios. For android we can use web application client id and client secret but for ios google only provides client id and no secret key. So I am not able to perform google login from ios. Since ios and android require two different client credentials, how can i include two client ids in one single project (one for android and one for ios)? This is the Back End code i have used: serializers.py `class SocialSerializer(serializers.Serializer): """ Serializer which accepts an OAuth2 access token and provider. """ provider = serializers.CharField(max_length=255, required=True) access_token = serializers.CharField(max_length=4096, required=True, trim_whitespace=True) views.py class SocialLoginView(generics.GenericAPIView): """ Log in using facebook or Google """ serializer_class = serializers.SocialSerializer permission_classes = [permissions.AllowAny] def get_tokens_for_user(self, user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } def post(self, request): """Authenticate user through the provider and access_token""" serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) provider = serializer.data.get('provider', None) strategy = load_strategy(request) try: backend = load_backend(strategy=strategy, name=provider, redirect_uri=None) except MissingBackend: return Response({'error': 'Please provide a valid provider'}, status=status.HTTP_400_BAD_REQUEST) try: if isinstance(backend, BaseOAuth2): access_token = serializer.data.get('access_token') user = backend.do_auth(access_token) except: return Response({ "error": "Invalid Credentials", }, status=status.HTTP_400_BAD_REQUEST) try: authenticated_user = backend.do_auth(access_token, user=user) except: return Response({ "error": … -
How request works in Flask if not parameterized in view
I have just started with Flask I know django. We take a request parameter in a simple django view from django.http import HttpResponse def view(request): #request is the local paramter for view return HttpResponse('Welcome to Django') Now this view is request aware because of parameter passed. But now in Flask from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['GET','POST']) def view(): if request.method == 'GET': return "Hello from Flask" request is not local to function view how it is aware of the request it should be like request is not defined. Where it is coming from? How it works here? -
Many small requests vs few large requests - Angular to Django REST API - No DB involved
I know there are related questions on SO, but I am not sure if the conditions I am asked to work on causes any changes to the answer, so I am asking it here. I am creating a simple webapp in Angular that imports spreadsheet data from the user and sends the data to Django backend that does data analysis on it. The data results are returned to frontend and Angular creates a dashboard of the results. There is a chart displayed for every column of the spreadsheet. I am faced with two options: a) Keeping the spreadsheet in the browser memory and sending each column of data separately to the Django server that makes analysis of the data and returns the results. Pros: Simple architecture. No caching required. Cons: If there are 150 columns in the sheet, it will result in 150 calls to the API for that user. b) Sending the entire sheet of data and let python handle everything. It will return a big chunk of data in return which will have to be unpacked by Angular. Pros: Only one request per file. Cons: For subsequent calls for the same file, I might need caching? If the … -
OSError: [WinError 123] (file name error) but project previously worked
I have written an authentification application with Django and it used to work now, when I try to use it in another project, I have an error: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect '' error seems to deal with a pathlib.py file I did not change: File "C:\Users\jl3.PRT-063\AppData\Local\Programs\Python\Python37-32\lib\pathlib.py", line 1168, in stat return self._accessor.stat(self) I try to go back with my original code that was working by cloning my project on gitlab but I have the same error what happen? -
Converting curl command to request.post
I have following curl command: curl.exe -u sys_dcmsys:sys_******1 -d "grant_type=client_credentials&scope=Token_WindowsAuth" -H "Content-type: application/x-www-form-urlencoded" https://abcd-i.company.com/token -k -i And i am trying to do the same over python using requests: payload = { 'grant_type': 'client_credentials', 'scope': 'Token_WindowsAuth' } header = {'Content-Type': 'application/x-www-form-urlencoded'} result = requests.post( https://abcd-i.company.com/token, auth=HTTPBasicAuth('sys_dcmsys', 'sys_******1'), data=payload, headers=header, verify=False) i am able to get the result from command line. but when i tried with request.post its failing. it says : File "/home/vcap/deps/1/python/lib/python3.5/json/decoder.py", line 357, in raw_decode [APP/PROC/WEB/0] ERR raise JSONDecodeError("Expecting value", s, err.value) from None 2019-10-23T11:48:28.60+0530 [APP/PROC/WEB/0] ERR json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) can any one suggest me why my python post request is failing -
Django user rights management through the admin panel
I have a user to whom I have added permissions. How to do this through the admin panel so that with one click I can assign the permissions I need (one at a time or all at once)? class TestUser(AbstractUser): phone = PhoneNumberField(null=False, blank=False, unique=True) class Meta: db_table = '"fyzzys"."users"' permissions = ( ("payments", "can_see_payments"), ("analytics", "can_see_analytics"), ) -
In Tabbing page how to come back to same tab if i have gone in children of each tab
In my Django page, I have two tabs.Tab1 and Tab2 right. And Each Tab has a number of children. If I navigate to Tab1's children, the Same as if I navigate to Tab2's children. If I came back to the parent(Tab1 or Tab2) it will always go to Tab1. If I navigate through Tab1 than it will come back to Tab1 and if I navigate through Tab2 than it will come back to Tab2. How to do this in Django? -
Django (or something else) for utilising stored procedures
I need a web framework that can handle SQL Server store procedures as a main way of recieving and sending data. This data wold also need to be editable and sent be able to be sent back with stored procedures. (This is unavoidable). I was thinking of using Django as it can be run on Linux and I enjoy developing with that platform, but resources on how to utilise stored procedures in Django are scarce. I'd love some suggestions! -
Error encountered checking Geometry returned from GEOS C function "GEOSGeom_createLinearRing_r"
Trying to generate a polygon field for my region and cities for geotagging. Idea is to save the coordinates separately from Gmaps. Then use them to generate a region polygon. For regions like NCR in India, you have multiple cities like Delhi, Noida. Gurgaon etc. So these cities form the subset of the polygon. So you create a polygon and save with every city, then make a multipolygon to save at a regional level. Encountered this error. Please help from Geography.models import Region,City from django.contrib.gis.geos import Polygon,MultiPolygon coordinates={ 'JAL':{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "Name": "jalandhar", "Description": "" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 75.510571, 31.384717, 0.0 ], [ 75.515237, 31.270770, 0.0 ], [ 75.683574,31.264225, 0.0 ], [ 75.672656,31.390200, 0.0 ] ] ] } } ] } } def add_polygons(): r = Region.objects.last() city_coordinates = coordinates[r.name]['features'] polygon=None for cx in city_coordinates: coo_list_ = cx['geometry']['coordinates'][0] coo_list =[[item[0],item[1]] for item in coo_list_] name = cx['properties']['Name'] city=City.objects.filter(name__iexact=name).first() p = Polygon(coo_list) if city: city.poly=p city.save() if polygon: polygon=polygon.union(p) else: polygon=MultiPolygon(p) r.poly=Polygon(polygon.shell) r.save() add_polygons() This is the error I get. Something about create linear ring function. I tried to go through the library itself but to no avail. … -
mutiValueDictKeyError in django
I am a novice in django app development. I was trying to develop a simple app where it adds two numbers. I am getting MulitValuedDictKeyError. I referred to few questions of same type previously asked and tried some solutions, but none worked.Kindly help me fix it. views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request,'home.html',{'name':'pavan sunder'}) def add(request): val1 = request.GET["num1"] val2 = request.GET["num2"] res = val1 + val2 return render(request, 'result.html',{'result':res}) home.html <!DOCTYPE html> <html lang="en"> <body> {% extends 'base.html' %} {% block content %} <h1>hello {{name}}</h1> <form action="add"> Enter 1st number:<input type="text",name="num1"><br> Enter 2nd number:<input type="text",name="num2"><br> <input type="Submit"> </form> {% endblock %} </body> </html> result.html <!DOCTYPE html> <html lang="en"> <body> {% extends 'base.html' %} {% block content %} Result:{{result}} {% endblock %} </body> </html> error msg: MultiValueDictKeyError at /add 'num1' Request Method: GET Request URL: http://127.0.0.1:8000/add Django Version: 2.2.6 Exception Type: MultiValueDictKeyError Exception Value: 'num1' Exception Location: C:\Users\PAVANM~1\django\lib\site-packages\django\utils\datastructures.py in __getitem__, line 80 Python Executable: C:\Users\PAVANM~1\django\Scripts\python.exe Python Version: 3.7.1 Python Path: ['C:\\Users\\pavan m sunder\\projects\\django\\tst', 'C:\\Users\\PAVANM~1\\django\\Scripts\\python37.zip', 'C:\\Users\\PAVANM~1\\django\\DLLs', 'C:\\Users\\PAVANM~1\\django\\lib', 'C:\\Users\\PAVANM~1\\django\\Scripts', 'c:\\users\\pavan m ' 'sunder\\appdata\\local\\programs\\python\\python37-32\\Lib', 'c:\\users\\pavan m ' 'sunder\\appdata\\local\\programs\\python\\python37-32\\DLLs', 'C:\\Users\\PAVANM~1\\django', 'C:\\Users\\PAVANM~1\\django\\lib\\site-packages'] Server time: Wed, 23 Oct 2019 05:32:02 +0000 -
What is the best django practice to collect and store users' interest data?
I need to implement the simpliest users interest module in Django. I have a very small web application with the ony search bar and a button. The search bar is intended for an account number input. After pressing the button users get information about the entered account number I need to collect and store data of users' interest by days. How many times data was searched everday. eg. | day |number of queries| |22 Oct | 7 | |23 Oct | 5 | ... Django 2.2.1 I created the model: models.py class LeadsNumber(models.Model): date_of_interest = models.DateField(blank=False) number_of_queries = models.IntegerField(blank=False, default=0) class Meta: ordering = ["date"] When the user input the data and press the button the function from view.py look for the existing model and then update or create a new instance of the LeadsNumber model for the day when the account number was searched. I guess there is a better way for implementing such thing. Share your thoughts please -
Dynamic Multi level approval system with django view flow
We have a request that needs to be processed by multiple users before it gets approved. The request can be approved by any user in a group or having certain permissions or the request be assigned to a certain user. What would be the best way to approach the problem using django-viewflow. Any suggestions would be appreciated. -
Have url with pk or id to redirect to update page in Django error message
I've creating a app, and on the CreateView page, the Submit button works fine to create new S Reference. I also created error message if the input value matches a existing Reference. I created button in the error message part and tried to link it to update page to update this reference fields, like primary contact. I tried many options but have not got right code for the argument with pk or id to get individual record update page. this is the url in error message. I tried quite few pk, id options, none of them works. 'pk'=self.pk; {'pk'=self.pk}; object.id some code as below models.py class LNOrder(models.Model): reference_number = models.CharField(max_length=15,blank=True, null=True, unique=True, error_messages={'unique':"This reference already exists."}) primary_contact = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) urls.py urlpatterns = [ path('lfcnotifier', LNCreateView.as_view(), name='lnorder_create'), path('lfcnotifier/<int:pk>', LNDetailView.as_view(), name='lnorder_detail'), path('lfcnotifier/<int:pk>/update/', LNUpdateView.as_view(), name='lnorder_update'), ] template <div class="input-group mb-3"> <div class="input-group-prepend w-225px"> <label class="input-group-text w-100">S Reference</label> </div> <input name="reference_number" type="text" class="form-control" placeholder="Enter your S Reference"/> <button class="btn btn-primary cardshadow " data-toggle="tooltip" title="Click to submit" style="width:200px;" type="submit">submit</button> {%for field in form %} {% for error in field.errors %} {{ error }} <a href="{% url 'lnorder_update' 'pk'=self.pk %}" class="shadow-sm col-sm-4 btn-block btn btn-primary mt-0">Update Request</a> {% endfor %} {% endfor %} … -
I want to access struct block default ID in its template
I want to save stream field ID into it's template. In short, in text_question.html I am giving id = {{ self.id }} but that return Nothing. I want this because in question.html file I want it to compare with {{ field.id }} which return stream field ID In another word, I want to store {{ field.id }}'s value in id field of text_question.html models.py class TextQuestionBlock(blocks.StructBlock): """Text Question""" question = blocks.CharBlock(required=True, help_text="Add your Question") is_save = blocks.BooleanBlock(label="Want to save this field ?", required=False) is_email = blocks.BooleanBlock(label="Want to get this field as an email ?", required=False) class Meta: # noqa template = "question/question_field/text_question.html" icon = "edit" label = "Text Question" @register_setting(icon='fa-commenting') class QuestionSettings(BaseSetting): body = StreamField([ ("text_question", TextQuestionBlock()), ], verbose_name='Question', blank=True) panels = [ StreamFieldPanel('body') ] class Meta: verbose_name_plural = 'Question' verbose_name = 'Questions' text_question.html {% load tag_library %} <input issave="{{self.is_save}}" isemail="{{ self.is_email }}" class="text_question" type="text" name="{{ self.question|to_name }}" id="{{ self.id }}" data-conv-question="{{ self.question }}" question.html <form name="question_form" action="" method="post" class="hidden"> <div id="unique_id"></div> {% for field in question.body %} {{ field.id }} {% endfor %} <input type="text" data-conv-question="test"> </form> Thank You!!! -
Trying to Write a Django Query That Counts Events Per Day For Events That Span Multiple Days
I am using Django and trying to count the number of events that are running on each day based on events running across multiple days. For example, if Event 1 starts on Monday and ends on Wednesday and Event 2 starts on Tuesday and ends on Thursday, the event count per day should be: Monday (1 event), Tuesday (2 events), Wednesday (2 events), Thursday (1 event). The event model looks like this: class Event(models.Model): name = models.CharField(max_length=300, blank=True) start_date = models.DateTimeField(blank=True) end_date = models.DateTimeField(blank=True) def __str__(self): return self.name I would like to get query results to include the date of the day we are counting for, the number of events running on that day, and the name of each event running on that day. Any help on this Django query would be helpful. Thanks in advance! -
Custom Button in django
enter code here I am trying to create custom Button in Django Admin class HeroAdmin(admin.ModelAdmin): change_list_template="hellogym/hellogymapp/templates/change_list.html" {% extends 'admin/change_list.html' %} {% block object-tools %} <div> <form action="immortal/" method="POST"> {% csrf_token %} <button type="submit">Make Immortal</button> </form> <form action="mortal/" method="POST"> {% csrf_token %} <button type="submit">Make Mortal</button> </form> </div> <br /> {{ block.super }} {% endblock %} I have created superuser Admin and I want a custom button inside it -
How to declare variable in django html file. not pass from any view. and i also update that variable
I check all blogs in stackorverflow but i doesn't find any solution. Django Template - Increment the value of a variable This link solution doesn't work. please tell me Other solution. -
ModuleNotFoundError: No module named 'project.appname' when running Django tests
When trying to run my tests using either ./manage.py test or pytest, all of the apps in my Django project fail their tests with ModuleNotFoundError: No module named 'project.appname'. However, when running with ./manage.py test app.tests (if the tests are in a dedicated tests directory), they do progress beyond a Module Not Found error. I think there is something wrong with my configuration that leads to this error but I have no idea where to poke to try fixing this: I'm not seeing anything that makes PyCharm yell at me when I look at any testing module nor when looking at Settings.py -
Stripe Payment Intent API Prevent Form From Submitting Until User Authenticates Card
Using the new Stripe Payment Intent API and Stripe.js, I want to be able to do the following: 1) If the user's card is valid but requires authentication (SCA), do not submit the form until the user clicks "complete authentication" on the 3D secure popup. 2) If the user's card is valid but does not require authentication (SCA), submit the form. Here is a video of my issue: https://streamable.com/797e5 As you can see from the video, the form submits itself with a card that requires authentication but the user does not have time to click "complete authentication" since the form refreshes the page immediately. Stripe support says JavaScript is needed to do this and provided me a PHP example. https://glitch.com/edit/#!/stripe-php-sca-example?path=public/charge.php:9:0 However, I am using Django and not PHP. I am also not sure how to code this in JavaScript. Any help would be greatly appreciated. Html: <form onsubmit="return false;" action="{{checkout}}" method="post" id="payment-form">{% csrf_token %} <div class="form-row"> <label for="card-element"> Credit or debit card </label> <div id="card-element"> <!-- A Stripe Element will be inserted here. --> </div> <!-- Used to display form errors. --> <div id="card-errors" role="alert"></div> </div> <button id="card-button" data-secret="{{ client_secret }}"> Submit Payment </button> </form> <script src="https://js.stripe.com/v3/"></script> Stripe.js: var stripe … -
How to manually authenticate user in Django
hi I want to authenticate user manually how can I keep user signed in, in all applications of project? here's my login view function: def sign(request): context = {} if request.method == 'POST': form = SigninForm(data = request.POST) if form.is_valid: username = request.POST['username'] password = hashlib.sha256(request.POST['password'].encode('utf-8')).hexdigest() users = customer.objects.all() for user in users: if username == user.username: if password == user.password: context['tmp'] = "OK" -
Django use data in a class based view
I have a class-based view in Django. I have implemented a method get_context_data. A user can log in or update his/her data and is redirected to a class-based view template. I want the information of the logged-in user inside the class-based view. I'm not rendering the view, just re-directing. Is there any approach like saving the data in memory during computation or global variables so that it can be accessed anywhere in the views.py.