Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SSL proxy pass with NGINX leading to bad gateway through Docker
Background My setup is based on the following tutorial: Dockerizing Django with Postgres, Gunicorn, and NGINX TL;DR: (italics: not covered by tutorial; personal adventure) 3 Docker services for: nginx -> django -> postgres (arrow indicating dependency) Nginx proxy passes requests to exposed port in Django service. HTTP (non-SSL) requests working require SSL connections by redirecting http -> https Details I've generated a self-signed certificate to test out ssl redirects with NGINX locally before trying to get it to work on a VPS in production. I'm quite new to working with NGINX and so I'm not entirely sure what's going wrong or how to diagnose problems. Here's what I expect should happen with the NGINX file I've provided below: Go to http://localhost Get redirected to https://localhost Warning from browser about a self-signed cert; accept warning and proceed Site rendered fine, SSL redirect working! But this isn't the case. I get a 502 Bad Gateway, and NGINX outputs the following logs: prod_1 | 192.168.144.1 - - [03/Jun/2019:00:01:44 +0000] "GET / HTTP/1.1" 502 158 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:67.0) Gecko/20100101 Firefox/67.0" "-" prod_1 | 2019/06/03 00:01:44 [error] 8#8: *1 peer closed connection in SSL handshake while SSL handshaking to … -
Skip saving row if slug already exists in postgresql database - python
I'm setting up a function in my Django Views that calls an API and save the data into my Postgresql database. Everthing was working fine until I got an IntegrityError slugkey already exists, so I'm trying to find a way to skip or ignore the row if the slugify slug already exists. I've been stuck with this all day and I need a solution to respect expected timeline.. This is my Django Models: class Product(models.Model): destination = models.CharField(max_length=255, default='') title = models.CharField(max_length=255, default='') slug = models.SlugField(unique=True, max_length=255, default='') description = models.TextField(max_length=2047, default='') link = models.TextField(max_length=500, default='') ptags = TaggableManager() image = models.ImageField(max_length=500, default='images/zero-image-found.png') timestamp = models.DateTimeField(auto_now=True) def _ptags(self): return [t.name for t in self.ptags.all()] def get_absolute_url(self): return reverse('experience', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) super(Product, self).save(*args, **kwargs) def __str__(self): return self.destination And this is my function in Views: def api_data(request): if request.GET.get('mybtn'): # to improve, == 'something': resp_1 = requests.get( "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=ROME&limit=5000&currencyCode=CAD", headers={ "Headout-Auth": HEADOUT_PRODUCTION_API_KEY }) resp_1_data = resp_1.json() base_url_2 = "https://www.headout.com/api/public/v1/product/get/" for item in resp_1_data['items']: print('parsing, translating and saving item {}'.format(item['id'])) # concat ID to the URL string url = '{}{}'.format(base_url_2, item['id'] + '?language=fr') # make the HTTP request resp_2 = requests.get( url, headers={ … -
Are pre-save signals handled before the clean method in Django?
I could not find a reference to it. The question is honestly pretty self-explanatory. In Django forms, such as admin forms, the clean method is automatically called before saving. My question is, if I have a method as a pre-save signal, which one will execute first? -
"Invalid choice" for forms.Select
I defined a model with a fixed set of values allowed for a field: class ContactMode(Enum): EMAIL = "E-mail" PHONE = "Phone" class Foo(models.Model): mode = models.CharField( max_length=5, choices=[(tag, tag.value) for tag in ContactMode]) I defined a form using this model: CONTACT_MODES = [(tag, tag.value) for tag in ContactMode] class CreateFooForm(ModelForm): mode = forms.CharField(widget=forms.Select(choices=CONTACT_MODES)) class Meta: model = Foo fields = ["mode",] On validating this form, I get: Value 'ContactMode.EMAIL' is not a valid choice Form data field seems properly bound: <QueryDict: {'csrfmiddlewaretoken': ['...'], 'mode': ['ContactMode.EMAIL']}> I also tried using (tag.name, tag.value) instead of (tag, tag.value) as choices and got the same result. What is the right way to bind a value from a closed-set to a ModelForm? -
restring user to like a post more than once
I have a code that allows user to like the post but I realized the user can like the post more than once which I don't want. How do I restrict this? my code @login_required def like_post(request, pk): if pk: liked_post = Post.objects.get(id=pk) count = liked_post.likes count += 1 liked_post.likes = count liked_post.save() return redirect('/community/post/%s' %liked_post.id) what I tried adding something like this....but not sure if post.likes.filter(id=user.id).exists(): post.likes.remove(user) else: post.likes.add(user) -
How to access a Postgres database from a python program without django or heroku
I've created a simple python app using heroku with django that writes to a Postgres database online. I also want to read and write to this database from a raspberry pi program using Python. Is it possible to do so without running heroku or django on the pi? Is there a simple way of accessing the database? -
Django permission row table to a determinate user
i'm asking a questions about permissions, i have 2 table, AnagraficaCliente and Tracking with relation 1 to many, autentichate of user is default built in with a django.contrib.auth.urls. I searched many forum and site but i d ont understand how set permission on row for determinate users. For example: My site is a web track to show shipped items, if i search a tracking for a user it worked, but all tracking are visible (for all users), i want that only the tracking that belongs to user show to him. I think that i use model user from django.contrib.auth.models import User i don't know how work with my code. Thanks at all. #models.py from django.db import models from django.urls import reverse # Create your models here. class AnagraficaCliente(models.Model): codice_cliente = models.CharField(max_length=20, primary_key=True, null=False, unique=True) ragione_sociale = models.CharField(max_length=80) #ragione_sociale_dest = models.CharField(max_length=40) nome = models.CharField(max_length=40, blank=True) cognome = models.CharField(max_length=20, blank=True) #ragione_sociale = models.CharField(max_length=20) indirizzo = models.TextField(blank=True) cap = models.CharField(max_length=5, blank=True) piva = models.CharField(max_length=20, blank=True) vatnumber = models.CharField(max_length=20, blank=True) #ragione_sociale_dest = models.CharField(max_length=40) #indirizzo_dest = models.TextField(null=True) def __str__(self): #return self.ragione_sociale + " " + self.codice_cliente #return self.ragione_sociale_dest + " - " + self.indirizzo_dest + " - " + self.codice_cliente return self.codice_cliente + " - … -
Displaying image from back-end
I create a project - a web application based on the django framework. One of tasks is creating graphics based on user's parameters. I created a form that works correctly, and then correctly creates a matrix in the back-end. Everything works as I want. My problem is connected with display matrix in the frond-end. In the final result, the back-end returns the matrix. Matrix contains complex number and it's size is 256 x 256. I want to display this matrix on the website, but I do not know how to do it. I tried to solve my problem in this way: views.py image = plt.imshow (ML) encoded = base64.b64encode (image) encoded = plt.imsave ('myimage.svg', image) return render(request, 'myfirstapp/r.html', {'Page': page, 'form': form, 'image': encoded}) html file <img src = "data: image / png; base64, {{image}}" /> Unfortunately, it does not work. I have no idea what I'm doing wrong or how to solve it in a other way. I expected that my matrix is being displayed at the website. -
How to read a filename with special characters from disk into a FileField?
In my Django app, I am downloading a Youtube video to some folder inside MEDIA_ROOT. I am also associating the downloaded file with a model's FileField under the video title. The problem occurs when the video title contains some special characters. For example "Idiot Test - 90% fail" will be saved to disk with % removed, so when associating this file by video title to a model I will get an error that such file does not exist, because I am passing the original video title (not the one read from disk) to the FileField which contains the %. How can I solve this? Should I strip the video title of any special characters first or is there a better solution? downloaded_path = pytube.download(sampler_settings.AUDIO_PATH, video_title) downloaded = File(open(downloaded_path, 'rb')) # create folder by the name of current session key where the downloaded file will be stored session_folder = os.path.join(sampler_settings.AUDIO_PATH, session_key) os.mkdir(session_folder) main_sample = MainSample() main_sample.session_key = session_key main_sample.audio = os.path.join(session_folder, video_title) main_sample.save() -
Django + Celery - AttributeError: 'Settings' object has no attribute 'worker_state_db'
When trying to run a Celery worker using: celery -A my_app_name worker -l INFO I get a AttributeError: 'Settings' object has no attribute 'worker_state_db' The app was previously working, but I can't find the commit breaking it anymore. This is a Django web app that uses Celery as a worker with a Redis DB. My (relevant) settings.py looks like: ... SECRET_KEY = 'A_VALID_BUT_REDACTED_SECRET_KEY' REDIS = os.environ.get('REDIS_URL','redis://localhost:6379') CELERY_BROKER_URL = REDIS CELERY_BROKER_URL = REDIS CELERY_RESULT_BACKEND = REDIS CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' TASK_ALWAYS_EAGER=False My celery.py looks like: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'vccrm.settings') app = Celery('vccrm') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) and lastly my init.py: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) I tried doing what this question suggests, but it doesn't solve anything. I also tried to look at other Django apps running celery, but can't find anything different/mis-configured Are there any smart approaches to troubleshoot what's wrong with my Celery settings? -
Can I use full text search in Django with SQL Server?
I want to have a similar function to full text search with Django for SQL Server. Instead of using only "icontains", full text search would make it easier to search in text field (e.g., lemmatisation, indexing, etc.) I've been looking around but it seems there is only Full text search for postgres. https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/search/ But as my database is stored in SQL Server, I would need something similar for SQL Server. Does anyone know if such full text search function is available in Django for SQL server or anything else I should try (e.g., Elasticsearch)? Thanks a lot! -
Django createsuperuser throows django.core.exceptions.FieldDoesNotExist: User has no field named ' ' error
When i try to create a superuser using python manage.py createsuperuser command, it throws the following error : Username: wcud Traceback (most recent call last): File "/home/Music/ENV/lib/python3.5/site-packages/django/db/models/options.py", line 617, in get_field return self.fields_map[field_name] KeyError: '' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/Music/ENV/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/Music/ENV/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/Music/ENV/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/Music/ENV/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/home/Music/ENV/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/Music/ENV/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 129, in handle field = self.UserModel._meta.get_field(field_name) File "/home/Music/ENV/lib/python3.5/site-packages/django/db/models/options.py", line 619, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: User has no field named '' I am extending the Django user model it was working fine but when i deleted my database and then i again restore the database successfully, but when i am going to create the superuser it throws this error. Please help! -
like button not doing anything, cant tell what the problem is
I want users to be able to like my post so I implemented here. here's my code. It doesn't give any error which is frustrating. models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) url = models.URLField(max_length=250, blank=True, null=True) views = models.IntegerField(default=0) likes = models.ManyToManyField(User, related_name='likes') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) def total_likes(self): return self.likes.count() views.py def like(request): if request.method == 'POST': user = request.user # bring login user post_pk = request.POST.get('pk', None) post = Post.objects.get(pk = post_pk) #bring the post object. if post.likes.filter(id = user.id).exists(): #if exit post.likes.remove(user) #likes deleted. message = 'You disliked this' else: post.likes.add(user) message = 'You liked this' context = {'likes_count' : post.total_likes, 'message' : message} return HttpResponse(json.dumps(context), content_type='application/json') urls.py urlpatterns = [ path('', PostListView.as_view(), name='community-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/<int:post_pk>/comment/new',views.comment_new, name='comment_new'), path('post/<int:post_pk>/comment/<int:pk>/edit',views.comment_edit, name='comment_edit'), path('post/<int:post_pk>/comment/<int:pk>/delete',views.comment_delete, name='comment_delete'), path('like/', views.like, name='like'), my html <input type="button" class="like" name="{{ memo.id }}" value="Like"> <p id="count{{ memo.id }}">count : {{ memo.total_likes }}</p> <script type="text/javascript"> for(i = 0; i < $(".writer_name").length; i++){ if($("#user_name").text() == $(".writer_name")[i].innerHTML){ $("#control_id"+i).removeClass("hidden"); } } $('.like').click(function(){ var pk = $(this).attr('name') $.ajax({ type: "POST", url: "{% url 'like' %}", data: {'pk': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", … -
Make Django Rest Api User Specific (get_queryset)
I want to make a Django rest api that is user specific so that I do /username at the end of the url. Models: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField() description = models.CharField(max_length=300) class Meta: verbose_name_plural = 'User Profiles' def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_data(sender, update_fields, created, instance, **kwargs): if created: user = instance profile = UserProfile.objects.create(user=user, age=18, description='No Description') class Notes(models.Model): note = models.CharField(max_length=1000) parent_user = models.OneToOneField(UserProfile, blank=True, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Notes' def __str__(self): return self.note Serializers: class NoteSerializer(serializers.ModelSerializer): class Meta: model = Notes fields = ('id', 'note', 'parent_user') urls: router = routers.DefaultRouter() router.register('notes', views.UserNoteView) urlpatterns = [ path('', include(router.urls)), ] views: class NoteView(viewsets.ModelViewSet): http_method_names = ['get', 'post', 'put', 'delete', 'patch'] queryset = Notes.objects.all() serializer_class = NoteSerializer class UserNoteView(NoteView): def get_queryset(self): return self.request.parent_user.Notes.all() My problem is that I can't do for example /William which is the name of my user, and user profile. Someone that knows this must be able to help! -
Ignore saving the row if slug already exists in Django postgresql
I'm setting up a function in my Django Views that calls an API and save the data into my Postgresql database. Everthing was working fine until I got an IntegrityError slugkey already exists, so I'm trying to find a way to skip or ignore the row if the slugify slug already exists. I have done some researches but I didn't found anything.. This is my Models: class Product(models.Model): destination = models.CharField(max_length=255, default='') title = models.CharField(max_length=255, default='') slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='') description = models.TextField(max_length=2047, default='') link = models.TextField(max_length=500, default='') ptags = TaggableManager() image = models.ImageField(max_length=500, default='images/zero-image-found.png') timestamp = models.DateTimeField(auto_now=True) def _ptags(self): return [t.name for t in self.ptags.all()] def get_absolute_url(self): return reverse('experience', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) super(Product, self).save(*args, **kwargs) def __str__(self): return self.destination And this is my function in Views: def api_data(request): if request.GET.get('mybtn'): # to improve, == 'something': resp_1 = requests.get( "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=ROME&limit=5000&currencyCode=CAD", headers={ "Headout-Auth": HEADOUT_PRODUCTION_API_KEY }) resp_1_data = resp_1.json() base_url_2 = "https://www.headout.com/api/public/v1/product/get/" for item in resp_1_data['items']: print('parsing, translating and saving item {}'.format(item['id'])) # concat ID to the URL string url = '{}{}'.format(base_url_2, item['id'] + '?language=fr') # make the HTTP request resp_2 = requests.get( url, headers={ "Headout-Auth": HEADOUT_PRODUCTION_API_KEY }) resp_2_data = … -
Deploy Django Application to AWS
I'm trying to deploy a Django App to AWS using eb deploy app_name I get this response Creating application version archive "app-84c54-190602_180146". Uploading: [##################################################] 100% Done... INFO: Environment update is starting. INFO: Deploying new version to instance(s). INFO: New application version was deployed to running EC2 instances. INFO: Environment update completed successfully. But if I try to access the site I simply get Index of / I've looked at the log files (eb logs app_name), which are empty. I don't know how to debug the issue. Could you advise me on things to look at. -
How to display a template based on a queryset done in a class based view where one of the argument for queryset comes from URL parameter
How to generate a template of all 'posts' that a 'user' wrote. Idea: Client click on the 'user' link from the main site and we are taken to the page with all 'posts' user have generated. I have tried so many things in views.py, part of them worked so only last not working solution will be attached. :) I try to get a 'user' parameter from the URL so for example: blogname/user -> that URL will generate list of all 'user' posts. urls.py urlpatterns = [ path('author/<str:username>', AuthorPostIndexView.as_view(), name='author_post_index'), ] models.py class Person(models.Model): username = models.CharField(max_length = 50, null=True, unique = True) post = models.ManyToManyField(Post,blank=True,null=True, related_name='authors') class Post(models.Model): title = models.CharField(max_length=255, blank=True, null=True) views.py # - commented out as non of these worked. Some of them I have broken playing around with desperation to fix so they are with lack logic, sketches. Tried those one by one. class AuthorPostIndexView(ListView): model = Person template_name ='authorpostindex.html' # def get_queryset(self): # username = self.kwargs['username'] # authorpost = username.post.all() # return username # def get_queryset(self): # if self.request.method == 'GET': # queryset = Person.objects.all() # url_username = self.kwargs('username', None) # if url_username is not None: # queryset = queryset.filter(person__username=url_username).post.all() # else: # queryset = … -
I am uploading a file into the media folder in django using a browse button.I need to get the path of that file in my local storage
I am trying to upload a folder using webkit directory into the media folder in django.As we can't directly copy a directory into the media folder( i think we do it in uploading a file),to do this I'm trying to make use of shutil.copytree() to copy the directory entirely into the media from my local storage and drag individual file paths and store in database.For this shutil.copytree() demands the file path as input and how do i get it from webkitdirectory.I tried it with uploading a single file....I am unable to get the file path even this is my form {% load static %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{uploaded_file_url }}"> {{uploaded_file_url }}</a></p> {% endif %} <p><a href="{% url 'timelinemethod' %}">Return to home</a></p> {% endblock %} this is my view myfile is the file object after post it is displaying the path of file from media folder but i need the path in local storage as c://.... (so that in case of a folder I can copy the entire directory using shutil.copytree()) def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile … -
How to shuffle queryset object fields
i need to make Quiz app on Django with random questions, model for Question is given below. I`ve already figured out how to randomize Questions in query set, but now i need to find a way to shuffle options of the question in template, but i cant figure it out by myself. Would be grateful for any advice class Question(models.Model): question = models.CharField('Question text',max_length=250) test = models.ForeignKey(Test, on_delete=models.CASCADE) Option1 = models.CharField('answer 1',max_length=50) Option2 = models.CharField('answer 2',max_length=50) Option3 = models.CharField('answer 3',max_length=50) Option4 = models.CharField('answer 4',max_length=50) RightAnsw = models.IntegerField('Right answer nuber') mark = models.IntegerField('Points for right answer') -
How to pass data to a class based view's method?
I am trying to figure out how I can pass data from a form to the method of a class based view that serves as a API endpoint. Homepage view (has a form to enter a stock ticker): def home(request): # data = get_stock_data('TSLA', key) if request.method == 'POST': form = TickerForm(request.POST) if form.is_valid(): ticker = form.cleaned_data['ticker'] stock_data = get_stock_data(ticker, api_key) return redirect('chart-data', ticker=ticker) # this line I am having trouble with else: form = TickerForm() stock_data = None return render(request, 'app/home.html', {'data': stock_data, 'form':form}) The API View: class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, ticker, format=None): # get stock data stock_data = get_stock_data(ticker, api_key) # how do I pass the ticker? labels = [] default_items = [] # get label & values for key, value in stock_data.items(): labels.append(key) default_items.append(value['4. close']) # prepare data data = { 'labels': labels[::-1], 'default_items': default_items[::-1] } return Response(data) urls.py urlpatterns = [ path('', views.home, name="homepage"), path('api/chart/data', views.ChartData.as_view(), name="chart-data"), ] Then I get the data with Javascript and display the graph on the frontend, which works fine. The only thing I can't figure out how to pass the ticker argument to the get method of my ChartData view. I hope my … -
Why an i not being able to equate Menu1.maintriptype==Menu2.maintriptype?
I have two class menu1 and menu2. Two of them are interconnected by a ForeignKey. while using if (Menu1.maintriptype==Menu2.maintriptype) in nested loop to create a menu degined table it doesn't work? from django.db import models class Menu1(models.Model): maintriptype= models.CharField(max_length=32) def __str__(self): return self.maintriptype class Menu2(models.Model): menu2triptype=models.CharField(max_length=32) maintriptype=models.ForeignKey(Menu1, on_delete=models.PROTECT) def __str__(self): return self.menu2triptype With output: menu1 menu2 a x b y c z based on the foreign key use -
Method PUT not allowed in resquest without /<id>
I have a simple ModelViewSet class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all().order_by('id') serializer_class = PersonSerializer And with urls.py router = routers.DefaultRouter() router.register(r'persons', views.PersonViewSet) I need request a PUT /persons with the body { "id":10, "login":"alfredo", "avatar_url":"https://avatars.com/2222" } To update the the avatar_url. But when a call with this url '/persons' with method PUT I get response code 405 { "detail": "Method \"PUT\" not allowed." } ( I know the better way to do so is calling '/persons/10', but the requirement of the project is PUT '/persons' with the id inside the body request ) How can I implement this endpoint? -
How can I render ChoiceField as Radiobuttons with Crispy Forms?
I try to render field with choices in my form as radiobuttons with django crispy forms. I want to use bootstrap 4 styles. I maked custom template {% load crispy_forms_field %} <div class="form-check"> {% crispy_field field 'class' 'form-check-input' %} <label class="form-check-label" for="{{ field.id_for_label }}"> {{ field.label }} </label> </div> class CustomRadio(Field): template = 'orders/custom_radiofield.html' Than I try to use it in my Form: class CreateNewOrderForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( 'Delivery', CustomRadio('delivery_method'), 'city', 'address', css_class='col-12 col-lg-6') ) But it still as select in my page -
How To Correctly Render Likes For Multiple Objects in Django?
I have a Like feature, which works fine for the "Detailed Product". However, I want to add this feature on the main page, where multiple products are shown. Not sure, how to correctly do that. urls.py: url(r'^like$', views.like_product, name='like_product') script in the base.html: <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url 'like_product' %}', data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: 'json', success: function(response){ $('#like-section').html(response['form']) console.log($('#like-section').html(response['form'])); }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); </script> likes.html: <form action="{% url 'like_product' %}" method="post"> {% csrf_token %} {% if is_liked %} <button type="submit" id="like" name="product_id" value="{{ product.id }}" class="btn btn-danger">Dislike</button> {% else %} <button type="submit" id="like" name="product_id" value="{{ product.id }}" class="btn btn-primary">Like</button> {% endif %} </form> views.py: def home(request): products = Product.objects.all().order_by('-pub_date') f = ProductFilter(request.GET, queryset=products) context = { 'filter': f, } return render(request, 'product/home.html', context). def detail(request, product_id): product = get_object_or_404(Product, product_id=product_id) is_liked = False if product.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'product': product, 'is_liked': is_liked, 'total_likes': product.total_likes() } return render(request, 'product/detail.html', context) def like_product(request): product = get_object_or_404(Product, id=request.POST.get('id')) is_liked = False if product.likes.filter(id=request.user.id).exists(): product.likes.remove(request.user) is_liked = False else: product.likes.add(request.user) is_liked = True context = { 'product': product, 'is_liked': is_liked, … -
Django2.2 Context Manager | {{template_tags}} | Variable limit?
I have a template view in Django2.2, where I added two models & queries to look up metrics on user data (how many articles they read each month). I ran into a strange issue where if I place multiple context variables on the page, every variable on the page but the First Variable will return '0'. If I simply change the order of the variables in the markup, each date function appears to be calculating correctly (as long as it is the first to appear). I couldn't find anything about this in the docs...and I'm guessing that this isn't a great approach to display this information either and I should instead use a DjangoTemplateTag and perform the operations there. *Define the Object & Query def get_context_data(self, **kwargs): context = super(userDashBoardView, self).get_context_data(**kwargs) context['readArticleList'] = Articles.objects.filter(Unread = False,userId = self.request.user.SFPK ) *To avoid making further queries, I mutated the query into a set to perform further functions article_list = set(context['readArticleList']) article_read_date = (article_list.read_date for article_list in article_list) context['articles_last30'] = len(set(x for x in article_read_date if x > timezone.now() - timedelta(days=30))) context['articles_last60'] = len(set(x for x in article_read_date if x > timezone.now() - timedelta(days=60))) context['articles_last90'] = len(set(x for x in article_read_date if x …