Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to host a Django app on Docker in an Anaconda environment?
May be a fairly simple one to the Docker-savy... I am trying to create a Django app within a Docker container, which is straightforward in-and-of-itself, but I have some complex dependencies. I want to expose a port locally for now, later on an EC2 instance probably or something. I would like to get the benefit of having conda in this environment to handle some non-python dependencies that just pip won't cover. (Specifically Rtree and some things like that...) What is the fastest way to get a Django app hosted in a Docker container IN an anaconda environment that I can quickly/easily grab packages in? -
TypeError: can only concatenate str (not "DeferredAttribute") to str
I am wondering anyone can help me in one of the thing I cannot get my around it and really bothering as I spent last two on it but couldnt make it. Basically, I am building an App (Django Python) to restore the information regarding all the network device e.g hostname, IP Address, S/N, Rack info etc. but I also to enable few options like Add, Edit, Delete and Connect next to device entery. I was able to create all the options except Connect option where I am completely stuck, I am trying to query database to get the IP address information and then using Popen module to open a putty window with the ssh to that IP Address device related, I tried everything I could but nothing worked, thereofrore, asking your help if you have any idea about this ? or any other alternative method for a user when he click on connect the putty or similar app will open and he just put the login credentials and get into the device. I am sharing my code here, let me know if I am doing something wrong. on the show all device page, i have this code, show.html <td><a … -
Simple search engine in Django with custom forms
I am trying to create simple search engine for my project in Django. I could not find anything wrong with my code because there is no error message. When trying to search, it shows all of the records in my database. views.py def zam_details(response, id_z): ls = Zamowienie.objects.get(id=id_z) rsz = '' ssz = '' psz = '' if response.method == "POST": if response.POST.get("szukajProdukt"): rsz = response.POST("rsz") ssz = response.POST("ssz") psz = response.POST("psz") else: rsz = '' ssz = '' psz = '' szukane = ProduktBase.objects.filter(Q(rodzaj__contains=rsz), Q(symbol__contains=ssz), Q(plyta__contains=psz))[:10] return render(response, "zamowienia_lista.html", {"ls": ls, "szukane": szukane}) .html <form method="post" action="."> {% csrf_token %} <div class="row"> <div class="col"> <input type="text" class="form-control" placeholder="Rodzaj" name="rsz" id="rsz"> </div> <div class="col"> <input type="text" class="form-control" placeholder="Symbol" name="ssz" id="ssz"> </div> <div class="col"> <input type="text" class="form-control" placeholder="Płyta" name="psz" id="psz"> </div> <div class="col"> <button type="submit" name="szukajProdukt" class="btn btn-info">Szukaj</button> </div> </div> </form> <br> <table class="table table-bordered"> <thead> <tr> <th>Rodzaj</th> <th>Symbol</th> <th>Plyta</th> </tr> </thead> <tbody> {% for item in szukane %} <tr> <td>{{ item.rodzaj }}</td> <td>{{ item.symbol }}</td> <td>{{ item.plyta }}</td> </tr> {% endfor %} </tbody> </table> urls.py from django.urls import path from . import views urlpatterns = [ path("zam_details/<int:id_z>/", views.zam_details, name="zam_details"), path("create/", views.create, name="create"), path("", views.home, name="home"), ] If you have better … -
How to implement an API effectively in Python?
I just started working with API's and wanted some input. The web application I am creating requires getting various information from the foursquare API for multiple locations. I currently only have 1 location implemented (chipotle) and have already created a ton of variables. I hope to get information such as the store hours, address, etc. for around 10 locations total. Is there any easier way to extract information from an API in JSON format in Python/Flask? Would it be easier to create my own API? @app.route('/home', methods=['POST', 'GET']) @app.route('/', methods=['POST', 'GET']) def home(): chipotle = 'https://api.foursquare.com/v2/venues/587510d3dad26328417dd325/' cafeteria = 'https://api.foursquare.com/v2/venues/4b6b0953f964a5204cee2be3/' params = dict( client_id='', client_secret='', ) #Chipotle resp = requests.get(url=chipotle, params=params) data = resp.json() chipotle_hours = data['response']['venue']['hours']['status'] chipotle_name = data['response']['venue']['name'] chipotle_isOpen = data['response']['venue']['hours']['isOpen'] chipotle_address = data['response']['venue']['location']['address'] return render_template('index.html', chipotle_name=chipotle_name, chipotle_hours=chipotle_hours, chipotle_address=chipotle_address) -
How do I write a polymorphic join table with Django and setup it's associations?
I have four models Skill, Project, Endorsement, and Profile. There are a set list of skills that need to be able to be expanded over time and I want to create a join table that attaches to Project, Endorsement, and Profile. What is the best way to: create a new table with Django called something like SkillJoins which would have a skill_id, target_model, and target_id? and create the proper associations through Project, Endorsement, and Profile to get those lists of skills? I'm not wanting to have Project, Endorsement, and Profile inherit from another model. They are all separate concerns. -
Django module Issue/running django
Started having issues running Django. Install runs without error, however when I check the version packages that show "already satisified" are not found. I've removed my .local and re-installed files, no change. pip3 install /path/.../Django-3.0b1/ --user Processing /path/.../Django-3.0b1 Requirement already satisfied: pytz in /usr/lib/python3.6/site-packages (from Django==3.0b1) (2018.5) Requirement already satisfied: sqlparse in /path/.../.local/lib/python3.6/site-packages (from Django==3.0b1) (0.3.0) Requirement already satisfied: asgiref in path/.../.local/lib/python3.6/site-packages (from Django==3.0b1) (3.2.3) Installing collected packages: Django Running setup.py install for Django ... done Successfully installed Django-3.0b1 python3 -m django --version Traceback (most recent call last): File "/path/.../python/3.7.3b/lib/python3.7/runpy.py", line 193, in _run_module_as_main "main", mod_spec) File "/path/.../python/3.7.3b/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/path/.../Django-3.0b1/django/main.py", line 6, in from django.core import management File "/path/.../Django-3.0b1/django/core/management/init.py", line 14, in from django.core.management.base import ( File "/path/.../Django-3.0b1/django/core/management/base.py", line 11, in from django.core import checks File "/path/.../Django-3.0b1/django/core/checks/init.py", line 9, in import django.core.checks.database # NOQA isort:skip File "/path/.../Django-3.0b1/django/core/checks/database.py", line 1, in from django.db import connections File "/path/.../Django-3.0b1/django/db/init.py", line 2, in from django.db.utils import ( File "/path/.../Django-3.0b1/django/db/utils.py", line 5, in from asgiref.local import Local ModuleNotFoundError: No module named 'asgiref' -
Getting HttpResponse in Django from Javascript fetch
I have a django endpoint: def endpoint(request): return HttpResponse("Hello!") I call it in JS like this: fetch(baseUrl + "endpoint", { method: "POST", }).then(function(data) { // HOW DO I ACCESS THE "Hello!"? }); How do i access the hello! in the .then part? Thanks!! -
IF Statement Causing Unit Test To Fail, But I Dont Know Why
I have the following unit test and cannot figure out why its failing due to the check that the user was redirected from page1 (the test passes is i remove the check), though I cant figure out how to make the test pass with it still there. tests.py def test_redirects_after_POST(self): user = User.objects.create_superuser('username') self.client.force_login(user) response = self.client.post( reverse('page1'), data={ 'first_name': 'testuser', 'dob': UnitTest.set_age(20)} ) self.assertRedirects(response, reverse('page2')) I have tried adding this but it doesnt help: referer = 'http://testserver{}'.format(reverse('page1')) # also tried: referer = 'http://testserver{}'.format(reverse('page2')) response = self.client.post( reverse('page1'), data={ 'first_name': 'testuser', 'dob': UnitTest.set_age(20)} , HTTP_REFERER=referer) views.py @login_required @allowed_users(allowed_roles=['admin', 'registered_user']) def page1(request): if request.method == 'POST': form = Page1Form(request.POST, request.FILES, instance=request.user.page1) if form.is_valid(): form.save() return redirect('page2') else: form = Page1Form(instance=request.user.page1) context = { 'form' : form, } return render(request, 'website/page1.html', context) @login_required @allowed_users(allowed_roles=['admin', 'registered_user']) def page2(request): if request.method == 'POST': form = Page2Form(request.POST, request.FILES, instance=request.user.page2) if form.is_valid(): form.save() return redirect('page3') else: # redirect if user didnt access the page from page1 if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page1'))): return redirect('page1') else: form = Page2Form(instance=request.user.page2) context = { 'form' : form } return render(request, 'website/page2.html', context) error msg AssertionError: 302 != 200 : Couldn't retrieve redirection page '/website/page2/': response code was 302 (expected 200) Thank you -
Are there conventions for naming 'through' models in Django
Django has some very clear conventions for naming models: do so in the singular describe the object the model represents using capWords convention etc. When you are using a 'through' model, to describe a many-to-many relationship however, you are no longer describing an object, but a relationship between objects. Having googled a bit, I can't find any guidance on naming 'through' models. The example used in the django docs (Musician and Band) is named Membership. This is kind of perfect because membership exactly describes the relationship between the musician and the band. But in so many other cases there doesn't seem to be a word (or even phrase) to describe such a relationship. Take for example, the other situation used in the django docs (for a 'normal' many-to-many field) of Pizza and Topping. There doesn't seem to be a good word to describe how a pizza relates to a topping; and if I therefore needed a through field to add additional information (e.g. maybe I have a primary topping and a secondary topping) I end up with a naming difficulty. In practice there are two (maybe more, but two that I can think of) ways to procede: Call the through … -
Place default profile image based on gender in django
I need help on selecting a default profile picture depending on the gender of the user.. I have three default images in my media folder that i want to use as defaults, namely "00.png, 01.png, and 02.png". models.py GenderChoice = ( ('others', 'Others'), ('male', 'Male'), ('female' :'Female') ) class User(AbstractBaseUser): gender = models.CharField(choice=GenderChoice) pro_pic = models.ImageField(upload_to ="", default ="00.png") what I want is if a user selects gender="others" then 00.png should be saved as default and if they select male the 01.png should be selected as default.. Please help🙏🙏🙏 -
Django Url NoReverseMatch at issue
I don't know why I am getting this issue with my code. I've tried a bunch of stuff to resolve it but I can't NoReverseMatch at /property/ Reverse for 'property_detail' not found. 'property_detail' is not a valid view function or pattern name. Request Method:GETRequest URL:http://127.0.0.1:8000/property/Django Version:3.0.5Exception Type:NoReverseMatchException Value: Reverse for 'property_detail' not found. 'property_detail' is not a valid view function or pattern name. Exception Location:E:\django_projects\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677Python Executable:E:\django_projects\env\Scripts\python.exePython Version:3.7.4Python Path: ['E:\\django_projects\\hotel\\src\\project', 'E:\\django_projects\\env\\Scripts\\python37.zip', 'c:\\users\\user\\appdata\\local\\programs\\python\\python37\\DLLs', 'c:\\users\\user\\appdata\\local\\programs\\python\\python37\\lib', 'c:\\users\\user\\appdata\\local\\programs\\python\\python37', 'E:\\django_projects\\env', 'E:\\django_projects\\env\\lib\\site-packages'] html code <ul class="probootstrap-main-nav"> <li class="active"><a href="/">Home</a></li> <li><a href="{% url 'property:property_list' %}">Properties</a></li> <li><a href="{% url 'agents:agents_list' %}">Agents</a></li> <li><a href="{% url 'about:about_us' %}">About</a></li> <li><a href="{% url 'contact:send_mail' %}">Contact</a></li> </ul> project/urls (project directory) urlpatterns = [ path('admin/', admin.site.urls), path('property/', include('property.urls', namespace='property')), path('agents/', include('agents.urls', namespace='agents')), path('about/', include('about.urls', namespace='about')), path('contact/', include('contact.urls', namespace='contact')), ] propert/urls (app) from django.urls import path from . import views app_name= 'property' urlpatterns = [ path('', views.property_list, name='property_list'), path('<int:id>', views.property_detail, name='property_detail'), ] property/views from django.shortcuts import render from .models import (Property, Category) from .forms import ReserveForm def property_list(request): property_list = Property.objects.all() template = 'list.html' context = { 'property_list': property_list, } return render(request, template, context) def property_detail(request, id): property_detail = Property.objects.get(id=id) if request.method == 'POST': reserve_form = ReserveForm(request.POST) if reserve_form.is_valid(): reserve_form.save() else: reserve_form … -
How to pass Django form to parent template HTML file
I have a base template HTML file, which includes a form to be used to search the website. <div id="sidebar"> {{ form }} </div> <div id="content"> {% block content %} {% endblock %} </div> class SearchForm(forms.Form): query = forms.CharField() # ... Right now I'm manually passing form to every single page, since they all extend layout.html: # views.py def contact(request): # ... form = SearchForm() return render(request, 'contact.html', { 'email': email, 'phone': phone, 'form': form, }) Is there another way to render the form and only pass in email and phone when calling render? -
FileStorage in S3 via django
I am looking for any good implementation for storing files on S3 via any Django library or anything which supports fast upload, currently, I have tried with Django-storages but when I have implemented that with models as default storage it takes around 3 seconds to store for around 200kb of images, how can I reduce this time to microseconds? -
'DjangoDetailsView' object has no attribute 'object'
I'm trying to mix CreateView and DetailView in Django in one View, here is how I did it : models.py class Supplier(models.Model): person_name = models.CharField(max_length=850) company_name = models.CharField(max_length=1200) phone = models.CharField(max_length=15) email = models.EmailField(max_length=250, null=True) address = models.CharField(max_length=2200) def __str__(self): return self.company_name def get_absolute_url(self): return reverse('supplier_details', args=[str(self.id)]) class SupplierItem(models.Model): supplier = models.ForeignKey(Supplier, on_delete=CASCADE) item = models.ForeignKey(Item, on_delete=CASCADE) unit_price = models.DecimalField(max_digits=19, decimal_places=10) def __str__(self): return self.item.name def get_absolute_url(self): return reverse('portal_to_supplier', args=[str(self.supplier.id)]) forms.py class SupplierItemForm(forms.ModelForm): class Meta: model = SupplierItem fields = ['item', 'unit_price'] views.py class SupplierDetailsView(FormView, DetailView): model = Supplier form_class = SupplierItemForm def get_context_data(self, **kwargs): context = super(SupplierDetailsView, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def post(self, request, *args, **kwargs): return FormView.post(self, request, *args, **kwargs) The page renders great and the form too, but then I submit the form, it gives me this error : 'SupplierDetailsView' object has no attribute 'object' NOTE object is used as the object itself in the detail view, I'm rendering it inside the HTML as {{objects.name}}, it works great in the GET but seems like not found in POST FUll traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/supplier/4/details Django Version: 3.0.2 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'el_pagination', 'mathfilters', … -
How to fix no module found error in running Django Test
I am trying to run some simple tests for my blog app. I installed social_django beacsue I want users to be able to sign in with either their Facebook, Twitter or Google Account. On running my test using python manage.py test I get this error. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_fr File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 143, in create raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'django.test.TestCase' isn't a subclass of AppConfig. PS C:\Semicolon\Software Engineering\Web Development\Back End\Django Projects\christian_blog\christian_blog> ^C PS C:\Semicolon\Software Engineering\Web Development\Back End\Django Projects\christian_blog\christian_blog> python manage.py test Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File … -
For minimum resource usage in Django, should we gzip responses or respond uncompressed data?
Gzipping itself puts some extra load on server but this response is received by client quickly and servers gets freed quickly. But responding uncompressed data, it doesn't cost the extra load on server but it increases waiting time so client can receive all data. Between these two scenarios, which one is more optimized approach and why? -
NoReverseMatch at /basketball/ Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried:
I have a Django app where a user can create a Basketball object using the Basketball model and post it to a feed that is a ListView subclass. I then want other users to be able to access the details of that post by clicking the hyperlink for the object. The problem is, when I set the url for the details page to contain the variable "slug" as the object slug, it overwrites my list page with the url route "" as seen in basketball/urls.py, instead of routing to the list page it says it can't find a page with an empty slug. This does not allow me to get to the url "http://127.0.0.1:8000/basketball/" I'm working under the impression Django searched for url routes in order, so since the blank path is the first route it should be seen before the route containing the slug. Note the piece of code that is directly causing the issue is in basketball_list.html: <a href= "{% url 'basketball:detail' basketball.slug %> when this code is removed I am able to access "http://127.0.0.1:8000/basketball/" but the hyperlinks aren't there so it defeats the purpose. Note that I am using: Python == 3.8.3 Django == 3.0.6 models.py: from … -
How can I print all the products attributes in product.html
This is my models.py class Product(models.Model): title = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) price = models.FloatField() summary = models.TextField(blank=False, null=False) image = models.ImageField(blank=True, null=True) This is my Django views.py def products_view(request,*args, **kwargs): print(Product.objects.values()) myDict = list() for product in Product.objects.all(): my_product = { "product_id": product.id, "product_title":product.title, "product_description":product.description, "product_price":product.price, "product_summary":product.summary, "product_image":product.image } print(my_product) return render(request, "products.html", my_product) This my products.html {% extends 'base.html' %} {% block content %} <h1>Products Page</h1> <ul> {% for product in my_product %} <div class="card" style="width: 18rem;"> <img src="{{ product_image }}" class="card-img-top" alt="{{ product_id }}"> <div class="card-body"> <h5 class="card-title">{{ product_title }}</h5> <p class="card-text">{{ product_description }}</p> <a href="/cart" class="btn btn-primary">Add to Basket</a> </div> </div> {% endfor %} </ul> {% endblock %} My Product.html page only show the "h1" tag, do not show the Products attributes. How can I achieve this problem? -
How to solve link Posts and users to comments in Django Admin
I am trying to link each comment to a post and to a username I have proceeded with the logic of the comment with the following models.py class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) content = models.TextField(max_length=160) def __str__(self): return self.content Now that the comment is working and everything I am trying to link the comment section to the post and the user of the comment in the admin so I used the following models.py class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) content = models.TextField(max_length=160) def __str__(self): return '{}-{}'.format(self.post.title, str(self.user.username)) <----Error line Which is returning AttributeError at /admin/score/comment/ 'NoneType' object has no attribute 'title' Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'title' What should fix this problem I have also used the following which did not work def __str__(self): return '%s %s' % (self.post.title, self.user.username) -
django creating dupliucate images as and when the profile page is loaded
In my Django app, I have a user profile page displaying the user profile image apart from the other information. Every time I load this page, a duplicate copy of image is created with an additional 'key' and is saved in my media folder. I'm facing difficulty in resolving this This is what my user model looks like: class CustomUser(AbstractUser): email =models.EmailField(unique =True) state = models.CharField(max_length =100) city = models.CharField(max_length=100) is_active =models.BooleanField(default=False) about_me =models.TextField(max_length=255,default =None,blank=True,null =True) user_image =models.ImageField(upload_to="images",default =None,null =True,blank=True) def save(self,*args,**kwargs): try: # opening the uploaded image im =Image.open(self.user_image) output =BytesIO() # resize image im =im.resize((130,100)) # after modification, save to ouput im.save(output,format ='JPEG',quality =100) output.seek(0) self.user_image =InMemoryUploadedFile(output,'ImageField',"%s.jpg" % self.user_image.name.split('.')[0],'image/jpeg', sys.getsizeof(output),None ) except: pass super(CustomUser,self).save() def get_absolute_url(self): return reverse('view_profile',args =[(self.pk)]) Let me know if you need anything else -
how to combine generic `detailsView` and `CreateView` in a single view in django
I'm trying to combine detail and create in a single view in Django generic views, here is my code : models.py class Supplier(models.Model): person_name = models.CharField(max_length=850) company_name = models.CharField(max_length=1200) phone = models.CharField(max_length=15) email = models.EmailField(max_length=250, null=True) address = models.CharField(max_length=2200) def __str__(self): return self.company_name def get_absolute_url(self): return reverse('supplier_details', args=[str(self.id)]) class SupplierItem(models.Model): supplier = models.ForeignKey(Supplier, on_delete=CASCADE) item = models.ForeignKey(Item, on_delete=CASCADE) unit_price = models.DecimalField(max_digits=19, decimal_places=10, default=00.00) def __str__(self): return self.item.name urls.py path('<int:pk>/details', views.SupplierItemsView.as_view(), name="supplier_details"), views.py class SupplierItemsView(View): def get(self, request, *args, **kwargs): view = SupplierDetailsView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = SupplierItemCreate.as_view() return view(request, *args, **kwargs) class SupplierDetailsView(DetailView): model = Supplier class SupplierItemCreate(CreateView): model = SupplierItem fields = ['item', 'unit_price'] Now I want the detail view to be viewed including the create view inside of it, I've tried to render the HTML like this : templates/appName/supplieritem_forms.html <form method="post"> {{ form }} </form> templates/appName/supplier_detail.html .... {% include 'profiture_supplier/supplieritem_form.html' %} .... The result that it shows the details HTML view rendered perfect, but the form is never shown -
Django and Firebase Auth
I'm trying to use Firebase Auth with Django, but I have a few questions. So far, I've successfully created a demo app with a login form. Upon load the page checks if firebase.auth().currentUser is set, and disables the Login button if so. If not set, then login form is editable. When user logs in, I'm calling firebase.auth().signInWithEmailAndPassword. If that succeeds, I'm calling a backend view through Ajax to verify the ID token. Now I'm trying to tie all this in with a more realistic Django app. There's some index resource at, say www.example.com, and there's the login page at www.example.com/login. When user first goes to www.example.com, the view will check if the ID token exists in the request (and verify it if yes), and then return the index resource. If not, it will redirect to login resource. Once on the login page, how would I send the user to the index page after login with the ID token in the request header? I can make ajax requests from the login page, but how do you actually send the user to another page with this authorization header in "Django style"? -
AJAX sending empty FormData
I;m trying to send a file via ajx FormData but it is sending None instead. JS: $('#hide').click(function(e){ e.preventDefault(); var fd = new FormData(); fd.append('file', $('#lecturefile').prop('files')[0]) $.ajax({ type: 'POST', url: "{% url 'create_course' instructor.id %}", headers: { 'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val() }, data: fd, processData: false, contentType: false, success:function(){ console.log('done!!') } }); }); Views.py: file = request.FILES.get('data') print(file) con = CourseContent.objects.filter(user = request.user).latest('id') lec = CourseLecture.objects.filter(content = con).latest('id') lec.file = file lec.save() Printing var file gives None. Appreciate the help. -
How could I modify django-tracking2 so users can opt out of tracking
I'm making a website right now and need to use django-tracking2 for analytics. Everything works but I would like to allow users to opt out and I haven't seen any options for that. I was thinking modifying the middleware portion may work but honestly, I don't know how to go about that yet since I haven't written middleware before. I tried writing a script to check a cookie called no_track and if it wasn't set, I would set it to false for default tracking and if they reject, it sets no_track to True but I had no idea where to implement it (other than the middle ware, when I tried that the server told me to contact the administrator). I was thinking maybe I could use signals to prevent the user being tracked but then that would slow down the webpage since it would have to deal with preventing a new Visitor instance on each page (because it would likely keep making new instances since it would seem like a new user). Could I subclass the Visitor class and modify __init__ to do a check for the cookie and either let it save or don't. Thanks for any answers, if … -
Django form CharField not setting initial value
I am trying to set initial values in a Django form that is shown more than once in a view. Unfortunately even with 3 hours of searching and debugging, it ends up like everything I have tried does not work. My form is used to create a message object linked to a conversation (I'm building a chatbot app) and in my conversation template I show every message in a form to make it editable afterwards. The problem is that every field of the form does set the default value I passed to the form inside the message_values var in my view.py except one : the "tag_list" CharField (see below). I cannot use ModelForm because a message is composed of several models (q_reply_* fields will create QuickReplies() objects in my view, tags will create several Tags() etc.) I have tried passing the data specifying initial = message_values in the view when creating the form, setting the value through __init__ by getting the value in kwargs (like i did for the messages var) but it just does not want to work... I don't get any error anywhere, zero warnings and when debugging I got the confirmation that my ManyToMany where I get …