Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
access foreign key via a manytomany relationship in django
I have a foreign key that is in turn a many to many relation like the following: Persons<-M2M->Role(ManyToOne)->Name The model: class Person(models.Model): mail=models.EmailField() firstName=models.CharField(max_length=200) lastName=models.CharField(max_length=200) phoneNumber=PhoneNumberField() streetAdress=models.CharField(max_length=200) zipcode=models.CharField(max_length=200) city=models.CharField(max_length=200,default="Göteborg") country=models.CharField(max_length=200,default="Sweden") def __str__(self): return "%s %s" % (self.firstName,self.lastName) class Meta: ordering = ('firstName','lastName') class Role(models.Model): role=models.CharField(max_length=200) person=models.ManyToManyField(Person) def __str__(self): return self.role class Meta: ordering = ('role',) class Name(models.Model): name=models.CharField(max_length=200) role=models.ForeignKey(Role,on_delete=models.CASCADE) def __str__(self): return self.name class Meta: ordering = ('name',) class Address(models.Model): I can acces the manyTomany field from persons and roles but I cannot access names. the template: {% extends "artdb/base.html" %} {% block content1 %} <ul> {% for p in ans %} <h5>First name: {{p.firstName}}</h5> <h5>Last name: {{p.lastName}}</h5> <h5>Phone: {{p.phoneNumber}}</h5> <h5>Adress: {{p.streetAdress}}</h5> <h5>Zip Code: {{p.zipcode}}</h5> <h5>City: {{p.city}}</h5> <hr> {% endfor %} </ul> {% endblock content1 %} {% block content2 %} <ul> {% for p in ans %} {% for r in p.role_set.all %} <h5>{{ r.role }}</h5> {% endfor %} {% endfor %} <hr> </ul> {% endblock content2 %} {% block content3 %} <ul> {% for p in ans %} {% for r in p.role_set.all %} <h5>{{ r.name }}</h5> {% endfor %} {% endfor %} <hr> </ul> {% endblock content3 % I konow that I have to iterate to get manyTomany, … -
DJANGO - User not staying logged in through redirect
I am creating user accounts that sends them a link to their email that they can access to set their password and then login. I am doing this by creating an model that stores a uuid4 token for each created user. # models class ActivationToken(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) used = models.BooleanField(default=False) token = models.CharField(max_length=100, default=uuid4, unique=True) # view creating the user def createUser(): ... token = ActivationToken.objects.create(user=user) current_site = get_current_site(request) subject = 'Activate Your Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'token': token.token, }) user.email_user(subject, message) ... # view to set the users password def activate(request, token): try: access_token = ActivationToken.objects.get(token=token) except ActivationToken.DoesNotExist: return redirect('home') user = User.objects.get(pk=access_token.user.id) login(request, user) if request.method == 'POST': form = SetPasswordForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) user.need_password_change = False user.save() access_token.delete() return redirect('profile') else: form = SetPasswordForm(request.user) return render(request, 'users/setpasswordteacher.html', {'form': form}) When the user is redirected to profile view, they do not remain logged in and get redirect to the login page due to the login_required tag. Is there anything I can implement to make sure that they stay logged in through the redirect. Also: Is the token method that I have create a secure way of … -
How to get items from django user foreign key
How do I retrieve items from django foreign keys attached to a user account? class product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_title = models.CharField(max_length=100, blank=True) product_price = models.CharField(max_length=30, blank=True) product_image = models.CharField(max_length=100, blank=True) I looked into some other stack overflow question and tried request.user.product.product_title but that just returns an Attribute error,'User' object has no attribute 'product'. I also tried request.user.product_set.all() but that just returns this queryset: <QuerySet [<product: product object (2)>, <product: product object (3)>, <product: product object (4)>]> I tried some other things too but I can't remember what exactly and what error those threw. -
Django signals - kwargs['update_fields'] is always None on model update via django admin
I have a signal inside my django app where I would like to check if a certain field in my model has been updated, so I can then proceed and do something. My model looks like this... class Product(models.Model): name = models.CharField(max_length=100) price = models.PositiveIntegerField() tax_rate = models.PositiveIntegerField() display_price = models.PositiveInteger() My signal looks like this... @receiver(post_save, sender=Product) def update_model(sender, **kwargs): instance = kwargs['instance'] if 'tax_rate' in kwargs['update_fields']: # do something This returns the error None is not an iterable. I have read the django signal documentation regarding the update_fields and it says The set of fields to update as passed to Model.save(), or None if update_fields wasn’t passed to save(). I should mention that I am working inside django admin here so what I hoped would happen is, I could create an instance of my Product model in django admin and then later if the value of tax_rate or price were updated, I could check for those and update the list_price accordingly. However, kwargs['update_fields'] always returns None. What am I getting wrong? Or is there some other way I could achieve that result? -
django distinct queryset from queryset-values
I have a User that can have multiple Accounts. There can be multiple Units on each Account. I build a filter dictionary and get relevant units: units = Unit.objects.filter(**unit_filter) However, I would also like to get distinct users. I can easily get their ids: user_dicts = units.values('account__user').distinct() or to be more exact: user_ids = [rec.get('account__user') for rec in units.values('account__user').distinct()] So then I can filter Users using User.objects.filter(id__in=user_ids). (I can also use the generator expression instead of list comprehension, but that is not the point.) I am not sure but evaluating id in seems to me not very efficient. Is there a better way how to get unique users from filtered units? -
Django create object - use default value for None
So I have a Django model which has few non nullable field with default values. class Article(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, editable=False) code = models.CharField(max_length=200, default=uuid4, unique=True, null=False) company = models.CharField(max_length=200, default=uuid4, unique=True, null=False) Now i want to do a Article.objects.get_or_create(company=company, code=am_row['Article code']) But here the issue is am_row['Article code'] or company can be a None, and in that case i just want a new model to be created using that fields default values. How can i achieve this? -
Trying to use OneToOneField and get error on 'migrate'
I'm setting my model to work like a user table, like in asbtract way, with OneToOneField. It's for simple coding, like check username/password and login(Without register). I already tried, OneToOneField, AbstractBaseUser, AbstractUser and ForeingKey in a User model OneToOneFielded. For the second and the third... now i don't have knowlage for coding with them. For the first and the last, they are so close to work perfect, unless for minimal errors i don't know how solve and use the commands 100% correctly. Where it's commented, it's me trying to make another model and use ForeingKey in class Pessoa(Person) and use OneToOneField in class Usuario(User), but i can't make it work anyway. models.py #Here i am trying to make this in another way #class Usuario(models.Model): # user = models.OneToOneField(User, on_delete=models.CASCADE, db_column='cnpj') # password = models.CharField(max_length=40, blank=True, null=True, db_column='senha') class Pessoa(models.Model): id_pessoa = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) cnpj = models.CharField(max_length=14) nome = models.CharField(max_length=70) email = models.CharField(max_length=100, blank=True, null=True) senha = models.CharField(max_length=40, blank=True, null=True) ativo = models.BooleanField(blank=True, null=True) datacadastro = models.DateField(blank=True, null=True) cidade = models.CharField(max_length=50, blank=True, null=True) uf = models.CharField(max_length=2, blank=True, null=True) class Meta: managed = False db_table = 'pessoa' def __str__(self): return self.nome forms.py class PessoaForm(ModelForm): cnpj = forms.CharField(widget=forms.TextInput(attrs={ 'class': "form-control … -
Dj-stripe conflicts with multipe development severs
My team are developing a payment system for our web services. The site is built using Django, with the payment services provided by stripe. We are using dj-stripe to integrate the two. For development we are using the stripe test environment, but we are doing this on multiple development servers, each with it's own dev DB. dj-stripe identifies which customer to associate payment, card and source activity with using the dj-stripe customer id. This causes a conflict in the information for customers with the same ids on different development severs. We have thought of a number of workarounds for this, the top two choices are; 1) Generate an offset in the customer ids to prevent clash. The issue is this may break down as time goes on, with more developers joining. It fixes the issue for now, but doesn't guarantee it won't be an issue again. 2) Create a stripe account for each developer to ensure no clashes and only use the test environment. However, this seems like something stripe wouldn't be happy with if we end up with many devs working on the project. I am interested in whether there is a standard solution or best practices for this … -
Django: password reset link in email gives 'site can't be reached' error
I'm trying to set up password reset in Django using sendgrid smtp. The password reset page where you enter your email works well and the email is sent, however, I cannot get the link in the email to redirect to the password reset form. When I click it within my email it goes to a 'this site can't be reached' page. I'm not sure what I'm doing wrong. I've tried to change the 'sites' and the side_id. urls.py: from django.urls import path, include from users import views from django.conf import settings from django.conf.urls.static import static from users.forms import LoginForm from django.contrib import admin from django.contrib.auth import views as auth_views from booking.views import BookingView, BookingUpdateView urlpatterns = [ path('', include('django.contrib.auth.urls')), path('signup/', views.SignUp.as_view(), name='signup'), path('login/', auth_views.LoginView.as_view(), {'authentication_form': LoginForm}, name='login'), path('profile/', views.view_profile, name='profile'), path('profile/<int:pk>/', views.view_profile, name='profile_with_pk'), path('profile/edit/', views.EditProfileView, name='edit_profile'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) templates/registration/password_reset_form.html: {% extends 'layout.html' %} {% load static %} {% load widget_tweaks %} {% block title %}Forgot Your Password?{% endblock %} {% block content %} <div class="container-fluid booking"> <div class="container password_reset_text"> <h3 class="password_text">Forgot your password?</h3> <p class="password_text">Enter your email address below, and we'll email instructions for setting a new one.</p> </div> <div class="container"> <form class="password_text" method="post"> {% csrf_token %} <div … -
NameError: name 'cache' is not defined
I wanna make a random url, when the user validates the form he is redirected to the new url page with specific random url. The url looks like: localhost/pagewizard/ I use django 2.1 Views.py class Project(LoginRequiredMixin, CreateView): model = newproject template_name = '/create.html' def form_valid(self, form): form.instance.auteur = self.request.user some_key = "01234AZERTVC" cache.set(some_key, True, 5) return HttpResponseRedirect(reverse('dash-wizard', args=(some_key,))) class FormWizard(LoginRequiredMixin ,SessionWizardView): template_name = "wizard.html" form_list = [form1, form2] def done(self, form_list, **kwargs): return render(self.request, '/done.html', { 'form_data': [form.cleaned_data for form in form_list], }) def get(self, request, *args, **kwargs): try: return self.render(self.get_form()) except KeyError: return super().get(request, *args, **kwargs) url.py urlpatterns = [ path('page1/page2/', Project.as_view(), name='dash-create'), path('pagewizard/<slug:title>/', views.FormWizard.as_view(), name='dash-wizard'), ] The error displayed is : Exception name 'cache' is not defined -
Django multiple views one model
i try to create something like subpages in User profile. I try to create this because i think put everything(activity stream, user photos, wideo etc.) in one page it's not good idea. I have multiple views with one model like: def userprofile(request, username): user = User.objects.get(username=username) context = locals() template = 'auth/user_detail.html' feeds = feed_manager.get_user_feed(user.id) activities = feeds.get('user')['results'] activities = enricher.enrich_activities(activities) user_from = len(Follow.objects.filter(user_from=user)) target = len(Follow.objects.filter(target=user)) current_user_following = Follow.objects.filter(user_from=request.user, target=user) args = {"user": user, "target": target, "current_user_following": current_user_following, "activities": activities} return render(request, template, args) def userabout(request, username): user = User.objects.get(username=username) return render(request, 'auth/about.html', {'user': user}) def userphotos(request, username): user = User.objects.get(username=username) return render(request, 'auth/photos.html', {'user': user}) and on urls: path('users/<username>/', views.userprofile, name='userdetail'), path('users/<username>/about/', views.userabout, name='userabout'), path('users/<username>/photos/', views.userphotos, name='userphotos'), path('users/<username>/video/', views.uservideo, name='userphotos'), When I type this link with username like: localhost:8000/account/users/Maciej/about/ then this works good. But i don't know how to link this in template. I try <a href="{% url 'userabout' %}">About me</a> and then error apear "No reversMatch". Im begginer, maybe there is a better option to do this? Or to link this. -
Django exclude filter on related name field
I am trying to filter a query set based upon a nested contains on multiple fields. One field works but the other doesn't Here is a short version of my model: class Shift(models.Model): users = models.ManyToManyField(User, blank=True) potential_users = models.ManyToManyField(User, blank=True, related_name='potential_users') I want to filter it so that a user is NOT in users and NOT in potential users attribute. I use this exclude function on the queryset: queryset = Shift.objects.exclude(users__id__contains=self.request.user.id, potential_users__id__contains=self.request.user.id) When the user is in the users attribute of a shift I don't get any shifts which is expected. BUT when a user is in the potential user attribute I do get the shift. In potential users When the user is in potential_users. I run this in my debug executor after the queryset is made: self.request.user.id == queryset[0].potential_users.all()[0].id I get True which should be impossible since it is in the exclude. I suspect it has something to do with both of the attributes referring to the same foreign key model In users When I do the same filtering with the user in the users attribute I get a index out of range which is good because it means it did not retrieve the shift. Which is expected. … -
How to pin pipenv requirements with brackets?
I just did: pipenv install django[argon2] And this changed my Pipfile: -django = "==2.1.5" +django = {extras = ["argon2"],version = "*"} I want to pin the requirements. First I will pin django to 2.1.5: django = {extras = ["argon2"],version = "==2.1.5"} What about argon2? Is that a separate package? There is no such package when I do pip freeze: $ pip freeze | grep -i argon2 argon2-cffi==19.1.0 What is that? How do I fully pin django[argon2]? -
Can't create and active Virtualenv in windows 10 , python 37
I am new in Python and to be coder :) I am trying to create and active virtualenv, searching for days to fix this problem but I couldn't, can you help me pls.. Thank you. Let me show you my administrator: C:\Users\Büşra\Desktop\Django-Virtualenv>virtualenv myenv Using base prefix 'c:\users\büşra\appdata\local\programs\python\python37' New python executable in C:\Users\Büşra\Desktop\Django-Virtualenv\myenv\Scripts\python.exe Complete output from command C:\Users\Büşra\Deskt...v\Scripts\python.exe -m pip config list: Could not import runpy module ModuleNotFoundError: No module named 'runpy' Traceback (most recent call last): File "c:\users\büşra\appdata\local\programs\python\python37\lib\runpy.py", line 193, in _run_module_as_main "main", mod_spec) File "c:\users\büşra\appdata\local\programs\python\python37\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Büşra\AppData\Local\Programs\Python\Python37\Scripts\virtualenv.exe__main__.py", line 9, in File "c:\users\büşra\appdata\local\programs\python\python37\lib\site-packages\virtualenv.py", line 793, in main symlink=options.symlink, File "c:\users\büşra\appdata\local\programs\python\python37\lib\site-packages\virtualenv.py", line 1087, in create_environment install_wheel(to_install, py_executable, search_dirs, download=download) File "c:\users\büşra\appdata\local\programs\python\python37\lib\site-packages\virtualenv.py", line 935, in install_wheel _install_wheel_with_search_dir(download, project_names, py_executable, search_dirs) File "c:\users\büşra\appdata\local\programs\python\python37\lib\site-packages\virtualenv.py", line 964, in _install_wheel_with_search_dir config = _pip_config(py_executable, python_path) File "c:\users\büşra\appdata\local\programs\python\python37\lib\site-packages\virtualenv.py", line 1038, in _pip_config remove_from_env=["PIP_VERBOSE", "PIP_QUIET"], File "c:\users\büşra\appdata\local\programs\python\python37\lib\site-packages\virtualenv.py", line 886, in call_subprocess raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode)) OSError: Command C:\Users\Büşra\Deskt...v\Scripts\python.exe -m pip config list failed with error code 1 -
No such file or directory: saleor/static/assets
Want to host my Saleor web app on DigitalOcean, and after the whole installation proces and setting up everything, when i want to colectstatic, im getting this error : FileNotFoundError: [Errno 2] No such file or directory: '/home/saleordeploy/saleor_project/saleorecommerce/saleor/static/assets' __________________________________________________________________________ This is my settings.py STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = os.environ.get('STATIC_URL', '/static/') STATICFILES_DIRS = [ ('assets', os.path.join(PROJECT_ROOT, 'saleor', 'static', 'assets')), ('favicons', os.path.join(PROJECT_ROOT, 'saleor', 'static','favicons')), ('images', os.path.join(PROJECT_ROOT, 'saleor', 'static', 'images')), ('dashboard/images', os.path.join( PROJECT_ROOT, 'saleor', 'static', 'dashboard', 'images'))] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder'] Does anyone know how to fix this? Thanks -
Getting user id returned with JWT
Good morning, I am writing my first DRF API and am using django-rest-framework-jwt (https://getblimp.github.io/django-rest-framework-jwt/) to handle JWT auth. I am using the built in views currently: from rest_framework_jwt.views import obtain_jwt_token from rest_framework_jwt.views import refresh_jwt_token urlpatterns = [ path('auth/obtain_token/', obtain_jwt_token), path('auth/refresh_token/', refresh_jwt_token), but need to return some user information back to the UI (VueJS). I would like to store the user ID and name information into the Vuex store to pass into subsequent API calls and to present to the user ("Hello Jim!"). I found this which discussing adding a custom function for jwt payload response: jwt rest framework returning user id with token I am not sure WHERE to do this though... Thanks for your help in clarifying. BCBB -
Django window function with aggregation function on the same annotate
I am trying to use Django aggregation function SUM in an annotate along with Django window functions. The problem is that when I try to use the aggregation function on the same model field as used in previous annotate alias, then Django throws window functions are not allowed in GROUP BY error. I am providing the query below. queryset = UserEcosystemApplicationUsage.objects.filter( user_app__user=child, from_datetime__gte=from_datetime, to_datetime__lte=to_datetime ).annotate( day_duration_seconds=Epoch(Window( expression=Sum('duration_time'), partition_by=[F('name'), F('date')] )), period_duration_seconds=Epoch(Window( expression=Sum('duration_time'), partition_by=[F('name')], )), # duration_total_seconds=Epoch(Window( # expression=Sum('duration_time') # )), duration_total_seconds=Sum('duration_time') ).values( 'duration_total_seconds' ).distinct() Right now, when commented out part of query is used instead of Sum(duration_time) then everything is OK but I would expect to Sum('duration_time') to work as well. Could you pinpoint what I am doing wrong or present links to docs that explains what is going on? -
Return the first image from the model using the tag '{{value | first}}'
I have a list of photos from which I would like to always be the first to add as a profile photo. I found the following '|first' tag in the django documentation, but I have problems to add it in my situation, every time I try to do it in this way, '{{ image_list|first.photo.url }}' i receives nothing. Any help will be appreciated. My models.py class Image(models.Model): photo = models.ImageField() added_at = models.DateTimeField(auto_now_add=True) masseurs = models.ForeignKey(Masseurs, on_delete=models.CASCADE) views.py masseur = get_object_or_404(Masseurs, pk=masseurs_id) image_list = Image.objects.filter(masseurs_id = masseurs_id) return render(request, 'masseur/masseur_detail.html', {'image_list':image_list}) -
Declaring Instant of class in view Django
I have the following models in my models.py class Grade(models.Model): grade = models.IntegerField() class Student(models.Model): name = models.CharField(max_length=255) grade = models.ForeignKey(Grade) rollno = models.BigIntegerField() I want to do the post method in the view.py for the class Student. When it is without the foreign key it is very simple as below; class RegisterStudent(generics.ListAPIView): ''' GET student/ POST student/ ''' queryset = Student.objects.all() serializer_class = StudentSerializer def post(self, request, *args, **kwargs): a_site = Student.objects.create( name=request.data["name"], grade=request.data["grade"], rollno=request.data["rollno"], ) return Response( data=StudentSerializer(a_site).data, status=status.HTTP_201_CREATED ) But when I use the foreignkey method, I am not sure how to do it for grade in student. And this is how I am doing for grade: class RegisterGrade(generics.ListAPIView): ''' GET grade/ POST grade/ ''' queryset = Grade.objects.all() serializer_class = GradeSerializer def post(self, request, *args, **kwargs): a_site = Grade.objects.create( grade=request.data["grade"], ) return Response( data=GradeSerializer(a_site).data, status=status.HTTP_201_CREATED ) Any help will be appreciated. Thanks -
Push database into Django
I'm currently working on a project with Django, I have designed a model like Class Item(models.Model): id name ... And I've already had a sqlite database with data like Id, name, ... 1, a, ... 2, b, ... Now, the question is how I can push this database to django? Thanks -
Is there a way to always order a table by a specific column in django-tables2?
I'm using django-tables2 to render a table of MyModel. MyModel has a few different categories specified by its category field. I want to be able to overwrite order_by such that the table's primary ordering is always category and anything else selected is just a secondary ordering. Any suggestions on how I might do this? -
Google maps API issue with version 3.35 in a django form field widget
I am having a problem with the Google maps API, after upgrading it to version 3.35. The goal is to display the map in a form so that the user can define the geolocation. I am using Django 1.11.12 and CanJS 2.0.2. Here is the code (reduced for simplicity) which works fine with the Google maps API version 3.34, but not with the version 3.35. models.py from django.db import models from maps.models import JSONField class Institution(models.Model): geolocation = JSONField(blank=True, null=True) maps/models.py from django.db import models from maps.forms import LatLngWidget class JSONField(models.TextField): def formfield(self, **kwargs): kwargs.update({'widget': LatLngWidget()}) return super(JSONField, self).formfield(**kwargs) maps/forms.py from django import forms from django.conf import settings from django.contrib.staticfiles.templatetags.staticfiles import static from django.utils.safestring import mark_safe from django.template.loader import render_to_string from django.forms.widgets import Widget class LatLngWidget(Widget): def __init__(self, attrs=None): super(LatLngWidget, self).__init__(attrs) self.width = 640 self.height = 480 def render(self, name, value, attrs=None): data = dict(name=name, value=value, width=self.width, height=self.height) html = render_to_string("maps/widget.html", data) return mark_safe(html) def _media(self): return forms.Media(css={"all": [static("maps/css/gmap.css"),],},) media = property(_media) widget.html <div class="map-container" id="geolocation-container"> <div class="map-box"> <div class="map map-canvas" id="gmap-geolocation"></div> </div> </div> <script src="https://maps.googleapis.com/maps/api/js?v=3.35&key=xxx"></script> <script type="text/javascript"> Map = can.Control({ init: function(el, options) { this.map = null; this.marker = null; this.name = options.name; this.lat = options.lat || 0; this.lng … -
TypeError for DateField - Django XLWT Library
I am using xlwt library to export data in excel format. When i am adding company_created in value_list of my queryset i am getting error - TypeError at /company/csv/ can't subtract offset-naive andoffset-aware datetimes company_created is a DateField in Model. import xlwt from django.http import HttpResponse from django.contrib.auth.models import User def GenerateCompanyCSV(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="users.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Users') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Company Name', 'Company Email', 'Count of people','Created Date', 'Current Monthly Payment', 'Is TABopts Customer', 'Status', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Company.objects.exclude(id=1).exclude( company_is_deleted=True ).annotate( number_of_company_users=Count('userprofile') ).values_list( 'company_name', 'company_email', 'number_of_company_users', 'company_created', 'company_monthly_payment', 'company_tab_opts', 'company_status', ) for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response -
Issue with redirecting to various blog posts on click in django
I'm trying to create a simple blog which shows various articles on the homepage. The index page as of now holds the title and sub-title of various articles. I want it to display the entire content of the article on click. This is the error that I'm running into on the homepage. NoReverseMatch at / Reverse for 'article' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<article_id>[0-9]+)$'] This is the content of urls.py in the pages app that I've created. from django.urls import path from . import views urlpatterns=[ path('',views.index,name='index'), path('<int:article_id>',views.article,name='article'), path('about',views.about,name='about'), ] This is my views.py from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse from . models import Post # Create your views here. def index(request): post=Post.objects.all() context = { 'post' : post } return render(request,'pages/index.html',context) def article(request,article_id): article=get_object_or_404(Post,pk=article_id) context = { 'article' : article } return render(request,'pages/article.html',context) def about(request): return render(request,'pages/about.html') As you can probably see, I'm referring to the content of the articles through an article_id and the data regarding the particular post is fetched from the database. This is my index.html, which should redirect to the content of the specific post on click. {%extends 'base.html'%} {%load static%} {%block content%} <!-- Page Header --> <header class="masthead" style="background-image: … -
How to implement a click-through function without reloading the page
the site has a button, it is necessary that when you click on it the counter in the database increased. I solved this problem by going to the url with the function, but do not know how to call it without reloading the page. def add_show_phone(request, product_id): entry = Entry.objects.get(id=product_id) entry.count_show_phone += 1 entry.save() return HttpResponseRedirect('/product/' + product_id) Everywhere is only described as "how to send an AJAX form" or send data, but I'm sure there Must be a better method to solve this simple problem.