Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get files from related field - models.manytomanyfield at signals function
my models: class B: file= models.FileField(upload_to='files/', blank=True) class A: files = models.ManyToManyField('folder.B') and now I'm trying to get all the files. when the files from the 'A' model, when the files at 'A' model was a single file field I could get the file from the signal like this instance.files, now instead of file list i get folder.B.None -
Send a file to an external api from "InMemoryUploadedFile" in Django
In the Django Framework I would like to post a file, received as an InMemoryUploadedFile, to a different server as soon as it is received. I Have tried the solution in Django - post InMemoryUploadedFile to external REST api but the solution did not work for me. Curl request given by External API: curl --location --request POST 'https://app-sh.exmp.com/api/cret' \ --header 'Content-Type: multipart/form-data' \ --header 'api-key: Aa4f*******' \ --form 'kyc_doc=@/C:/Users/Shine/Downloads/image.png' \ --form 'company_name=name' \ --form 'company_country=IN' \ --form 'email=abc@xyz.com' How do I convert following into request.post() ? From my current functional flow, the file is not sent to external api. Here is my code: views.py def processUpload(request): data['company_country'] = request.POST.get('company_country') data['company_name'] = request.POST.get('company_name') #upload file data['kyc_doc'] = request.FILES['kyc_doc'].file.getvalue() files = {"kyc_doc":request.FILES['kyc_doc'].file.getvalue()} return service.doCurl(data,files) service.py def doCurl(data,files): #..... # business logic here # del data['common_user_token'] response_kcloud = curl.post('https://app-sh.exmp.com/api/cret',data,{ "api-key":acc.api_key},files) curl.py def post(url,data,headers,ufile=None): curlheaders = {"Content-Type": "application/json"} #empty data if not data: raise Exception("data cannot be empty") #empty url if not url: raise Exception("Url cannot be empty") #base case for header if headers: for key in headers: curlheaders[key] = headers[key] if ufile is None: return requests.post(url, data=json.dumps(data), headers=curlheaders) else: return requests.post(url, data=data, headers=curlheaders,files=ufile) -
i want my create view and list view on the same page
I want my create view and list view on the same page and in my list view i only want login users post to show . With this code my create view works but in place of list view it does not show anything and it also does not show any error. How can i fix this. Thank you this is my views.py:- from django.shortcuts import render from django.views.generic import ListView, CreateView from .models import simpleList from django.urls import reverse_lazy # Create your views here. class CreateList(CreateView): model = simpleList template_name = 'create_list.html' fields = ('title', ) success_url = reverse_lazy('create_list') def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def ListListView(request): current_user = request.user user_list = simpleList.objects.filter(author=current_user) return user_list this is my html:- {% extends 'base.html' %} {% block title %}Create{% endblock title %} {% block content %} <form method="POST">{% csrf_token %} {{ form.as_p }} <button class="btn btn-info" type="submit">Add</button> </form> <h2>simpleList</h2> <table class="table table-hover"> <thead> <tr> <th scope="col">S.No</th> <th scope="col">Task</th> <th scope="col">Done</th> </tr> </thead> </table> <div> {% for simpleList in user_list %} <table class="table table-hover"> <thead style="display: none;"> <tr> <th scope="col">S.No</th> <th scope="col">Task</th> <th scope="col">Done</th> </tr> </thead> <div> <tbody> <tr class="table-primary"> <th scope="row">{{ simpleList.pk }}</th> <td style="max-width: 100px; word-break: break-all;"> {{ … -
Django ModuleNotFoundError: No module named 'debug_toolbar' Python 3.6.1
Im trying to make django-admin.py runserver or just django-admin.py ( Its like manage.py) I got the following traceback : 2020-08-04 13:07:20.956398 INFO Watching for file changes with StatReloader django.utils.autoreload Exception in thread django-main-thread: Traceback (most recent call last): File "C:\users\test\.virtualenvs\test-gg4vino_\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\users\test\.virtualenvs\test-gg4vino_\lib\importlib\__init__.py", line 126, in import_module **return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'debug_toolbar'** Traceback (most recent call last): File "C:/Users/test/.virtualenvs/test-GG4viNo_/Scripts/django-admin.py", line 5, in <module> management.execute_from_command_line() File "C:\Users\test\AppData\Local\Programs\Python\Python36\Lib\pathlib.py", line 390, in wrapped return strfunc(str(pathobj), *args) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' So apparently no module nammed ModuleNotFoundError: No module named 'debug_toolbar' , Indeed, In my Settings.py : INSTALLED_APPS.append('debug_toolbar') and OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' I tired to install it : pip install django-debug-toolbar But still I have the same issue. I'm on Python 3.6.1 Thanks for your help ! -
Django NoReverseMatch at / with arguments '('',)'
I have: path('new/', views.new, name='new_without_arg'), path('new/<str:arg>', views.new_with_arg, name='new_with_arg') in my urls.py and when I have 'new_with_arg' in a template: <a href="{% url 'new_with_arg' subject %}">New Subject</a> I get: Reverse for 'new_with_arg' with arguments '('',)' not found. 1 pattern(s) tried: ['new/(?P[^/]+)$'] My views.py is: def new(request): return render(request, 'notes/new.html') def new_with_arg(request, arg): if(arg == 'task'): return render(request, 'notes/new_task.html') elif(arg == 'room'): return render(request, 'notes/new_room.html') elif(arg == 'subject'): return render(request, 'notes/new_subject.html') else: return HttpResponseRedirect(reverse('new_without_arg')) -
Django request.session not passing modified session data to template/other views
Hey I new to the Django framework and I have gone across this problem in my shop project. Here is the thing I have been using the request.session to store cart data and I wanted to clear users reservation sometime after the client selects an item. # Interacts with the database def configure_db(chosen, item_id, quantity=1): item = Item.objects.filter(id=item_id) if chosen: item.update(reservation=F('reservation') + quantity) if not chosen: item.update(reservation=F('reservation') - quantity) # Main cart handler def cart_manager(request): data = json.loads(request.body) itemId = int(data['itemId']) action = data['action'] stock = int(data['stock']) def clear_reservation(item_id): for item in request.session['cart_items']: if item_id == item['id']: item['quantity'] -= 1 print("reservation cleared") if request.session.has_key('cart_items'): cart_items = request.session['cart_items'] for item in cart_items: if itemId == item['id']: if action == 'add' or action == 'increase': reservation = Item.objects.get(id=itemId).reservation if int(reservation) < stock: item['quantity'] += 1 request.session['cart_quantity'] += 1 configure_db(True, itemId) Timer(5.0, clear_reservation, [itemId]).start() return JsonResponse("foo", safe=False) Here is my Javascript function editCart(itemId, action, stock) { let csrftoken = getCookie("csrftoken"); let itemData = JSON.stringify({ itemId: itemId, action: action, stock: stock, }); fetch("http://127.0.0.1:8000/shop/editcart", { method: "POST", body: itemData, headers: new Headers({ "content-type": "application/json", "X-CSRFToken": csrftoken, }), }) .then((res) => { return res.json(); }) .then((data) => { location.reload(); }); } I refreshed each time to … -
Django, configure production and local DB settings
I have a Django project deployed to Heroku, where I'm trying to configure the settings file to change DB between production and development. I don't really see the point of creating three settings file (including a base file) since the only thing I'm changing is the database settings but I don't want to use python manage.py runserver --settings=rivendell.settings.local every time I run manage.py. if I run without the settings flag the server runs But I get an error: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I know why this is happening but I can set Django to choose the right file. My tree: |-- rivendell | |-- __init__.py | |-- asgi.py | |-- settings | | |-- __init__.py | | |-- consts | | |-- local.py | | |-- settings.py | |-- urls.py | `-- wsgi.py my settings file: import os import dj_database_url import dotenv import environ from .consts.apps import INSTALLED_APPS, MIDDLEWARE from .consts.consts import (PASSWORD_VALIDATORS, POSTGRESQL_CONNECTION, STATIC, TEMPLATES, Config, Language) from .consts.logging import LOGGING from .consts.rest_framework import REST_FRAMEWORK env = environ.Env(DEBUG=(bool, False)) environ.Env.read_env() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) env_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(env_file): file = dotenv.load_dotenv(env_file) SECRET_KEY = '+@sxt&+q5=9-u&it^5n-n!!a-2*fcbur^-umoxw*#!_ik$@kbc' DEBUG = env('DEBUG') … -
Django Admin Styling corrupted
I recently made some changes to my django site, one big one being upgrading from Django 2.2 to 3.1. Now my admin site styling is all messed up. I can't figure out what went wrong. Any pointers would be appreciated! See image of what it looks like after update.... -
How to Convert a Date to Django Timezone Aware Datetime
I am trying to convert a DateTime with the UTC time zone to Django datetime that respects the time zone of my date. Here is my settings.py: TIME_ZONE = 'US/Pacific' USE_TZ = True Here is the date I am trying to convert to the right time zone for django: datetime.datetime(2020, 2, 20, 8, 55, 48, 846000) I used the make_aware function provided by Django but I can see the date isn't converted to the time zone in my settings.py when I save the Django Modal with a DateTime field from django.utils.timezone import make_aware -
join 3 tables queryset Python Django
I need join 3 tables in a query on Django. I have two query's in MySQL, both return the same result, it doesn't matter to use one or the other query: Query whit where SELECT dv.Division, COUNT(or.`ct_id`) AS `orders`, COUNT(CASE WHEN gr.`Status` = 'on going' THEN 1 ELSE NULL END) AS `ge_on_going`, FROM order or, zone zo, cctt ct, division dv WHERE or.zone_id = zo.id AND or.cctt_id = ct.id AND zo.division_id = dv.id GROUP BY dv.Division Query whit join SELECT dv.Division, COUNT(or.`ct_id`) AS `orders`, COUNT(CASE WHEN gr.`Status` = 'on going' THEN 1 ELSE NULL END) AS `ge_on_going`, FROM order or INNER JOIN cctt ct ON (or.cctt_id = ct.id) INNER JOIN zone zo ON (or.zone_id = zo.id) INNER JOIN division dv ON (zo.division_id = dv.id) GROUP BY dv.Division How can that query be translated to django, I have this, but it doesn't work: MODELS class DivisionModel(models.Model): id = models.PositiveIntegerField(db_column='Id', primary_key=True) division = models.CharField(db_column='Division', max_length=50) class ZoneModel(models.Model): id = models.AutoField(db_column='Id', primary_key=True) zone = models.CharField(db_column='Zone', max_length=50) division = models.ForeignKey(DivisionModel, on_delete=models.DO_NOTHING, db_column='Division_id') class PedidoModel(models.Model): zone = models.ForeignKey(ZonaModel, on_delete=models.DO_NOTHING, db_column='Zone_Id') cctt = models.ForeignKey(CCTTModel, on_delete=models.DO_NOTHING, db_column='CCTT_Id') -
Duplicate data occurs when order_by ('?') and pagination is applied
@action(detail=False, methods=["get"]) def home_list(self, request): data = extra_models.objects.order_by("?") print(data) paginator = self.paginator results = paginator.paginate_queryset(data, request) serializer = self.get_serializer(results, many=True) return self.get_paginated_response(serializer.data) What I want to do is, I want the data of extra_models (objects) to come out randomly without duplication every time the home_list API is called. However, I want to come out randomly but cut it out in 10 units. (settings.py pagination option applied) The current problem is that the first 10 appear randomly, but when the next 10 appear, the first ones are also mixed. In other words, data is being duplicated. Duplicates do not occur within the same page. If you move to the next page, data from the previous page is mixed. Even if you try print(data) or print(serializer.data) in the middle, duplicate data is not delivered. However, data duplication occurs from /home_list?page=2 when calling the actual API. Which part should I check? -
How to connect to existing oracle db table in Django
Actually, i am developing UI for my team for daily Data visualization using Django, but from last two week i have searched a lot in google, i didn't get solution, even i have followed Django Documentation for connecting Oracle DB. Already i have date in my Metrics table, i don't want create a table again. can anyone help me to connect existing Oracle DB OtherUser table in Django and how to write in model.py. i have installed cx_Oracle library also. i have tried inspectin DB its show as below. from django.db import models Unable to inspect table 'METRICS' The error was: ORA-00942: table or view does not exist # setting.py 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'servicename', 'USER': 'mysuer', 'PASSWORD': 'mypassword', 'SCHEMAS': 'SCHEMANAME', } # models.py class Metrics(models.Model): class Meta: db_table = '"SCHEMANAME"."METRICS"' verbose_name = 'Metrics' verbose_name_plural = 'Metrics' i have test in single test.py file i am able to get the data using cursor in cx_oracle, but how i can do it in django? -
ModuleNotFoundError: No module named 'django_filters'
I deleted the pycache, migrations and DB of my code to start migrations again. But I realized that there might be another way to do it, so I discarded all the changes in VS code. I tried pulling the code from master, just in case. But it showed me that my branch was already up to date with master. So I ran makemigrations, but as I tried doing that, it showed me this error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\gauta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\gauta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\gauta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\gauta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\gauta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\gauta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\gauta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\gauta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2288.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in … -
Django: IntegrityError null value violates not-null constraint
In my django app, there is something 'weird' that's happening & i'm not understanding. I have two different tables (employeeProfile & purchaserShippingDetail) each has a field with the relation OneToOneField but with the 1st table (employeeProfile) in the field user that uses OneToOneField i can pass a string representation say Michael using api & i don't get an error but in my 2nd table that has similar structure when i add a string representation to i get IntegrityError at /api/clients/shipping/ null value in column "owner_id" violates not-null constraint 1st Table model (works fine) class employeeProfile(models.Model): image = models.ImageField(default='default.png',upload_to='employee_photos/%Y/%m/%d/') user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name="employee_profile") phone_no = models.CharField(max_length=10, unique=True) def __str__(self): return self.user.name 2nd Table Model (The one that throws the "owner_id" violates not-null constraint error) class purchaserShippingDetail(models.Model): frequent_customer = models.BooleanField(default=False) owner = models.OneToOneField(Purchaser, on_delete=models.CASCADE, related_name="purchaser_shipping") address = models.CharField(max_length=12, blank=True) zip_code = models.CharField(max_length=12, blank=True) location = models.CharField(max_length=255) def __str__(self): return self.owner.name serializer for purchaserShippingDetail model class purchaserShippingDetailSerializer(serializers.ModelSerializer): owner = serializers.StringRelatedField(read_only=True) class Meta: model = purchaserShippingDetail fields = '__all__' -
why django form action url product/addcomment is redirect to product/addcomment twice?
my English knowledge is so bad but i can understand. when i click submit button get this error. i use python 3. and chrome browser. and also please help me .. 4 days i tried this problem. i think http://127.0.0.1:8000/product/17/product/addcomment/17 this line twoise add /product/17/ part. why it add please help me?? submit button error product/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('addcomment/', views.addcomment, name='addcomment') ] product/views.py def addcomment(request): url = request.META.get('HTTP_REFERER') if request.method == 'POST': # check post form = CommentForm(request.POST) if form.is_valid(): data = Comment() # create relation withmodel data.comment = form.cleaned_data['comment'] data.subject = form.cleaned_data['subject'] data.ip = request.META.get('REMOTE_ADDR') data.product_id = id current_user = request.user data.user_id = current_user.id data.save() # save data to table messages.success(request, 'Your Review Has be Send. Thank you for Your Review') return HttpResponseRedirect(url) return HttpResponseRedirect(url) home/urls.py from home import views urlpatterns = [ path('admin/', admin.site.urls), path('home/', include('home.urls')), path('about/', views.aboutus, name='aboutus'), path('contact/', views.contact, name='contact'), path('home/', include('home.urls')), path('product/', include('product.urls')), path('', include('home.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), path('category/<int:id>/<slug:slug>', views.category_products, name='category_products'), path('search/',views.search,name='search'), path('search_auto/',views.search_auto,name='search_auto'), path('product/<int:id>/<slug:slug>', views.product_details, name='product_details'), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) product/models.py class Comment(models.Model): STATUS = ( ('True', 'True'), ('False', 'False'), ('New', 'New') ) product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject … -
Django: How to add dropdown in UserCreationForm?
I have a UserCreationForm in django and that works fine with username, email, password and confirm password but when I extended the form for gender as I did for email it's not saving data coming from drop-down in DB and neither it's visible in admin area. forms.py: from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms GENDER = ( (None, 'Choose your gender'), ('male', 'male'), ('female', 'female'), ('custom', 'custom'), ('Prefer Not To Say', 'Prefer Not To Say'), ) class RegisterForm(UserCreationForm): email = forms.EmailField() gender = forms.ChoiceField(choices=GENDER) class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields + ("username", "email","gender", "password1", "password2") views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import RegisterForm from django.contrib.auth.models import User # Create your views here. def register(request): a = request.POST a = dict(a) print(a) if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): form.save() else: form = RegisterForm() return render(request,'register.html',{'form':form}) register.html: {% extends 'base.html' %} {{% block title %} Register {% endblock title %}} {% load crispy_forms_tags %} {% block body %} <form method="POST" class="form-group container"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Register</button> </form> {% endblock body %} Output: Webpage: Admin Page: … -
Django excel function uploading single row
I'm working on an excel file upload function in Django. My upload function is working, but it's only uploading a single row to the order model even if I have 2 rows. In my Django admin only the object of the first row gets created. models.py class Order(models.Model): item = models.CharField(max_length=30) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) address = models.CharField(max_length=100) views.py def simple_upload(request): if request.method == 'POST': ingredients_resource = IngredientsReource() dataset = Dataset() new_ingredients = request.FILES.get('myfile', None) if new_ingredients is None: messages.info(request, 'Please upload a file.') return render(request, 'upload.html') if not new_ingredients.name.endswith('xlsx'): messages.info(request, 'wrong format') return render(request, 'upload.html') try: imported_data = dataset.load(new_ingredients.read(),format='xlsx') for data in imported_data: value = Order( item = data[0], user = request.user, name = data[1], address = data[2], ) value.save() messages.success(request, 'File upload successful.') return redirect('/upload') except: IntegrityError messages.error(request, 'Wrong file syntax') return render(request, 'upload.html') -
Django submit form using ajax
@csrf_exempt def usersignup(request): if request.method == 'POST': userform = SignUpForm(request.POST) profileform = ProfileForm(request.POST) if userform.is_valid() and profileform.is_valid(): username = userform.cleaned_data['username'] first_name = userform.cleaned_data['first_name'] last_name = userform.cleaned_data['last_name'] email = userform.cleaned_data['email'] password = userform.cleaned_data['password'] user = User.objects.create_user(username,email,password) user.save() gender = profileform.cleaned_data['gender'] birth_date = profileform.cleaned_data['birth_date'] profile = Profile(gender=gender, birth_date=birth_date, user=user) profile.save() datauserform = userform.cleaned_data dataprofileform = profileform.cleaned_data response = {"message":"Registered Successfully", "status":"200", "alert_type":"alert-success"} elif not userform.is_valid(): userformerrors = userform.errors response = {"message":userformerrors, "status":"400", "alert_type":"alert-error"} elif not profileform.is_valid(): profileformerrors = profileform.errors response = {"message":profileformerrors, "status":"400", "alert_type":"alert-error"} return JsonResponse(response) elif not request.user.id: userform = SignUpForm() profileform = ProfileForm() return render(request, 'register.html', {'userform': userform, 'profileform':profileform}) How i submit my django view using ajax submit form.I want success message in alert and error message in span.Please help How i submit my django view using ajax submit form.I want success message in alert and error message in span.Please help How i submit my django view using ajax submit form.I want success message in alert and error message in span.Please help How i submit my django view using ajax submit form.I want success message in alert and error message in span.Please help How i submit my django view using ajax submit form.I want success message in alert and error … -
How to call a function/change bool value in html django by script
I simply want to use 2 for loops in django template with 'if' in inside loop. For now It looks like this: {% for i in tiles_numer %} {% for p in path %} {% if p == i %} <div class = "tile" style = "background-color: black;" value = "{{i}}"> </div> {%endif %} {%endfor%} {%endfor%} But i need something like(i will show u how it would looks like in regular python): for i in tiles_numer: check = False for p in path: if p == i do_something() check = True if check == False: do_somethig_v2() I have a problem with a bool part My idea is to do this with hidden input, can you show me how to call a function (wrote in jquery) that will change value of input ( I would use it as a bool). Or maybe there is a better way to do this? I hope I expressed myself clearly :) -
Provide access to statistics to site users. Google Analytics
I am new to Google Analytics. Please don't throw stones at me. I need to collect statistics of visits to my site and provide access to statistics to registered users. Each user on the site has his own page. I want users to be able to view the statistics of visits to their page. For this I want to use Google Analytics. Deny the user to view the statistics of another's page (the user has access to the statistics of his own page only). I am using Django-Python Can you tell me which GA tools should I use? -
How to include same model relation "parent" in django queryset filter
I have this scenario: class People(models.Model): name = models.CharField(max_length=200) age =... city=... ... parent = models.ForeignKey(People) I am building a search function that takes the user's criteria into a list of Q filters and returns a queryset of the result. How do I get the queryset to include the parents for every person that has a parent but the parent does not fit the search criteria? I can flatten the result and get the id's and do a second query for any parents and merge the two query sets. but is there any way for me to do this in one go within the Q filter function? -
Again: Django - no such table: auth_user
I am sorry for posting a question that has been posted before in different styles. But none of them is really satisfactory. I am just starting out and follow the Django tutorial, did everything written therein including creating a superuser. But when I try to login I get all of these error messages: OperationalError at /admin/login/ no such table: auth_user Request. Method: POST Request. URL: http://magus.pythonanywhere.com/admin/login/?next=/admin/ Django Version: 2.2.7 Exception Type: OperationalError. no such table: auth_user Exception. Location: /usr/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.9 Python Path: ['/home/magus/django_projects/mysite', '/var/www', '.', '', '/var/www', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/lib/python3.6/site-packages'] Server time: Tue, 4 Aug 2020 09:32:05 +0000 Exception Type: Operational Error Exception Value: no After reading answer here and doing lots of migrate/makemigrations ;-) I downloaded the database. And with the help of DB browser for SQLite I could see that the tables are all there! ... as well as the admin. What I though find most curious is the fact that the error shows me Django 2.2.7 BUT I use Django 3.0.9!! Where's the problem? - and what is another solution except for killing the DB and all migrations?? Thanks. -
Verifying email address really exists
I am using Google sign-in in my Django(V2.2.3) application which is to authenticate the user. So, I am requesting the response type as "authorization_code" from google and exchange it for id_token and exchanging id_token for user info. Now, I have a case where a user's email id may be suspended after logged-in. So, I have to validate the email address at regular intervals. Since I am using Google sign-in, I am wondering whether I can use id_token to validate the email address. But the id_token expires in 1 hour. Is there any way to refresh the id_token silently without prompting the user to re-login? -
how can I save or update the data form separately in django?
sorry if I couldn't ask the question properly but I want to update form and that form breaks into 3 parts and this form has more than one field which I need to update but separately so when I did that the request send but no data saved when I'm checking on the process I see that form is invalid so, in this case I tried to update the whole form by sending data in the normal way in HTML: <div> <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> </div> and what I see here is the data is accepted to save so how can I save or update the data form separately not as a bundle so to speak? information_form.html <!-- Update Overview --> <div class="modal fade overview_info" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="container"> <div class="form-group"> <form method="post"> {% csrf_token %} <label>Overview:</label> <p class="col-xs-12">{{ form.overview }}</p> <button type="submit" class="btn btn-primary btn-lg">Update</button> </form> </div> </div> </div> </div> </div> <!-- Update Personal Information --> <div class="modal fade personal_info" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="container"> <div class="form-group row"> <form method="post"> {% csrf_token %} <label>City:</label> <p class="col-xs-12">{{ form.city }}</p> <label>Phone:</label> … -
Django - Show Form Errors on Dynamic Template
I'm trying to obtain form errors on dynamic template without success. I know that instead of doing this form = CommentsForms() return HttpResponseRedirect(url) I Should do something like this : form = CommentsForms() context = {"form":form} return render(request,'somepage.html',context) But instead of somepage.html I want the current Post_Detail page. This is my views.py : def post_detail(request,slug): post = get_object_or_404(Post,slug=slug) commenti = Commento.objects.filter(post=post) commenta = CommentiForms() context = {"post":post,"commenti":commenti,"commenta":commenta} return render(request,'post_detail.html',context) @login_required def addComment(request,slug): post = get_object_or_404(Post,slug=slug) if request.method == 'POST': form = CommentsForms(request.POST) if form.is_valid(): form.save(commit=False) form.instance.post = post form.instance.user = request.user form.save() url = reverse('post-detail',kwargs={'slug':slug}) return HttpResponseRedirect(url) else: form = CommentsForms() return HttpResponseRedirect(url) post_detail.html : {% if request.user.is_authenticated %} {% for comments in commenti %} <li"> <div class="container"> <img class="omg-fluid" src="img/user.png" alt=""> <span>{{ comments.utente.username }}</span> <span">{{ comments.data_commento }}</span> </div> <p>{{ comments.commento }}</p> </li> {% empty %} <li> <p>No Comments!</p> </li> {% endfor %} {% include 'addComment.html' %} {% else %} <h1>You need to be logged for add a comment</h1> {% endif %} addComment.html : <form action="{% url 'commenta' slug=film.slug %}" class="form" method="POST"> {% csrf_token %} {% for fields in commenta %} {{ fields }} {% endfor %} <button type="submit" class="form__btn">commenta</button> </form>