Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to pass varibale to Mixin
Let's say I have the following function-based view, where I pass the argument fofname to the view: def illiquid_reporting(request, fofname): ... If I want to make a class-based view out of it, is the below way the correct method to pass the argument: class IlliquidReporting(TemplateView) def get_context_data(self, fofname **kwargs): context = super().get_context_data(**kwargs) ... -
nginx.conf settting for django
On my ubuntu server i would setting nginx.conf for work with my django app I setup che nginx.conf file like this: user root; worker_processes auto; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; # Load dynamic modules. See /usr/share/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; index index.html index.htm; server { listen 80 default_server; listen [::]:80 default_server; server_name 34.233.212.246; root /usr/share/nginx/html; #root /home/ec2-user/carrera/podium/static; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { proxy_pass http://127.0.0.1:8000; #proxy_set_header X-Forwarded-Host $server_name; #proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; add_header P3P 'policyref="/w3c/p3p.xml", CP="IDC DSP COR ADM DEVi TAIi PSA PSD $ } # redirect server error pages to the static page /40x.html # error_page 404 /404.html; location = /40x.html { } # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { } } … -
How to create dynamic route for file paths in flask app
In my application I have a file browser. The file names are urls for a detail page, wich takes as argument the bucket and the object name. @app.route("/object_info/<string:bucket_name>/<string:object_name>/", methods=["POST", "GET"]) def object_info(bucket_name, object_name): Like this: http://localhost:5000/bucket_name/Grain_08.tif/ This is working fine, but I cannot display the files in subfolders like in 1aaaa, because if I click to the 2. row the url is: http://localhost:5000/bucket_name/1aaaa/Grain_11.tif and so the url pattern for the object_info route is not working. I have tried solutions like optional routes, but the depth of the subfolders are not limited. Thats mean there can be a file in 4 subfolders. So I need some dynamic stuff so I can display the objects in the deeper folders. -
Is there something called quote_plus from request.compat?
I;m trying to import request.compat.quote_plus but they say cannot find reference in compat.pyi. Is there a fix to this? -
Django/Python3: Convert complex inner join query to
I am developing a book sales application on Django and I need to get a list of the most popular book categories from the books sold. Models: Category (id, name) BookCategory (id, category[FK], book[FK]) Sales(id, book[FK]) Book(id, name) The following SQL is the equivalent of my requirement but I have no idea how to use this using Django models and filtering. sql = "SELECT c.* FROM category c INNER JOIN book_category bc ON c.id = bc.category_id INNER JOIN sales s ON s.book_id = bc.book_id GROUP BY c.id ORDER BY count(s.id) DESC" I have used the following lines of code to execute this but get an error. categories = Category.objects.raw(sql) Object of type 'RawQuerySet' is not JSON serializable How can I accomplish this? -
Can't access /admin in Django in AWS EC2
I deployed my project in AWS EC2 instance, but I can't access the admin site, on going to /admin URL, it gives 404 Error. -
How do I get an AJAX callback function to render a Django url or html template with parameters?
I am a beginner and working on an app where I want to redirect the user to a checkout-basket (Django url via POST? Or render html template with variables?) after checking if anything is saved in localStorage. So I check that and use AJAX to send that data to my Django url in order to render that template passing on the variables in localStorage as JSON. But return render(request, "pizza/prebasket.html", context) in views.py doesn't work: even though the data is recieved, prebasket.html is not rendered. I read that that's because AJAX doesn't allow that and instead I need to post through AJAX's callback function. But how do I do that via POST and how do I pass on the parameters to my view or directly to my html template? (window.location.href only handles GET requests, so I guess that doesn't work). Here's my JavaScript and my views.py: function previous_selection () { if (localStorage.getItem("preselection") != null) { const data = new FormData(); data.append("preselection", preselection); const request = new XMLHttpRequest(); request.open('POST', '/prebasket'); const csrftoken = getCookie('csrftoken'); request.setRequestHeader("X-CSRFToken", csrftoken); console.log("DATA IS: ", data); request.send(data); console.log("PRESELECTION IS: ", preselection); request.onload = () => { // HOW DO I CALL MY URL WITH PARAMETERS HERE? }; … -
How can I fetch data from other's app forms Django
Well I am making a Chat type web app in which user enters a name to start . I want to showcase that name whenever user sends a message . Both are different apps. So how can I fetch name that user enter to showcase whenever he sends message -
how can i see django database that is storing values on its own from site server?
I am trying to store the questions tag in sqlite3 of Django but whenever I am trying to click on Question in /admin/ it shows error : error image in case image is not displayed, this is error { OperationalError at /admin/userinfo/question/ no such table: userinfo_question Request Method: GET Request URL: http://127.0.0.1:8000/admin/userinfo/question/ Django Version: 3.0.5 Exception Type: OperationalError Exception Value: no such table: userinfo_question } I have already tried changing sqlite3 path in settings (error not resolved same error) python manage.py migrate --run-syncdb (migrations apply error not resolved) this was written while doing migrations Creating tables... Running deferred SQL... so I am thinking that the table is creating but not displaying( might be) this is my models.py ''' from django.db import models # Create your models here. class Question(models.Model): prob_link = models.CharField(max_length=500, default='') prob_level = models.CharField(max_length=1) prob_rating = models.IntegerField() expression_parsing = models.BooleanField(default=False) fft = models.BooleanField(default=False) two_pointers = models.BooleanField(default=False) binary_search = models.BooleanField(default=False) dsu = models.BooleanField(default=False) strings = models.BooleanField(default=False) number_theory = models.BooleanField(default=False) data_structures = models.BooleanField(default=False) hashing = models.BooleanField(default=False) shortest_paths = models.BooleanField(default=False) matrices = models.BooleanField(default=False) string_suffix_structures = models.BooleanField(default=False) graph_matchings = models.BooleanField(default=False) dp = models.BooleanField(default=False) dfs_and_similar = models.BooleanField(default=False) meet_in_the_middle = models.BooleanField(default=False) games = models.BooleanField(default=False) schedules = models.BooleanField(default=False) constructive_algorithms = models.BooleanField(default=False) greedy = models.BooleanField(default=False) bitmasks … -
How to stop user coming back to login page using back button in django
I have a created a website in django and when hit backbutton it comes to login page how to avoid that. -
Django: Send form inputs in URL
I am new to Django and was trying to create a web-app student management system in which students are added by admin and students can edit their details by entering their enrollment-id. In models.py I added this model class Student(models.Model): gender_choices = [('M', 'Male'), ('F', 'Female')] enrollment_no = models.CharField(max_length=10, primary_key=True, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) father_name = models.CharField(max_length=50) mother_name = models.CharField(max_length=50) address = models.CharField(max_length=200) dob = models.DateField('date of birth') gender = models.CharField(choices=gender_choices,max_length=1,default=None) def __str__(self): return (self.first_name +" "+ self.last_name) form for entering student enrollment id at index.html page is <form action="{% url 'students:detail' %}" method="post"> <div class="form-group"> <label for="enrollmentid">Enrollment ID: </label> <input type="text" class="form-control" id="enrollmentid" placeholder="Enter enrollment id"> </div> <div class="form-group"> <label for="dob">Date of Birth: </label> <input type="email" class="form-control" id="dob" placeholder="Enter dob (YYYY-MM-DD)"> </div> <button class="btn btn-primary">Edit Details</button> </form> Now I want to go to /students/detail/{enrollment id given by user} route how can i pass the input to url In views.py I have defined def detail(request, student_id): try: student = Student.objects.get(pk=student_id) except Student.DoesNotExist: raise Http404("Student do not exist") return render(request, 'students/detail.html', {'student': student}) In urls.py I have defined app_name = 'students' urlpatterns = [ path('', views.index, name='index'), path('detail/<student_id>', views.detail, name='detail') ] If i manually enter http://localhost:8000/students/detail/ABC1235 then I … -
Django Template nests script automatically
AOS and Chart.js files are getting overlapped. I am using django 3.0.5. In the template, I have tried using 1 script block and 2 script blocks (shown in the example below), but it still keeps giving the same error. The scripts in the code are in different tags but the response sent by the local server nests the scripts. base.html script part <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> {% block script %} {% endblock script %} {% block script_2 %} {% endblock script_2 %} weatherdetail.html script part {% block script %} <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <script> // TEMPERATURE GRAPH var chart_temperature = document.getElementById('tempChart').getContext('2d'); var chart = new Chart(chart_temperature, { type: 'line', data: { labels: {{days | safe}}, datasets: [{ label: 'Maximum Temperature', backgroundColor: 'rgba(255, 255, 255, 0)', borderColor: 'rgba(255, 0, 0, 0.9)', data: {{temp_high | safe}} }, { label: 'Minimum Temperature', backgroundColor: 'rgba(255, 255, 255, 0)', borderColor: 'rgba(255, 150,0,0.9)', data: {{temp_low | safe}} }] }, options: { scales: { yAxes: [{ ticks: { max: 50, min: 0, stepSize: 10 } }] } } }); // PRECIPITATION GRAPH var chart_precipitation = document.getElementById('precipChart').getContext('2d'); var chart = new Chart(chart_precipitation, { type: 'line', data: { labels: {{days | safe}}, datasets: … -
In django while using images from static folder how can we call the images in main index
I used this syntax but I think after background images there is some problem please fix guys. <header class="intro-header" style="background-image: {% static 'img/home.jpg' %}"> -
Making related query?
There are 3 models, I want to execute a query like this select article_id from votes_vote where user_id=user.id and value=True with the orm. I try this Article.objects.filter(author=user.id, likes=True) Vote class Vote(models.Model): value = models.NullBooleanField() user = models.ForeignKey(User, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='likes') voted_on = models.DateTimeField( auto_now=True ) article class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(db_index=True, unique=True, max_length=255) title = models.CharField(max_length=255) subtitle = models.CharField(blank=True, max_length=400) # El campo RichTextUploading lo heredo de CKEDITOR body = RichTextUploadingField() image = models.ImageField(upload_to='featured_image', blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user class User(AbstractUser): # Lista de cohortes de Academlo COURSE_START = [ ('J2019', 'Julio 2019'), ('E2020', 'Enero 2020'), ('M2020', 'Mayo 2020'), ] GENDER = [ ('M', 'Hombre'), ('F', 'Mujer') ] # Campos de usuario first_name = models.CharField(max_length=200, blank=False) last_name = models.CharField(max_length=200, blank=False) username = models.CharField(max_length=200, blank=False, unique=True) email = models.EmailField(unique=True, max_length=300, blank=False) course = models.CharField(choices=COURSE_START, max_length=5) gender = models.CharField(choices=GENDER, max_length=1) -
Django: Update Record before save
Model: class Tester: test = models.ForeignKey(Platform) count = models.Integer() status = models.CharField(max_length=1, default='A') I need to change the status to 'D' every time I insert a new record for the same test. I tried using Signals pre_save, but that function went into a loop. I would really appreciate any help. -
MongoDB Atlas connection issue with Django
I am trying to connect my Django application with the Atlas MongoDB cloud database using Djongo. The setting file database section is, DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'mydb', 'HOST': 'mongodb+srv://user:' + urllib.parse.quote_plus('password') + '@xx-xxxxx.mongodb.net/test?retryWrites=true&w=majority', 'USER': 'user', 'PASSWORD': 'password', } } But after running python manage.py migrate, it is throwing the following error, File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\migrate.py", line 87, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\recorder.py", line 73, in applied_migrations if self.has_table(): File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\introspection.py", line 48, in table_names return get_names(cursor) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\introspection.py", line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\djongo\introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pymongo\database.py", line 856, in list_collection_names … -
Django environment/setup issue: AttributeError: 'Settings' object has no attribute 'USE_REDIS'
I am new to django and docker setup environment. I have an existing django project that I need to deploy on my local server. I am configuring my python environment on Windows for Linux Ubuntu 18.04 TLS. I am able to do my setup with pipenv install. Following django packages got installed: Django==3.0.5 django-cors-headers==3.2.1 django-debug-toolbar==2.2 django-environ==0.4.5 django-filter==2.2.0 django-polymorphic==2.1.2 django-storages==1.9.1 djangorestframework==3.11.0 but when I run django-admin --version, I get error: AttributeError: 'Settings' object has no attribute 'USE_REDIS' Full stack-trace is as given below: Traceback (most recent call last): File "/home/username/.local/share/virtualenvs/project_code/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/home/username/.local/share/virtualenvs/project_code/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/username/.local/share/virtualenvs/project_code/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/username/.local/share/virtualenvs/project_code/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/username/.local/share/virtualenvs/project_code/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/username/.local/share/virtualenvs/project_code/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.7/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 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/mnt/c/Users/pgupta15/git_repos/uppley-backend/catalystlab/models.py", line 11, in <module> from catalystlab.data.models.entity import Tag, Type, Entity, update_types File "/mnt/c/Users/pgupta15/git_repos/uppley-backend/catalystlab/data/__init__.py", line 32, … -
Django form containing different types of fields
I'm wanting to add a MultipleChoiceField with a CheckboxSelectMultiple widget to a model/form containing other types of input. I am wondering how I can do this and add classes to the entire MultipleChoiceField as well as classes to each of the choices (for bootstrap). I have tried adding a class to the whole MultipleChoiceField using: preferred_subjects.widget.attrs.update({'class': 'form-control'}) but it doesn't work. Even if it did, I also want to add classes to each of the options, but I am unsure how. I usually output forms using {{ form|crispy }} but since I want to add classes to each of my MultipleChoiceField options im guessing i'll need to use {% for option in fieldset %} and add classes as each is output. But the problem is I have other types of input in that same form which I don't want to add the class names to. Here is my code: class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200, default='') dob = models.DateTimeField('Date of birth (mm/dd/yyyy)', null=True, default=now) subjects = model.CharField(max_length=200, default='') class PersonalInformationForm(forms.ModelForm): SUBS = ( ('MATH', 'Maths'), ('ENG', 'English'), ) subjects = forms.MultipleChoiceField(choices=SUBS, widget=forms.CheckboxSelectMultiple()) class Meta: model = PersonalInformation fields = ['first_name', 'gender', 'subjects'] Summary - I want to … -
Is there any method to display list items in django template with variable name as atrributes?
I want to display all the tags related to post but in different color-badge. But in place of color variable there is nothing appears and when i do with the just constant numbers like colors.0 it works but i don't want one color, I want to be change the color as the tags changes. here is my views.py file: def blogs(request): posts = Post.objects.order_by('-posted_on') tags = Post.tags.most_common()[:5] colors = [ 'primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark' ] context = { 'posts': posts, 'tags': tags, 'colors': colors } return render(request, 'writeups/blogs.html', context) and my blogs.html template: {% for post in posts %} <div class="card border-dark mb-3 w-100"> <div class="card-header">{{ post.posted_on|date:"F d, Y" }}</div> <div class="card-body text-secondary"> <h5 class="card-title">{{ post.title }}</h5> <p class="card-text">{{ post.description }}</p> {% for tag in post.tags.all %} {% with forloop.counter as color %} <span class="badge badge-{{ colors.color }}">{{ tag }}</span> {% endwith %} {% endfor %} </div> </div> {% endfor %} -
How to start and stop celery beat and workers in Django?
I'm getting some data from an API every 30 seconds and insert to mongoDB periodically. hence, I used celery to process it in the background. celery.py as follow: @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): from example.tasks import API sender.add_periodic_task(30, API.s(), name='Api') I have tasks.py as follow: @shared_task def API(): data=request.get(url).json() db.collectionName.insert_many(data) Then, I used two commands to run the task in the background periodically: celery -A DjangoCelery1 beat -l info celery -A DjangoCelery1 worker -l info Everything all right and data is getting from the API and saved in MongoDB. Now, I want to able to start and stop all running tasks by press a button on a web page. What should I do for this? -
Django - How to check all the attributes of a queryset?
I am looking a way to get all the attributes of a variable after we set the value in it using queryset. For example...refer below code... using user.id or user.first_name i can get the value for that attribute. But if i want to check what all other attributes it has? Is there a way i can get. If we use user then it will just return which is what we have defined in admin.py. Code, i am using Django Shell from django.contrib.auth.models import User user=User.objects.get(id=1) user.first_name # Will return some value say testUser user.id # will return some value say 1 -
Django Rest Framework return user profile along with api token after login or registration
I've got the following serializer: from rest_framework import serializers from allauth.account import app_settings as allauth_settings from allauth.utils import email_address_exists from allauth.account.adapter import get_adapter from allauth.account.utils import setup_user_email from kofiapi.api.users.models import User, UserProfile class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('dob', 'phone', 'receive_newsletter') class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) class Meta: model = User fields = ('url', 'email', 'first_name', 'last_name', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() UserProfile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = validated_data.get('email', instance.name) instance.save() profile.dob = profile_data.get('dob', profile.dob) profile.phone = profile_data.get('phone', profile.phone) profile.receive_newsletter = profile_data.get('receive_newsletter', profile.receive_newsletter) profile.save() return instance and these are the respective routes I have: router = DefaultRouter() router.register(r"users", UserViewSet) urlpatterns = [ path('', include(router.urls)), path('rest-auth/', include('rest_auth.urls')), #path('rest-auth/registration/', include('rest_auth.registration.urls')), ] I'm using: 'rest_framework', 'rest_framework.authtoken', 'rest_auth', configured as: AUTH_USER_MODEL = 'users.User' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), } when I log in I'm getting back only the token key: { "key": "8c0d808c0413932e478be8882b2ae829efa74b3e" } how can I make it to return user info along with the key upon registration/login? Something like: { "key": "8c0d808c0413932e478be8882b2ae829efa74b3e", "user": { // user data } } -
Python crashes when including a template
this is the first time that i ask something here so excuse me if im been not so clear about the issue. At my views, i have the def home that renders the template home.html passing two variables: posts and trendList. Home.html: <div class="create"> {% include 'snippets/create.html' %} </div> <div class="main"> <div class="feed"> {% block detail %} {% endblock detail %} {% include 'snippets/post.html' %} </div> <div class="trends"> {% include 'snippets/trendList.html' %} </div> </div> The code only freezes when i do the 'include post.html'. If i call it in block format, it does not load the post.html inside the block. Post.html <div class="post"> <p> {{ post.text }}</p> <p> {{ post.created_at }}</p> <p> {{ post.author }}</p> <a href="{% url 'who_liked' pk=post.pk %}" >{{ post.likes.count }}</a><br> <a type="button" href="{{ post.pk }}" >Like</a> </div> {% endfor %} But if i click in an object of trendList, it works fine, redirecting me to the home.html with the template loading inside the blocks. I don't know why 'include post.html' crashes the program and putting it in blocks will do nothing. Thanks in advance. -
Django - Rendering a template multiple times in a loop
I have a Django view that receives a list of selected files in request. I want to iterate over all files and render the same template for each file (one after the other). Is there a way/hack to re-render the template with the modified context without returning from the view? Or is there a way to do it with javascript using local-storage, i.e., calling the view for each file (one after the other)? -
Why am I getting a Django Reslover404 Error?
I'm studying Django with djbook and so far created my 'polls' app. It works fine but when I added a log file, there is an error message in it: Exception while resolving variable 'name' in template 'unknown'. Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/lib/python3.8/site-packages/django/core/handlers/base.py", line 100, in _get_response resolver_match = resolver.resolve(request.path_info) File "/usr/lib/python3.8/site-packages/django/urls/resolvers.py", line 567, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLPattern list> (admin:admin) 'admin/'>], [<URLResolver <module 'polls.urls' from '/home/DeadMoroz/mysite/polls/urls.py'> (polls:polls) 'polls/'>]], 'path': ''} ... During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/django/template/base.py", line 848, in _resolve_lookup raise VariableDoesNotExist("Failed lookup for key " django.template.base.VariableDoesNotExist: Failed lookup for key [name] in <URLResolver <module 'polls.urls' from '/home/DeadMoroz/mysite/polls/urls.py'> (polls:polls) 'polls/'> Not Found: / My 'polls/urls.py' file seems to be the same as in Django Book: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] Here's my project file structure: polls/ ---logs/ ------debug.log ---migrations/ ---static/ ------polls/ ---------images/ ------------background.gif ------style.css ---templates/ ------admin/ ---------base_site.html ------polls/ ---------detail.html ---------index.html ---------results.html ---__init.py__ ---admin.py ---apps.py ---models.py ---tests.py ---urls.py ---views.py I'm very …