Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django site preview not updating after model.py change
I am learning django and I am working on models. I created a Product class from django.db import models class Product(models.Model): title = models.CharField(max_length=10) description = models.TextField(blank=False) price = models.DecimalField(max_digits=10, decimal_places=2) featured = models.BooleanField(default=False) int = models.IntegerField(default=10) and I am trying to delete the 'int' field but the django site does not update after the chanage. After deleting a model field(the 'int' field, see the screenshots), and running python manage.py makemigrations python manage.py migrate the live preview does not update and throws an error regarding the erased field. after closing the server and restarting the server(ctrl + c and than python manage.py runserver the page updates and does not throw any errors I am using sqlite. I tried deleting 'pycache' and all the migrations also db.sql3, recreating the superuser but after removing any field I still get the same error. picture 1 -> initial state $ https://ibb.co/Yb6pmgr picture 2 -> after removing 'int' field https://ibb.co/xf1bJQJ picture 3 -> error : $ https://ibb.co/0cPyRZv -
How to run a mysql stored procedure in django with two output parameters when data is received through REST API?
I am working on a django project where I have to use a stored procedure to update multiple tables and it gives two output parameters. There are four input parameters which comes from REST api. The procedure runs properly in phpmyadmin/MySql. In a pure python script it doesn't update the required tables but gives the output properly. In django I am not able to run the procedure. I just want to know how to set the output parameters properly and execute the procedure in django. I have tried it in a seperate python script but it only gives the output parameters and doesn't update the tables. In djando I tried to edit the views.py. pure python script: import mysql.connector from mysql.connector import Error from mysql.connector import errorcode var1 = " " var2 = " " try: mySQL_conn = mysql.connector.connect(host='192.111.11.111', database='Safemode', user='root', password='password here') cursor = mySQL_conn.cursor() x = cursor.callproc('ProcessIOTData',[1,2,"3","2019-06- 21T11:56:33Z",var1,var2]) for result in cursor.stored_results(): print(result.fetchall()) for output in x: print(x) except mysql.connector.Error as error: print("Failed to execute stored procedure: {}".format(error)) finally: if (mySQL_conn.is_connected()): cursor.close() mySQL_conn.close() print("connection is closed") IN Django(views.py). I have also not saved the data from the api as that will also be done the procedure: . . … -
django logging is not coming to log file
django logging configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'debug.log', }, }, 'loggers': { 'django': { }, 'setting':{ 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } error in debug.log: Watching for file changes with StatReloader Waiting for apps ready_event. Apps ready_event triggered. Sending autoreload_started signal. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/django/contrib/admin/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/django/contrib/sessions/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/django/contrib/messages/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/django/contrib/auth/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/django/contrib/contenttypes/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/django/contrib/staticfiles/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/rest_framework/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/user/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/corsheaders/locale with glob **/*.mo. (0.001) QUERY = 'SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"' - PARAMS = (); args=() Watching for file changes with StatReloader Waiting for apps ready_event. Apps ready_event triggered. Sending autoreload_started signal. error i am expecting: File "/home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/pymongo/database.py", line 552, in collection_names ReadPreference.PRIMARY) as (sock_info, slave_okay): File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/pymongo/mongo_client.py", line 904, in _socket_for_reads with self._get_socket(read_preference) as sock_info: File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/pymongo/mongo_client.py", line 868, in _get_socket server = self._get_topology().select_server(selector) File "/home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/pymongo/topology.py", line 214, in select_server … -
Is there any way to store ssh session object that is generated through paramiko?
I Have connected to my remote server using ssh paramiko library.Once after connected to my server i needed to perform many operations like remote files accessing,password altering etc so now iam creating connection lot of times in every view to make use of this connection object. Now my query is ...Is there any way to make this object availaible in every view until i close the connection... -
deploying e-commerce django project
I want to deploy an application based on Oscar Django framework. I don't know what to use for that. It will be the online-shopping website with the threshold of maximum 3k purchases/month. Which hosting service will be the best for this case with cost effectiveness and enough performance? -
PHP to Django compatibilty
i have a legacy app in php with authentication and everything working properly. Now i have decided to migrate to django for faster user experience since the app already has thousands of users i dont want to change the PHP component. What i want is that my login and user auth is done by existing PHP codebase and after login when the user shifts to django component django should automatically detect the user is signed in by looking at the session table in the mysql database. i have tried to integrate the https://github.com/winhamwr/django-php-bridge this bridge but it seems to be broken and doesn't work. -
AttributeError: 'list' object has no attribute 'iter_rows'
I'd read an excel file, there I'm getting all sheets but when doing this getting that error. views.py from Django.shortcuts import render import openpyxl def index(request): if "GET" == request.method: return render(request, 'file/index.html', {}) else: excel_file = request.FILES["excel_file"] # you may put validations here to check extension or file size wb = openpyxl.load_workbook(excel_file) # getting all sheets worksheet = wb.sheetnames print(worksheet) excel_data = list() # iterating over the rows and # getting value from each cell in row for row in worksheet.iter_rows(): row_data = list() for cell in row: row_data.append(str(cell.value)) excel_data.append(row_data) return render(request, 'file/index.html', {"excel_data": excel_data}) -
How to Filter HTML Content in Template By URL Conditional
How do I create a template filter that only shows a section of code on a specified page? For example, my homepage which is my base_generic has code that is specific to that page. Whenever another page is loaded that code should not be displayed. I know I can use the block system but was wondering if I could also accomplish the task with a combination of the URL and If filter. See code below: # Code for base_generic template {% url 'organizer-homepage' as home_page %} {% if home_page %} Shows Content Only on Specified Page {% else %} Show Alternate on All Other Pages {% endif %} -
How to set lazy module file load path in Angular, js file cannot find in Apache
Code works fine in dev mode. But not work after deploying to apache. Home page path is http://127.0.0.1 , and click lazy-module it will find path from /. My js files are under static folder. Static files loads here , e.g. browser access path is 'http://127.0.0.1/static/4-es5.js' D:/web/staticsites └─4-es5.js └─4-es2015.js └─... └─main-es5.js When I click lazy-router module link console prompt (missing: http://127.0.0.1/4-es2015.js) How to make angular load the path to http://127.0.0.1/static/4-es2015.js ? Apache Config Alias /static D:/web/staticsites <Directory D:/web/staticsites> AllowOverride None Options None Require all granted </Directory> -
Forloop choices of RadioSelect in Django ModelForm
I have list of choices. I want to get value one by one choice in HTML forms.py class ProfileForm(ModelForm): class Meta: model = UserInfor fields = [ 'gender'] widgets = { 'gender': forms.RadioSelect(choices=GENDERS), } labels = { 'gender': "Gender", } view.py def profile(request): user_info = ProfileForm() return render(request, 'pages/test.html', {'user_info': user_info) test.html {% for choice in genders %} <label class="radio-inline" class="radio-inline"><input type="radio" value="???">{{ ??? }}</label> {% endfor %} -
Creating model field to store multiple text inputs in django
i created a form on html with a dynamically increasing text field. how do i store all the inputs from the text fields under the single 'collaborators' attribute in my django models.py? this is my html code: <!DOCTYPE html> <html lang="en"> <head> <title>Central Data Masking Platform</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ var i=1; $('#addCollab').click(function(){ i++; $('#dynamicField').append('<tr id="row'+i+'"><td><input type="text" name="collab" id="collab'+i+'"></td><td><button type="button" name="removeCollab" id="'+i+'" class="removeCollab">x</button></td></tr>') }); $(document).on('click', '.removeCollab', function(){ var button_id = $(this).attr("id"); $('#row'+button_id+'').remove(); }); }); </script> </head> <body> <div class="formGrp"> <form> <div class="collaborators"> <table id="dynamicField"> <tr> <td> <label for="collabID">Collaborator Names: </label> <input type="text" name="collab" id="collab1"> </td> <td><button type="button" name="addCollab" id="addCollab">Add Collaborator</button></td> </tr> </table> <input type="submit" name="submit" value="submit"> </div> </form> </div> </body> </html> python code: class projectDetails(models.Model): project_id=models.BigAutoField(primary_key=True) #collaborators= date_created=models.DateTimeField(auto_add_now=True) -
Django Rest Framework and Auth: GET user with unauthenticated credentials throws 403
I'm using django-rest-auth for API endpoints for my custom user model. Getting user details, I send a GET request to /rest-auth/user/. This works fine with an authenticated user, but is forbidden for an unauthenticated user marked by a 403 Forbidden error. However, I want other users to be able to view each other's details. How can I change this? This test is the one which demonstrates this error: def test_get_user(self): # /rest-auth/user/ (GET) # params: username, first_name, last_name # returns: pk, username, email, first_name, last_name client = APIClient() client.login(username=self.user2.username, password=self.user2.password) path = "/rest-auth/user/" user_data = { "username": self.username, } expected_response = { "pk": self.id, "username": self.username, "email": self.email, "first_name": '', "last_name": '', } response = client.get(path, user_data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, expected_response) -
How can i connect my django like button to ajax to refresh automatically
I have a django project that im working on. Users will be able to like and dislike post....... here is my model class Tweet(models.Model): tweet_user = models.ForeignKey(User, on_delete=models.CASCADE) tweet_message = models.TextField() tweet_date = models.DateTimeField(auto_now_add=True) tweet_like_counter = models.IntegerField(default=0) tweet_picture = models.FileField(null=True,blank=True) def __str__(self): return self.tweet_message class Like(models.Model): user = models.ManyToManyField(User) tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweet.tweet_message class Disike(models.Model): user = models.ManyToManyField(User) tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweet.tweet_message here is my view from django.views.decorators.csrf import csrf_exempt @csrf_exempt @login_required def like(request, pk): currentTweet = get_object_or_404(Tweet,pk=pk) username = User.objects.get(pk=request.user.id) like_queryset = Like.objects.filter(tweet=currentTweet, user=username) dislike_queryset = Disike.objects.filter(tweet=currentTweet, user=username) if like_queryset.exists(): Like.objects.filter(tweet=currentTweet, user=username).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() if dislike_queryset.exists(): Disike.objects.filter(tweet=currentTweet, user=username).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() like = Like.objects.create(tweet=currentTweet) like.user.add(username) dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() return JsonResponse({ 'like_counter': currentTweet.tweet_like_counter }) @csrf_exempt @login_required def dislike(request, pk): currentTweet = get_object_or_404(Tweet, pk=pk) username = User.objects.get(pk=request.user.id) like_queryset = Like.objects.filter(tweet=currentTweet, user=username) dislike_queryset = Disike.objects.filter(tweet=currentTweet, user=username) if dislike_queryset.exists(): Disike.objects.filter(tweet=currentTweet, user=username).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() if like_queryset.exists(): Like.objects.filter(tweet=currentTweet, user=username).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject … -
How to get label name from labels in Meta class Django ModelForm
In Meta class, I define label name for fields. I want to get label name, I tried but nothing. forms.py class UserForm(ModelForm): class Meta: model = User fields = ['first_name'] widgets = { 'first_name': forms.TextInput(attrs={'type': 'text', 'placeholder': 'First Name', 'class': 'form-control input-md'}) } labels = { 'first_name': "First Name" } views.py def profile(request): user = UserForm() user_info = ProfileForm() return render(request, 'pages/demo.html', {'user': user}) demo.html <label style="margin-left: -48px; margin-right: 48px;" class="col-md-4 control-label">{{ ??? }}</label> -
Cannot import apps in django project with vscode
In vscode I am trying to import Apps in my django project. But as below screen shot, I cannot import my apps in urls.py. I also added my apps into mysettings(INSTALLED_APPS). vscode error -
How create simplest possible template for view with inline formset?
I have my view where I used inline formset, but I don't know how to display this formset in my template, in normal view I would use <form method='POST' action=''> {%csrf_token%} {{form.as_p}} But I don't know how to do this in this case. This is my view: class AddBookView(CreateView): model = Book form_class = AddBookForm formset_class = IndustryIdentifiersFormSet success_url = reverse_lazy('add_book') def get_context_data(self, **kwargs): data = super(AddBookView, self).get_context_data(**kwargs) if self.request.POST: data['identifiers'] = IndustryIdentifiersFormSet(self.request.POST) else: data['identifiers'] = IndustryIdentifiersFormSet() return data def form_valid(self, form): context = self.get_context_data() identifiers = context['identifiers'] with transaction.atomic(): self.object = form.save() if identifiers.is_valid(): identifiers.instance = self.object identifiers.save() return super(AddBookView, self).form_valid(form) def get_success_url(self): return self.success_url -
How to create a search query to search a local JSON file using python?
I just want to search this JSON data shown below when the search button is clicked and it shows the results in a table using Python but I am unsure as to how to create a search query. {"returnCode":0,"message":null,"resultList":[{"poNo":"0000123456","deliveryDock":"D1","dcNo":"DC01","vendorNo":"0001112222","orderDate":"2019-06-07","deliveryDate":"2019-06-02","deliveryTime":"00:00","noOfPallets":"10.0000","source":"MANUAL","status":"Scheduled","auditList":[{"oldDeliveryDock":"D2","oldDeliveryDate":"2019-06-03","oldDeliveryTime":"01:30","changedBy":"XASNH","changedOn":"2019-06-07","reasonCode":"FCST"},{"oldDeliveryDock":"D3","oldDeliveryDate":"2019-06-04","oldDeliveryTime":"03:30","changedBy":"XRCA4","changedOn":"2019-06-07","reasonCode":"WOW"}]}]} This is the design of the search query and the tables where the results should show ` -
How to get my like button in django to work?
I am trying to get my like button to work on my website. You can make "tweets" on my website, but users are not able to like the post. I already have the front end set up with ajax. that works perfect. The problem lies in my views. Here is my models class Tweet(models.Model): tweet_user = models.ForeignKey(User, on_delete=models.CASCADE) tweet_message = models.TextField() tweet_date = models.DateTimeField(auto_now_add=True) tweet_like_counter = models.IntegerField(default=0) tweet_picture = models.FileField(null=True,blank=True) def __str__(self): return self.tweet_message class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweet.tweet_message class Disike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweet.tweet_message class TweetComment(models.Model): class Meta: ordering = ['-id'] tweetcomment = models.ForeignKey(Tweet, on_delete=models.CASCADE, related_name='tweetcomments') tweetcommentauthor = models.ForeignKey(User,on_delete=models.CASCADE) tweetcommentmessage = models.TextField() tweetcommentcomment_date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweetcommentmessage Here is my view from django.views.decorators.csrf import csrf_exempt @csrf_exempt @login_required def like(request, pk): currentTweet = get_object_or_404(Tweet,pk=pk) user = User.objects.get(pk=request.user.id) like = Like.objects.create(tweet=currentTweet, user=user) like_queryset = Like.objects.filter(tweet=currentTweet, user=user) dislike_queryset = Disike.objects.filter(tweet=currentTweet, user=user) if like_queryset.exists(): Like.objects.filter(tweet=currentTweet, user=user).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() if dislike_queryset.exists(): Disike.objects.filter(tweet=currentTweet, user=user).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() return JsonResponse({ 'like_counter': currentTweet.tweet_like_counter … -
Django login redirect to password reset page instead of profile page
I am new at django and building my first app. At this stage, I am trying to login with django without using a custom view function. Unfortunately, after creating users in the django admin page, and trying to login, I found that the login button redirects me to the password reset page having entered an invalid link. I don't know if the login have failed or succeeded. Thank you to take my question into consideration. I have looked for many similar problems, but never encountered the same situation. url from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) #Add Django site authentication urls (for login, logout, password management) urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), path('accounts/login/', include('django.contrib.auth.urls'), name = 'login'), path('accounts/logout/', include('django.contrib.auth.urls'), name = 'logout'), path('accounts/password_change/', include('django.contrib.auth.urls'), name = 'password_change'), path('accounts/password_change/done/', include('django.contrib.auth.urls'), name = 'password_change_done'), path('accounts/password_reset/', include('django.contrib.auth.urls'), name = 'password_reset'), path('accounts/password_reset/done/', include('django.contrib.auth.urls'), name = 'password_reset_done'), path('accounts/reset/<uidb64>/<token>/', include('django.contrib.auth.urls'), name = 'password_reset_confirm'), path('accounts/reset/done/', include('django.contrib.auth.urls'),name='password_reset_complete') ] html base <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% block title %} <title>Acceuil</title> {% endblock %} {% load static %} <link rel="stylesheet" type=text/css href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'css/menu.css' %}"> <link rel="stylesheet" type=text/css href="{% static 'css/style.css' %}"/> </head> <body> <section id="global"> {% block nav%} <!-- <nav … -
Django ModelForm shows "Select a valid choice. That choice is not one of the available choices" when I submit my ForeignKey field
I have a form where users can register the name of Cause Construct by selecting from a list of construct. Every time I try to submit, the field raises "Select a valid choice. That choice is not one of the available choices" Here are my models: class Construct(models.Model): name = models.CharField(max_length=200, help_text='Enter construct name') area = models.ForeignKey(AreaOfInterest, on_delete=models.CASCADE, related_name="construct") def __str__(self): return self.name class Cause(models.Model): name = models.ForeignKey(Construct, on_delete=models.CASCADE, related_name="cause") reference_value = models.ForeignKey(Value, on_delete=models.CASCADE, related_name="cause_ref") observed_value = models.ForeignKey(Value, on_delete=models.CASCADE, related_name="cause_obs") def __str__(self): return self.name.name This is my form: class CauseForm(forms.ModelForm): def __init__(self, area, *args, **kwargs): super(CauseForm, self).__init__(*args, **kwargs) self.fields['name'].queryset = Construct.objects.filter(area=area) class Meta: model = Cause fields = '__all__' And this is my view: def new_theory(request, name): current_area = get_object_or_404(AreaOfInterest, name=name) if request.method == 'POST': causeform = CauseForm(current_area, request.POST) if causeform.is_valid(): newcause = causeform.save(commit=False) newcause.save() return redirect('area_of_interest', name=name) else: print(causeform.errors) else: causeform = CauseForm(current_area) return render(request, 'swetheory/createtheories.html', {'current_area': current_area, 'causeform': causeform}) How can I correctly submit my form? -
How to run a docker django app in my Centos VPS
I have a VPS and Docker with Django Application, How I can deploy and run it on my VPS in specified Domain? -
How to get all Django REST Framework permission classes?
After starting a Django shell using ./manage.py shell I can't see any of the custom permission subclasses in the application: In [1]: from rest_framework.permissions import BasePermission In [2]: BasePermission.__subclasses__() Out[2]: [rest_framework.permissions.AllowAny, rest_framework.permissions.IsAuthenticated, rest_framework.permissions.IsAdminUser, rest_framework.permissions.IsAuthenticatedOrReadOnly, rest_framework.permissions.DjangoModelPermissions] How can I get all the permission classes, including the custom ones? -
How can i display "Tags" feature implemented from my views.py to the template in DJANGO?
I have implemented a "Tag" feature but i am unable to show it in the template. As matter of fact, my query in the view show "None" as result when i try to debug it with PDB. I dont know what to do, it been a few days now. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'draft'), ('published', 'published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete='models.CASCADE', related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('core:post_detail', args=[self.publish.year,self.publish.month,self.publish.day,self.slug]) views.py from django.shortcuts import render, get_object_or_404 from .models import ( Post, Comment ) from django.core.paginator import ( Paginator, EmptyPage, PageNotAnInteger ) from django.views.generic import ( ListView, ) from .forms import ( EmailPostForm, CommentForm ) from django.core.mail import send_mail from taggit.models import Tag def post_list(request, tag_slug=None): """ Tags also included. """ page_posts = Post.published.all() # Tags tag = None if tag_slug: tag … -
Determine whether the user was authenticated in "LogoutView"
Django always show the same page when you go to 127.0.0.1:8000/admin/logout, whether you were logged-in before or not. What I want is showing a Logout Successful Message only if the user was authenticated before; and show an error message if the user wasn't authenticated and try logging out. I also need to include the user's first_name in my logout successful message. I am using class-based django.contrib.auth.views.LogoutView view like this: class SignoutView(LogoutView): template_name = "users/signout.html" def get_next_url(self): redirect_to = self.request.GET.get("next", "/") return redirect_to and here is the template: {% extends "base.html" %} {% block content %} <h1>Sign out Page</h1> <br> {% if was_authenticated %} <div class="alert alert-success" role="alert"> <h4 class="alert-heading">You have logged out from your account {{first_name|capfirst}}!</h4> <p>Thanks for spending some quality time with my web site today.</p> <hr> <p class="mb-0" id="displayTimer"></p> </div> {% else %} <div class="alert alert-danger" role="alert"> <h4 class="alert-heading">Ooh no!</h4> <p>Looks like you are not logged in! So you can not log out! Cool yeah?</p> </div> {% endif %} {% endblock %} {% block js %} {% if was_authenticated %} <script type="text/javascript"> var count = 5; var url = "{{redirect_address}}"; var countdown = setInterval(function() { $('#displayTimer').text("You will be redirected to the home page in " + count-- + … -
Django using ajax
I am finish with my project using django but I want it to be a asynchronous so I use jquery and ajax but i am stuck right now, The problem is when I add a product in the cart all of the product fields in the table are having the same values but when I refresh it came back to their own values. Can any body help me with this, I am new in using ajax. html link <a class="add-to-cart"href="{% url 'cart:add_cart' cart_item.product_format.id %}" class="custom_a" data-endpoint="{% url 'cart:add_cart' cart_item.product_format.id %}"><i class="fas fa-plus-circle custom_icon"></i></a> html table <td class="text-left"> <strong class="table-format"><span class="product-format">{{ cart_item.product_format.bformat }}</span></strong> <br> SKU: {{ cart_item.product_format.id }} <br> Unit Price: $<span class="cart-unit-price">{{cart_item.product_format.price}}</span> <br> Discount: <span class="cart-discount">{{cart_item.product_format.discount}}%</span> <br> Qty: <span class="cart-qty-price">{{ cart_item.quantity }} x ${{ cart_item.product_format.price }}</span> </td> <td class="text-primary"> <strong> <span class="cart-subtotal">${{ cart_item.sub_total|floatformat:2 }} </span></strong></td> script <script> $(document).ready(function(){ /* AJAX add to cart */ var cartAdd = $('.add-to-cart') cartAdd.unbind('click').click(function(event) { event.preventDefault(); var thisLink = $(this) var hrefEndpoint = thisLink.attr('data-endpoint') var addCartMethod = "GET" var linkData = thisLink.serialize(); $.ajax({ url: hrefEndpoint, method: addCartMethod, data: linkData, success: function(data){ console.log(hrefEndpoint) var productFormat = $('.product-format') var cartSubtotal = $('.cart-subtotal') var cartQtyPrice = $('.cart-qty-price') var cartDiscount = $('.cart-discount') var cartUnitPrice = $('.cart-unit-price') var cartTotal = …