Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React SPA with initial state/route, served from Django
I am facing an unusual use-case with React and Django. My process starts with a POST request initiated by an app running on user's system to my Django server(The response is displayed on the browser). The POST request contains the data required for authenticating the user. Once authenticated, the server returns a simple HTML page customized for that user, including the details necessary to authenticate subsequent requests(like form submissions). Now I need to replace that simple HTML page with a react application. The problem is how can I embed the user specific info into the react app when returning the react app from server, so that I don't have to ask user to provide authentication information again once application loads on browser. Is this even possible while using react? -
Django DateTimeField query last hour
I'm trying to query the data from the last hour form a postgreSQL database, this is the table model in Django: class data(models.Model): fecha = models.TextField(db_column='Fecha', blank=True, null=True) # Field name made lowercase. hora = models.TextField(db_column='Hora', blank=True, null=True) # Field name made lowercase. lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) tipo = models.BigIntegerField(db_column='Tipo', blank=True, null=True) # Field name made lowercase. ka = models.FloatField(db_column='kA', blank=True, null=True) # Field name made lowercase. error = models.FloatField(blank=True, null=True) tiempo = models.DateTimeField(db_column='Tiempo',primary_key=True, blank=True, null=False) # Field name made lowercase. geom = models.PointField(blank=True, null=True) and this is what I have in my views file: from datetime import datetime, timedelta time = datetime.now() - timedelta(hours=1) def last_hour(request): hour = serialize('geojson',data.objects.filter(tiempo__lt=time)) return HttpResponse(hour, content_type='json') I haven been luckly with the information of other posts. My Django version is 3.0.5 and the timezone data in postgreSQL is utc-5 -
In Django REST Framework, how to filter list based on user?
I have two models, User and Book. Users own books and can only be seen by their owners. NOTE: the book model is handled in a separate database, so I can't use a foreign key on Book pointing to User. Not sure if this matters. If I'm authenticated, and send a GET /books request, I want only the books owned by the user to be shown. If I'm not authenticated, I should get a 403 error. Where should I implement this logic? I could do it in the View, with something like this: class BookView(APIView): """ Get books """ permission_classes = (IsAuthenticated, IsBookOwner,) queryset = Book.objects.all() serializer_class = BookSerializer def post(self, request): # create a book def get(self, request): books = Book.objects.filter(owner_id=request.user.owner_id) serializer = self.serializer_class(books, many=True) return Response(serializer.data) class IsBookOwner(permissions.BasePermission): """ Object-level permission to only allow seeing his own books """ def has_object_permission(self, request, view, obj): # obj here is a Book instance return obj.owner_id == request.user.owner_id Is this the correct way to do it? Also, is the IsBookOwner permission doing anything here? -
how can I run celery task only once in django?
from __future__ import absolute_import, unicode_literals from celery import shared_task from celery.task import periodic_task from celery.schedules import crontab from datetime import timedelta @periodic_task(run_every=(crontab(minute='*/1')), name='greeting_task') def greeting_task(): print('hello Dias!') Can I create a function that runs only once at certain time with crontab? PLEASE, HELP!!! thanks in advance! -
Hide a button when another is clicked with ajax
I'm currently triying to implement a voting system similar to the one in Hackernews. When the votearrow is clicked, the nuber of votes should update and the unvote button should appear. Since I don't want to reload the wholepage, I am using ajax to handle the votes requests. I'm struggling with the voting system (showing unvote and hiding votearrow when votearrow is clicked and vicecersa). With the current implementation when i clicked the votearrow, it hides as expected but does not show the unvote button (I need to reload) and the same happens with the unvote button, It hides but does not show the vote button... I have the following html template: ... {% for contribution in contribution_list %} ... {% if not user.is_authenticated %} <button onclick="location.href = 'http://127.0.0.1:8000/login/google-oauth2/?next=/';" id="myButton" class="votearrow"></button> {% elif contribution.id_contribution not in voted %} <button class="votearrow" id="vote{{ contribution.id_contribution }}" likehref='{{ contribution.get_api_like_url }}' userlike='{{ user.pk }}' contid='{{ contribution.id_contribution }}'></button> {% endif %} ... <span class="score">{{contribution.points.count}} point</span> by <a> {{contribution.author}} </a> <span class="age"> {{contribution.whenpublished}} </a> </span> {% if user.is_authenticated %} {% if contribution.id_contribution in voted %} <button class="unvote" id="unvote{{ contribution.id_contribution }}" likehref='{{ contribution.get_api_like_url }}' userlike='{{ user.pk }}' contid='{{ contribution.id_contribution }}'>Unvote</button> {% endif %} {% endif %} ... And … -
How do I view the first name of a user in Django?
I have set up my blog so that when a user clicks on the displayed name, it will go to that user's blogs (filtered that so only that person's blogs will show up). I used {{ view.kwargs.username }} to show the person's username, but I'd rather show the first name. What can I change to accomplish this? blog/templates/blog/user_post.html: {% extends 'blog/base.html' %} {% block content %} <h1 class="mb-3">Posts by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1> {% for post in posts %} <article class="media content-section"> <img class="rounded article-img mt-2" src="{{ post.author.profile.image.url }}" alt=""> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author.profile.user.first_name }} {{ post.author.profile.user.last_name }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% … -
Django - extract filtered data
I have a django-filter (OrderFilter) to display a filtered table, now I want to extract to excel the same filtered table. My code works but the get return blank. Can you help please ? Views.py def Order(request): filter= OrderFilter(request.GET, queryset=Order.objects.all()) orders= filter.qs.order_by('-Date') """ Don't work Category_query = request.GET.get('Category') qs = Order.objects.filter(Category= Category_query) """ if request.GET.get('Export') == 'Export': response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="data.xlsx"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Data') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Date', 'Category', 'Item'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows=qs.values_list('Date', 'Category', 'Item') for row, rowdata in enumerate(rows): row_num += 1 for col, val in enumerate(rowdata): if isinstance(val,datetime.date): val = val.strftime('%d/%m/%Y') ws.write(row_num, col, val, font_style) wb.save(response) return response return render(request, 'template.html',{'orders':orders,'filter': filter}) template.html <form method="get"> {{filter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> <form method="GET" > <button class="btn btn-warning" type="submit" value="Export" name="Export"> Export</button> </form> -
POST requests do not go through Google Cloud Endpoints? (Django REST)
My iOS app makes POST requests to Google Cloud Run container which hosts my Django Rest Framework Project. To add a layer of security I've set up public ESP (Extensible Service Proxy - Cloud Endpoints) to serve as a gateway for private Cloud Run Container. Basically, ESP does authentication before routing the request to private Cloud Run container. Django urls All GET requests to ESP work fine: they successfully get routed to Cloud Run Container (for example when I request non existent /hello at www.mysite.com/hello, I get Django Debug 404) However, for some reason, POST requests are not routed by ESP (for example I'm trying to access existing /upload at www.mysite.com/upload I get standard 404) I've tried disabling csrf, setting APPEND_SLASH to false, nothing seems to work. All POST requests result in 404. Am I doing something wrong in Django? All testing done with Postman. All POST requests work fine if sent directly to Cloud Run Container -
How to use a single model 'employee' for storing employees and managers in django?
I am creating a ERP type system, where I have a django model(table) called 'employee'. I want every worker of a company to be an 'employee'. (ex. coder, boss, janitor, line manager etc. will all be 'employee') I also want some employees to have one or more line manager/s. And a line manager can have multiple employee under him/her. So the question is how to make line manager a part of 'employee' table, and have a field which describes 'employees' under line manager? So that I can display what line manager/s an employee has. Also display what line manager has which employees under him? Here's the models file: class Team(models.Model): name = models.CharField(max_length=64) t_id = models.CharField(max_length=64) def __str__(self): return self.name class Employee(models.Model): first_name=models.CharField(max_length=64) last_name=models.CharField(max_length=64) e_id=models.CharField(max_length=64) current_role=models.CharField(max_length=64) # "coder" past_roles=models.CharField(max_length=512) # "coder, developer, janator" (seperator: ,) teams = models.ManyToManyField(Team, related_name="employees", blank=True) joining_date = models.DateTimeField(null=True,blank=True) desk_location=models.CharField(max_length=64) #How do I go about this? line_manager = ??? def __str__(self): return self.first_name I am new to django, so please forgive me if I am missing something very simple. Also if there is a more elegant solution which requires me to add additional tables, I dont mind. Thanks -
Confusion over Multiple Database Configuration
I am trying to use multiple database where one DB is a default and the second DB is a :memory DB. From the description in the Docs (shown below), it sounds like the default routing should be fine. But it says that the objects are "sticky" to their original database. How is there an "Original" database? When I first started to implement this, I expected that there would be a META in the Model classes that would specify its database, but that does not seem to be the case. I see examples where people have a Mapping of Apps to DB, which would be perfect for my scenario, but then they turn around and write a Routing anyway. I don't want to have to always add the database to Save calls, as this would be prone to programming errors. Is there an official setting to map an App to a Database, or a Model to a Database? Or is it always required to write a Router to use multiple databases. # Is DATABASE_APPS_MAPPING just a name that some developer chose to use or is it a # real Django thing that would do what I want? DATABASE_APPS_MAPPING = {'app1': 'default', … -
Wagtailstreamforms TypeError from_db_value() missing 1 required positional argument: 'context'
I got this error when trying to use wagtailstreamforms. Built a from-scratch environment and reproduced the error. The only things I installed: Django==3.0.5 wagtail==2.8 wagtailstreamforms==3.9 In base.py added (as prescribed in docs): 'wagtail.contrib.modeladmin', 'wagtailstreamforms' Left everything else untouched (standard Wagtail base.py), migrated database. Home page 127.0.0.1:8000 gives Wagtail's welcome page as expected, admin is at 127.0.0.1:8000/admin/ with Streamforms item in menu on the left as expected. When I click on it, I can make a form and when I make the first field for the form and then save it, I get the error above. After that I cannot access the Streamforms section anymore, I immediately get the same error when I try. I looked through all posts on SO on wagtailstreamforms and many similar items on the internet, no solution. What am I doing wrong? Complete error log: Internal Server Error: /admin/wagtailstreamforms/form/ Traceback (most recent call last): File "/Users/paulsmits/Code/MyCompany/streamformserror/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/paulsmits/Code/MyCompany/streamformserror/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/paulsmits/Code/MyCompany/streamformserror/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/Users/paulsmits/Code/MyCompany/streamformserror/env/lib/python3.8/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/Users/paulsmits/Code/MyCompany/streamformserror/env/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/Users/paulsmits/Code/MyCompany/streamformserror/env/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render … -
Django admin Tabularinline helptext
It seems like to that django admin allows the display of helptext for a model field, but I can't get it to display. I have an admin interface that looks like class ModelA(): name=DecimalField(blehbleh, help_text='some help plz') desc=DecimalField(blehbleh, help_text='some other help') class ModelAInlineAdmin(admin.TabularInline): model = ModelA formset = ModelAFormSet class ModelAFormSet(forms.BaseInlineFormSet): def clean(self): super(ModelAFormSet, self).clean() # some validation stuff class SomeOtherAdmin(admin.ModelAdmin): inlines = [ModelAInlineAdmin] model = some_other_model The ModelA's inline shows up in SomeOtherAdmin, but I cannot make the help text (i.e. 'some help plz' and 'some other help') to show. Any help? -
why my django id field get the value of user field?
Im new in django. I want to make a script that can make fake data with faker enter link description here this is my model.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #additional blood_type = models.CharField(max_length=2,blank=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) description = models.TextField(blank=True) case =models.CharField(max_length=30,blank=True) def __str__(self): return self.user.username this is my fake data function fake_first_name is variabale that has fake name that faker generated and so on for other variables def populate(N=5): for entery in range(N): #making fake data fake_first_name = fakergen.first_name() fake_last_name = fakergen.last_name() fake_email = fakergen.email() fake_password = fakergen.password(length=10) fake_blood_type = random.choice(bloodType) fake_phone = fakergen.phone_number() fake_case = random.choice(Case) Create new User entery user = User.objects.get_or_create( username=fake_first_name, first_name=fake_first_name, last_name=fake_last_name, email=fake_email)[0] tempUser = User.objects.get(username=fake_first_name) tempUser.set_password(fake_password) tempUser.save() userprofile = UserProfile.objects.get_or_create( user=fake_first_name, blood_type=fake_blood_type, phone_number=fake_phone, case=fake_case, description='')[0] and i get this error: ValueError: Field 'id' expected a number but got 'Lisa' -
Django OperationaL Error: No such column found
I was running a django project , that was working fine. Then just for testing, I deleted the migrations folder inside my app. After that I recreated the folder manually with __init__.py file. I was trying to add new columns in my models.py file. But after running python manage.py makemigrations python manage.py migrate I got the unknown column exception. I don't know add to retrieve my old migration folder. If not possible how to sync the new manually created migration folder so that I can change my existing model. I'm struck between the middle of project. Can anyone help me out? -
how can i update an Image field in Django: I want to let the user (employee) change his/her personal_image
Header 1 models.py: class Employee(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.EmailField(max_length=254) phone_number = models.PositiveIntegerField(default=None) address = models.CharField(max_length=200) position = models.CharField(max_length=200) hire_date = models.DateField(auto_now_add=False) salary = models.PositiveIntegerField(default=1000) is_manager = models.BooleanField(default=False) personal_image = models.ImageField(blank=True, null=True, upload_to='images/') password = models.CharField(max_length=200) def __str__(self): return str(self.pk) + " " + self.first_name + " " + self.last_name Header 2 forms.py: class change_image(ModelForm): class Meta: model = Employee fields = ['personal_image'] exclude = ('email', 'first_name', 'last_name', ' phone_number', 'address', 'position', 'hire_date', 'salary', 'is_manager', 'password') Header 3 views.py: if request.method == 'POST': form_4 = change_image(request.POST or None,request.FILES or None) if form_4.is_valid(): change_4 = form_4.cleaned_data emp = Employee.objects.filter(id=x.id) emp.update(personal_image=request.FILES['personal_image']) return redirect('/main') Header 4 settings.py: MEDIA_URL = '/images/'MEDIA_ROOT = os.path.join(BASE_DIR, 'employees/') Header 6 URLS.py: urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) Header 7 HTML code: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group" style="width:500px;"> <label>Upload a new suitable profile picture showing at least your face.</label> {{form_4}} </div> <button type="submit" class="btn btn-primary">Upload</button> </form> what should I do to solve this issue, I'm able to change it but when I click on it from the database, it says that the image doesn't exist -
Using a intermediary table with extra data and showing extra data in the form
I am building a database app for my company the produces office equipment hardware. I would like to be able to store the models we sell as well as the options that go on each model. (for clarity I will refer to the models we sell as product models as to not confuse the Django model with our model) Here are the requirements: Each product model can have many options Each option can go on many product models Each option may be standard on some product models and optional on others I would like to store all of this data which is not really a problem. I have done this as shown below: models.py: class ProductModel(models.Model): modelID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) model_number = models.CharField(max_length=25, editable=True, unique=True) slug = models.SlugField(null=False, unique=True) model_description = models.TextField(max_length=5000, editable=True) family_id = models.ForeignKey(ProductFamily, on_delete=models.DO_NOTHING, editable=True, null=False, blank=False) #relates to the family of the product model class Option(models.Model): option_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) option_model_number = models.CharField(max_length=50, verbose_name='model number', editable=True, unique=True) slug = models.SlugField(null=False, unique=True) option_description = models.TextField(max_length=500, editable=True, help_text='A description of what the function of the option') model_id = models.ManyToManyField(ProductModel, through='OptionBelongsToModel') class OptionBelongsToModel(models.Model): product_model = models.ForeignKey(ProductModel, on_delete=models.DO_NOTHING) product_option = models.ForeignKey(Option, on_delete=models.DO_NOTHING) is_standard = models.BooleanField() #defines if this … -
X-Accel-Redirect Nginx configuration not working
I'm now deploying django projects on CentOS and have a problem with X-Accel-Redirect for protected file serving. Here is my nginx.conf server { listen 80; server_name example; index index.html index.htm index.php; root /www/server/example; charset UTF-8; access_log /var/log/nginx/myproject_access.log; error_log /var/log/nginx/myproject_error.log; client_max_body_size 75M; location /public/ { root /www/wwwroot/myproject/; } location /media/ { root /www/wwwroot/myproject/; internal; } location / { include uwsgi_params; uwsgi_pass django; } ... } Of course, protected files are on /www/wwwroot/myproject/media. And corresponding python view file is following. class ProtectedView(generics.GenericAPIView): permission_classes = [IsAuthenticated] def get(self, request, id, target): file_name = "1.png" response = HttpResponse() response["X-Accel-Redirect"] = "/media/{0}".format(file_name) response["Content-Disposition"] = "attachment; filename={0}".format(file_name) return response But server returns 404 error. And the myproject_error.log is like this. [error] 24570#0: *5 open() "/www/server/example/media/1.png" failed (2: No such file or directory), client: 174.11.13.81, server: example, request: "GET /protected-view/ HTTP/1.1", upstream: "uwsgi://0.0.0.0:8008", host: "40.1.12.23" Maybe location /media/ {} block is not working. What problem? I have changed the permission but not working. PS: I'm using django rest framework. -
X has no attribute 'object' - Django
I am following a tutorial about how to build a social network in Django. I have built this view: class JoinGroup(LoginRequiredMixin, generic.RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse("groups:single",kwargs={"slug": self.kwargs.get("slug")}) def get(self, request, *args, **kwargs): group = get_object_or_404(Group,slug=self.kwargs.get("slug")) try: GroupMember.object.create(user=self.request.user,group=group) except IntegrityError: messages.warning(self.request,("Warning, already a member of {}".format(group.name))) else: messages.success(self.request,"You are now a member of the {} group.".format(group.name)) return super().get(request, *args, **kwargs) But when I try to access its url, I get (from console): my_path\simplesocial\groups\views.py", line 40, in get GroupMember.object.create(user=self.request.user, group=group) AttributeError: type object 'GroupMember' has no attribute 'object' What's the problem? -
Django two databases for two apps in one project. Haw to make migration correctly?
I wanna use 'db1' for app 'app1', and 'db2' for 'app2'. (I don`t need any synhronization between ths applications and databases. They independent but lay in one 'mysite' django project.) I have migration for 'db1' in 'app1'. /app1/migrations/0001_initial.py. It contain classes for 'db1' ('default') structure. Now - I appended database 'db2' to settings.py DATABASES dict. 'app1' use 'default' database. (db1 is 'default') - I made $startapp 'app2' folder - I put 'app2.apps.App2Config' to INSTALLED_APPS list - I executed $makemigrations app2 app2/migrations/ folder is empty (only init.py where) Any makemigrations exectuions now write: No changes detected in app 'app2' I running $migrate --datbase=db2 It writing: Operations to perform: Apply all migrations: admin, auth, contenttypes, db1, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK .... .... Applying db1.0001_initial... OK And nothing is changing. No any mention about 'db2', no migrations upgrade as i see, the app2/migrations folder is empty yet. What i have to do for make models for 'db2' and use it in 'app2' code? Thanks -
Force Django User To Pick A Username After Verifying Their Email And Logging In For The First Time
I'm looking for ideas on the most elegant way to force a user to define a username immediately after they verify their email and log in for the first time. Alternatively, they click the verification email, are not logged in, and must enter a username first to be able to log in for the first time. My requirements are that the username not be in the registration form, but instead be on its own template page immediately after the user logs in for the first time. Once they define a username, they would not see this page again. I'm using class-based views so I think that rules out decorators. I've researched: User-level Permissions (can't view any page until you provide a username) Using the is_active boolean (user is not considered active until they provide a username) PermissionRequiredMixin (add to every class that a logged-in user could potentially see) UserPassesTestMixin (add to every class that a logged-in user could potentially see) AccessMixin (add to every class that a logged-in user could potentially see) Add my own boolean field to my custom User model In every view, check if username is null, if it is, redirect to username form page (doesn't seem … -
Add help_text to UserCreationForm
I'm using UserCreationForm in Django and I'm trying add help_text to the email field. Here's the forms.py code: from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = get_user_model() fields = ('email','username',) help_texts = { 'email': 'Use your work email', } I'm using Crispy Forms to render it and it isn't rendering the help_text. As another approach, I tried adding this to the class: def __init__(self, *args, **kwargs): super(CustomUserCreationForm, self).__init__(*args, **kwargs) self.fields['email'].help_text = 'hello' But it didn't work either. What am I missing? -
How to add custom class and id to UserCreationForm fields?
So,I have fields from the default UserCreationForm. Now, I want to add bootstrap class and id to those fields. How do I do this? I don't wanna install third-party packages(yet).My code -
Django 'dict' object has no attribute 'META' error when using an API
I am trying to get some data from an API but have been getting the error 'dict' object has no attribute 'META' when I try to print it. I am using Requests module for this. Here is the code: url = "https://coronavirus-map.p.rapidapi.com/v1/summary/region" querystring = {"region":"Bangladesh"} headers = { 'x-rapidapi-host': "coronavirus-map.p.rapidapi.com", 'x-rapidapi-key': "leaving this out :P" } request = requests.get(url, headers=headers, params=querystring).json() print(request.text) Everything works on Postman. Can anyone help? -
How to get html form input and save as variable in Python Django
I'm trying to get a simple input(which would be an integer) from the user, and use it as a variable in the next python function. But whenever I try to print the input it prints out "None". Here's my code HTML <form action="/./" method="POST">{% csrf_token %} <input type="text" name="quantity" placeholder="Repeat" size=2> <input type="submit" value="Save!"> </form> Python Django (This is just part of the function.) def saveCriteria(request): title = request.POST.get('quantity') context = {} print(title) return render(request, "home.html", context) Any help or advice would be greatly appreciated! -
How to display category list at django template
I want to display list of category at main(base) page. (mysite is here. http://jgahn.pythonanywhere.com/) When I click the 'Chemistry' category, It took me post list with 'Chemistry' category and display list of category(right side, sky-blue color, chemistry and physics). This is my problem, category list is displayed only when I access some category. I want to display always without any access at category (like sidebar). Here is my view.py from .models import Post, Comment, Category def list_of_post_by_category(request, category_slug): categories = Category.objects.all() posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') if category_slug: category = get_object_or_404(Category, slug=category_slug) posts = posts.filter(category=category) template = 'myblog/list_of_post_by_category.html' context = {'categories': categories, 'posts': posts, 'category': category,} return render(request, template, context) This is my main_page.html <p class="taglist"><a href="{% url 'list_of_post_by_category' category.slug %}">{{ category }}</a></p> {% endfor %} list_of_post_by_category.html {% extends 'myblog/main_page.html' %} {% block content %} <h4><span style="color: #ab4a67; font-weight: bold;">{{category.name}}</span> category</h4> <hr> <!--<button class="btn-tag">{{ category.name }}</button>--> {% for post in posts %} <div class="list"> <h6><a href="{% url 'post_detail' pk=post.pk %}" style="text-decoration:none;"> &gt; &nbsp; {{ post.title }}</a> &nbsp; &nbsp; <span class="small">{{ post.published_date|date }} {% if user.is_superuser %} {% if post.comments.count >= 1 %} &nbsp; {{ post.comments.count }} Comments {% endif %} {% endif %} &nbsp; <button class="btn-tag">{{ tag }}</button> </span> </h6> </div> {% …