Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker + django + gunicorn connect to Nginx of the host system
On ubuntu server 18.04 I run a docker container with Django 3.1 and Gunicorn which connects to a locally installed Postgres. I already have an another Django project with Nginx and Gunicorn on the same server without docker. The questions are: how to set up socket files for Gunicorn in a container and connect this container to the existing external Nginx so I can access the containerized django app from outside? docker-compose.prod.yml version: '3' services: app: build: context: . ports: - "8001:8001" volumes: - ./app:/app env_file: - .env.prod command: > sh -c "gunicorn app.wsgi:application --bind 0.0.0.0:8001" I run the container like this: docker-compose -f docker-compose.prod.yml up .env.prod ... DJANGO_ALLOWED_HOSTS='111.111.111.111 .mysitename.com localhost 172.18.0.1 127.0.0.1 [::1]' ... when running container executing of this command: curl 'http://127.0.0.1:8001/admin/login/?next=/admin/' gives me the html code of the admin page and it's ok. The existing Nginx is set up as in these digital ocean tutorials: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 I also secured it with Let's encrypt using this tutorial https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04 -
Bring current user in logs inside Django
My goal in Django is to log every row with the current user so that when multiple users are using the app, I know which log is from whom. Step 1: I found that I can create filters for Logger: (like this) The problem that I have is that the record doesn't have a request inside. Step 2: I learn here, that I need middleware to store my current user so that logger could use it. My problem now is, that if I store in local, and then retrieve from local, apparently, this is not "same" local, so it doesn't have this information Middleware.py import threading local = threading.local() class UserNameMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. setattr(local, 'my_user', 'Marko') print('set local Marko') response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response Filter.py import logging import threading local = threading.local() class UserFilter(logging.Filter): def filter(self, record): print('INSIDE') record.myusera = getattr(local, 'my_user', 'None') print(record.__dict__) return True Step 3: So, I was thinking to create a variable inside … -
custom primary email to login and secondary to disable to login in django
I am trying to make email management. Users can add a secondary email and make it primary for login and disable the previous email to login in to django. I build some models, forms, and views. Models.Py class Emails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) email = models.EmailField() is_primary = models.BooleanField() *Forms.py class MultipleEmailForm(forms.ModelForm): class Meta: model = Emails fields = ('email', ) Views.py def addemail(request): form = MultipleEmailForm if form.is_valid(): user_emails = Emails.objects.filter(user=request.user).update(primary=False) primary_email = Emails.objects.get(pk=email_id, user=request.user) primary_email.primary = True primary_email.save() return render(request, 'account/addemail.html', context) -
Django Settings.py stuck on "SECURE_SSL_REDIRECT = True"
I added the setting SECURE_SSL_REDIRECT = True to my django settings.py. It works perfectly in production mode so no issues there however, now if I make it the following to test in development mode SECURE_SSL_REDIRECT = False I get the following error You're accessing the development server over HTTPS, but it only supports HTTP. What could the issue be? Seems like something is making it not register the new value. -
EmailMultiAlternatives not sending BCC emails
I have a Django management command defined like this: class Command(BaseCommand): help = "Sends out an email with new jobs added in a timespan of a week" def handle(self, *args, **options): time_a_week_ago = timezone.now() - timedelta(days=7) time_now = timezone.now() job_listings_added_this_week = JobListing.objects.filter(time_added__gte=time_a_week_ago, time_added__lt=time_now) email_subscribers = EmailSubscriber.objects.all() emails = [] for subscriber in email_subscribers: emails.append(subscriber.email) msg_plain = render_to_string("employers/weekly_newsletter.txt", {"joblistings_list": job_listings_added_this_week}) msg_html = render_to_string("employers/weekly_newsletter.html", {"joblistings_list": job_listings_added_this_week}) msg = EmailMultiAlternatives("New jobs added this week", msg_plain, "newsletter@myjobboard.com", [], bcc=[emails]) msg.attach_alternative(msg_html, "text/html") msg.send() self.stdout.write(self.style.SUCCESS("Successfuly sent out the weekly email.")) I set the email content to be output to a file. When I run the management command, this is is what I get: Content-Type: multipart/alternative; boundary="===============8145459042862347861==" MIME-Version: 1.0 Subject: New jobs added this week From: newsletter@myjobboard.com Date: Thu, 12 Nov 2020 05:23:05 -0000 Message-ID: <160512424922.55295.17004148678390675586@johns-computer.168.1.22> --===============8145459042862347861== Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Jobs added last week Hey! These job listings were added last week: Test job 5 - click here: http://127.0.0.1:8000/12/ Test job 6 - click here: http://127.0.0.1:8000/13/ --===============8145459042862347861== Content-Type: text/html; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit <h1> Jobs added last week </h1> <p> Hey! These job listings were added last week: </p> <ul> <li><a href="http://127.0.0.1:8000/12/">Test job 5</a></li> <li><a href="http://127.0.0.1:8000/13/">Test job 6</a></li> </ul> --===============8145459042862347861==-- ------------------------------------------------------------------------------- In … -
Why is the CharField related to Form not showing up?
I have created Comment Model for my Project but the CharField is not showing in the LocalHost for some reason. The submit button is working but there is no field to place text Here is the models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField(max_length=300) def __str__(self): return f"{self.post}-{self.user}-Comment No.{self.pk}" Here is the views: class Comment_create(CreateView): model = Comment fields = ['body'] template_name = 'blog/post_detail.html' form = CommentModelForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug'])) Here is the forms.py class CommentModelForm(forms.ModelForm): body = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Add a comment...'})) class Meta: model = Comment fields = ('body',) Here is the urls.py path('blogs/<slug:slug>/comment/', Comment_create.as_view(), name='comment-post'), Here is the template: <div class="container-fluid mt-2"> <div class="form-group row"> <form action="{% url 'blog:comment-post' post.slug %}" method="post" class="comment-form" action="."> {% csrf_token %} {{ form }} <input type="submit" value="Submit" class="btn btn-outline-success"> </form> </div> </div> -
CRUD IN THE SAME PAGE DJANGO
I am trying to do a CRUD using only one html page with django, but I have already encountered the first problem, when using nav-tabs I am not able to load the form when I click on the Create / Edit tab, maybe it has something to do with urls, but I don't know. index.html <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Ordens de Serviço</h2> <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#list">Ordens de Serviço</a></li> <li><a data-toggle="tab" href="#create-update">Criar/Editar</a></li> <li><a data-toggle="tab" href="#detail">Ver</a></li> </ul> <div class="tab-content"> <div id="list" class="tab-pane fade in active"> <h3>Ordens de Serviço</h3> <table class="table"> <thead> <tr> <th>Nome</th> <th>TAG</th> <th>nivel</th> </tr> </thead> <tbody> {%for equipamento in equipamentos %} <tr> <td>{{equipamento.nome}}</td> <td>{{equipamento.tag}}</td> <td>{{equipamento.nivel}}</td> <td><a><button class="btn btn-primary">Editar</button></a></td> </tr> {%endfor%} </tbody> </table> </div> <div id="create-update" class="tab-pane fade"> <h3>Criar/Editar</h3> <form method="post"> {% csrf_token %} {{form}} </form> </div> <div id="detail" class="tab-pane fade"> <h3>Menu 2</h3> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.</p> </div> </div> </div> <script> </script> </body> </html> views.py: class ArvoreListView(ListView): queryset = Arvore.objects.all() template_name = 'example/index.html' context_object_name = 'equipamentos' class ArvoreCreateView(CreateView): form_class = ArvoreModelForm model = Arvore template_name = … -
Setting `CategoryInline.extra` at the class level is now deprecated. Set `CategoryInline.factory_kwargs` instead
I use django-extra-view on my project, i want to use CreateWithInlinesView and InlineFormSetFactory but i get this error Setting `CategoryInline.extra` at the class level is now deprecated. Set `CategoryInline.factory_kwargs` instead. This is my views.py class QuestionInline(InlineFormSetFactory): model = Question ordering = ("order", "category") extra = 1 class CategoryInline(InlineFormSetFactory): model = Category extra = 0 class SurveyCreate(CreateWithInlinesView): model = Survey fields = '__all__' list_display = ("name", "is_published") inlines = [CategoryInline, QuestionInline] and this is how i call it on page.html <form action="" method="post"> {% csrf_token %} <table> {% for formset in inlines %} {{ formset }} {% endfor %} </table> <div> <input class="btn btn-primary" type="submit" value="Submit"> </div> </form> -
How to Create a Comment Model for Posts in a Django Project
I am new in creating projects using Django, so I am creating a Blog Project, I am trying to add a comment function for my posts, I have created a Class Based View for the comments. I have also tried 2 comments as a trial from the admin and they are showing perfectly. My only issue is that I can not view the form from the website. I am not sure what I have missed? Here is the models.py class Comment(models.Model): # To know Who liked user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField(max_length=300) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post}-{self.user}-Comment No.{self.pk}" Here is the views: class Comment_create(CreateView): model = Comment fields = ['body'] template_name = 'blog/post_detail.html' form_class = CommentModelForm def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) Here is the forms.py class CommentModelForm(forms.ModelForm): body = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Add a comment...'})) class Meta: model = Comment fields = ('body',) Here is the urls.py path('blogs/comment', Comment_create.as_view(), name='comment-post'), Here is the template: <h2>Comments...</h2> {% if not post.comment_set.all %} No comments yet {% else %} {% for c in post.comment_set.all %} <div class="ui segment mb-5"> <span>{{ c.user }} {{ c.created }}</span> <div class='mt-5'>{{ c.body }}</div> </div> {% … -
How to solve page not found 404 - python django?
I have created an app which has the index.html which is the main page and when I run "py manage.py runserver" command it opens the index page. Then I created another app for home page and added urls, created views and everything as far as I know. But when I click "home" it navigates to "http://127.0.0.1:8000/static/home.html" and says "Page not found(404)" and "'home.html' could not be found" I will paste my code below webapp\settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tbs', 'tbs_home' ] webapp\urls.py: urlpatterns = [ path('', include('tbs.urls')), path('tbs_home', include('tbs_home.urls')), path('admin/', admin.site.urls) ] tbs_home\urls.py: urlpatterns = [ path('home',views.home, name='home') ] tbs_home\views.py: def home(request): return render(request, 'home.html') templates\home.html: {% extends 'index.html' %} {% load static%} {% block content%} <h1 style = "font-family:Georgia;font:40px;font-style:normal;">Hi! {{name}}</h1> <form action="add" method="POST"> {% csrf_token %} Enter 1st num : <input type="text" name="num1"><br> Enter 2nd num : <input type="text" name="num2"><br> <input type="submit"> </form> {% endblock %} templates\index.html: This is the part where "home.html" link is given in "index.html" page <div class="col-xs-10 text-right menu-1"> <ul> <li class="active"><a href="{% static 'home.html' %}">Home</a></li> I think I've provided the necessary code snippets, thank you for your help in advance. I should be able to navigate to home page … -
Best way to take a Python program that runs on a terminal and get it running on Django
I have a chess game in python that runs on a basic terminal (user vs ai) and I essentially am trying to figure out the best way to take this terminal program and have it run in a Django project. I chose Django because it was recommended to me as a python based web framework and am also using Docker which should make it easier to get get hosted on a cloud service. I looked into some basic Django tutorials but they were also pretty basic about creating views and back end work. I thought it would just be simple to just run the python code, print to the screen, and take input but it seems more difficult than that. Essentially I would just like my program to run when a user loads the page but it seems more complex than that I am stuck trying to just recreate the terminal in Django. -
TypeError Object of type 'bytes' is not JSON serializable
Code causing the error is in a view: return JsonResponse({"messages": messages}) Contents of messages is: [ { 'from_self': 0, 'item_id': '29587918269741646013775288731697152', 'item_type': 'text', 'text': b'Test', 'thread_id': '340282366841710300949128228322131625374', 'ticket': 32866, 'timestamp': datetime.datetime(2020, 10, 29, 9, 37, 43, tzinfo=<UTC>), 'user_id': '31612701168' } ] I don't understand what part of this is type bytes? Django 3 and Python 3. -
Django model field dynamic choices which calls API
Say I have the following model: class DenyList(models.Model): vm_id = models.CharField(max_length=25) I want to add choices to the vm_id field, however the choices are dynamic via API of an external virtual machine registry system. so I have that done in the following way: class MachineChoices(object): def get_vms(self): if 'makemigrations' in sys.argv or 'migrate' in sys.argv: return [] # calls api, optionally cache, return the vms def __iter__(self): yield from self.get_vms() class DenyList(models.Model): vm_id = models.CharField(max_length=25, choices=MachineChoices()) The above works that: When creating migrations it won't call the API to set all the options in the migration file It is driven from the backend so it works on all model forms so as in django admin. Django admin displays the label instead of the raw value in list display (requires caching implemented in MachineChoices for efficiency) I don't feel this is elegant as it involves hackery to deceive django especially during migrations. I am aware that an alternative is to use autocomplete libraries but I need to customize with django forms. So are there any better ways to do this? -
How to get django model permission in Djano REST API?
In Django template i use like this {% if perms.app_label.can_do_something %} <form here> {% endif %} how to achieve same in Django rest API, how serialize all permission and return through API request -
Reason for form not showing although I added it in the template
I have made a new Comment Model in my Django Project but the form is not showing in the browser although I added the form in the template. Here is the models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField(max_length=300) def __str__(self): return str(self.pk) Here is the views: def comment_create(request, self): post = get_object_or_404(Post, slug=self.kwargs['slug']) user = User.objects.get(user=request.user) c_form = CommentModelForm() context = { 'post': post, 'user': user, 'c_form': c_form, } return context Here is the forms.py class CommentModelForm(forms.ModelForm): body = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Add a comment...'})) class Meta: model = Comment fields = ('body',) Here is the urls.py path('blogs/comment', comment_create, name='comment-post'), Here is the template: <form action="" method="POST"class='ui fluid form'> {% csrf_token %} <input type="hidden" name="post_id" value={{post.id}}> {{ c_form }} <button type="submit" name="submit_c_form" class="">Send</button> </form> -
DoesNotExist at /api/users Token matching query does not exist in Django rest api
I am trying this for so long but have failed everytime. I want to return the particular user associated with the token. The frontend dev will send a request with token on the header and I need to return the particular user after that user has logged in. My view: class UsersListView(ListAPIView): serializer_class = UserListSerializer def get(self, request, *args, **kwargs): user = Token.objects.get(key="token").user return self.list(request, user) and I also, tried this which returns Token matching query does not exist. class UsersListView(ListAPIView): serializer_class = UserListSerializer def get_queryset(self): return User.objects.filter(user =Token.objects.get(key="token").user) My serializer is: class UserListSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' My user model is: class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): """Creating new user and saving the user.""" if not email: raise ValueError('Admin must have a valid email') user = self.model(email=self.normalize_email(email), **kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Creates and saves a new super user""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user # # class User(AbstractBaseUser, PermissionsMixin): """ Custom user model that supports using email instead of username """ email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = … -
Can't figure out how to Parse data from another endpoint using rest_framework
I'm trying to figure out how to parse data directly into a database in Django, i've gone through the rest_framework tutorial. But all can gather from that is, How to create an APIview which displays the data directly from the endpoint, since when i view the DB i can't see the data being stored after i have put the request through. Or i can create some kind of form to post the data through the front-end to the database, but that doesn't make any sense to do that since it would just be dataentry rather then just pulling the related keys. But i can't for the life of me figure out how to just request the data, parse it using an already existing model with the related keys and add that to a database. Feel free to destroy me for this but i really can't find anything in relation to this or maybe i just don't know the right lingo to search. -
Best way to set unique_together for all fields of a django model
I would like to prevent the creation of duplicated rows on some tables of my database. I know one way to do it is setting the unique_together or constraints attribute in the Meta class of the model as a tuple with the names of the fields, but I'd like to know if there's a better way to do it since my models have 30+ fields, so I don't think it would be practical to repeat the names of them again. The way I have it now: class MyModel(models.Model): model_id = models.BigAutoField(db_column="MyModelColumnID", primary_key=True) field1 = models.BooleanField(...) field2 = models.CharField(...) field3 = models. ... . . . field34 = models. ... class Meta: db_table = "MyTableName" unique_together = ( "field1", "field2", "field3", . . . "field34" ) I'm looking for something like unique_together="__all__" or all_unique=True, is this possible on Django? It is important to me to handle this as a database constraint, the get_or_create method won't suffice since it's for an app using multiple threads and making multiple concurrent calls to the database. Thanks ! -
Integrate PDF js web viewer in Django web application
I want to display a ".pdf" document in a Django-based Webapp using pdf-js. The reason for that is to have access to the current pdf page number as mentionned in this stack overflow exchange. I was able to use the default pdf-js viewer as described in this tutorial. However, I could not integrate it with my Django webapp. When I use a similar scheme in the Tutorial, I get the following error: The current path, web/viewer.html, didn't match any of your URL patterns. When I add the following view : def pdf_View(request): return render(request,'static_files/web/viewer.html') Using this view, the pdf is not displayed, only the buttons (next, previous page, zoom in,out ...). -
how to add element in django list
I'm confused with how django adds elements to a list. consider the following: def add(request): if request.method == "POST": form = NewTaskForm(request.POST) if form.is_valid(): task = form.cleaned_data["task"] request.session['tasks'].append(task) # request.session['tasks'] += [task] return HttpResponseRedirect(reverse("tasks:index")) else: return render(request, "tasks/add.html",{ "form": form }) return render(request, "tasks/add.html",{ "form": NewTaskForm() }) if we add a print statement after request.session['tasks'].append(task) we get a list: ['check email'] we also get the same list if we comment the append line and use the correct way with += However, on the redirect to task/index the first way shows an empty list and the second way shows the list that's expected. Why? Whats going on? -
How can I create and edit user profiles in django?
I'm trying to create a profile when a new user is created, but I'm very new to this and I'm very lost. I'm not sure if I'm even creating a profile at all, and if I am I can't figure out how to let the user edit it once it's created. Any help is appreciated. I'm not fully understanding how to link a profile to the user and I'm having a hard time understanding signals... also apologies for the terrible documentation, I haven't made anything consistent in the least forms.py class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('email',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('email',) class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['bio','specialty', 'style',] class EditProfileForm(ModelForm): class Meta: model = Profile fields = ('bio', 'specialty', 'style',) models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class Profile(models.Model): user = models.OneToOneField('accounts.CustomUser', on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) specialty = models.CharField(max_length=150, blank=True) style = models.CharField(max_length=150, blank=True) def create_profile(sender, instance, created, **kwargs): if created: user_profile = Profile.objects.create(user=instance) post_save.connect(create_profile, sender=CustomUser) signals.py @receiver(post_save, sender=User) def save_profile(sender, instance, … -
Proxy Model Customization
I have proxy models for related types. The problem is ListView and DetailView connection. Courses has all types of course, each course must have related type's URL. Here is full structure of my sample code, ( models, views, urls, template) #models.py COURSE_TYPES = ( ('a', 'Appetizer'), ('s', 'Soup and Salad'), ('m', 'Main Course'), ('d', 'Dessert') ) class Course(models.Model): type = models.CharField(max_length=1, choices=COURSE_TYPES) name = models.CharField(max_length=100) slug = models.SlugField(blank=True, unique=True) thumbnail = models.ImageField(null=True, blank=True) description = models.TextField(max_length=1000) def get_absolute_url(self): return reverse('course', kwargs={'slug':self.slug}) class AppetizerManager(models.Manager): def get_queryset(self): return super(AppetizerManager, self).get_queryset().filter( type='a') class MainManager(models.Manager): def get_queryset(self): return super(MainManager, self).get_queryset().filter( type='m') class Appetizer(Course): objects = AppetizerManager() class Meta: proxy = True class Main(Course): objects = MainManager() class Meta: proxy = True #views.py class CourseListView(ListView): model = Course template_name = 'courses.html' class AppetizerDetailView(DetailView): model = Appetizer template_name = 'appetizer_detail.html' class MainDetailView(DetailView): model = Main template_name = 'main_detail.html' #urls.py urlpatterns = [ path('courses/', views.CourseListView.as_view(), name='courses'), path('appetizer/<slug:slug>/', views.AppetizerDetailView.as_view(), name='appetizer'), path('main/<slug:slug>/', views.MainDetailView.as_view(), name='main'), ] #courses.html <h1>Courses</h1> {% for course in object_list %} <ul> <li><a href="{{ course.get_absolute_url }}">{{ course.name }}</a></li> </ul> {% endfor %} How can I edit my code for this purpose properly? Thanks. -
Django ValueError: Need 3 values to unpack in for loop; got 2. How to unpack zipped data in template?
I was trying to display some zipped data in a table within a Django template and kept getting this error: ValueError: Need 3 values to unpack in for loop; got 2. It contains a dictionary and a list. I've tested the same code in idle and it prints out fine. What am I doing wrong? Thanks in advance! Here's what i did for Django: views.py labels = [1, 4, 5] mydic = {'a': ['a','b','c'], 'b':['e','f','g'], 'c':['l','m','n']} dic_items = mydic.items() zipped = zip(dic_items, labels) base.html <table> {% for (k, v), l in zipped %} <tr> <th>Label{{ l }}</th> <td>{{ v.0 }}</td> <td>{{ v.1 }}</td> <td>{{ v.2 }}</td> </tr> {% endfor %} </table> In idle with the same code it prints out: a ['a', 'b', 'c'] 1 b ['e', 'f', 'g'] 4 c ['l', 'm', 'n'] 5 I've also tried: {% for k, v, l in zipped %}; {% for k, v in dic_items %}{% for l in labels %}; {% for k,v in dic_items, for l in labels %}, etc. None of them worked. I suspect it might have something to do with the label doesn't contain the same amount of items as v? But it is the same amount as … -
How can I remove the blue glow arround the fields?
Right now i am just trying to remove some king of blue borders which appears when we start writing something in the field. As shown in image, I want to remove that blue glow. and as you can see in the image there is an image input also , i want to change that in image icon, How can i change that in a image icon instead of browse.. button Inside form.py I defined the fields classes : class Meta: model = Blog fields = ('tag',"title","image_data","body",) widgets ={ 'title' : forms.TextInput(attrs={'class':'blogtitle'}), 'body': forms.Textarea(attrs={'class':'editable medium-editor-textarea blogbody'}), 'image_data': forms.FileInput(attrs={'class':'blogimage'}) } custom.css .blogtitle:focus{ font-size:40px; text-align: left; border-top: 0px; border-right: 0px; border-left: 0px; border-bottom-style: groove; outline:none; } .blogimage{ style:fa fa-image; } If more information or code is require than tell me in comments session I will update my question with that information. -
Using Ajax to automate Like button with refreshing the page
I am trying to add Ajax to my like button to avoid refreshing everytime along with updating the count automatically as well but it is not working properly and the page keeps refreshing for some reason: So when I was trying to debug my code in Google Chrome Console Log I keep receving this error: 127.0.0.1/:96 Uncaught ReferenceError: $ is not defined and DevTools failed to load SourceMap: Could not load content for chrome-extension://gannpgaobkkhmpomoijebaigcapoeebl/bundle.min.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME for some reason. I am not an expert in JS but I am trying to understand what is happening here. So my template for the like button here it is: <form action="{% url 'blog:like-post' %}" method="POST" class="like-form" id="{{post.id}}"> {% csrf_token %} <input type="hidden" name="post_id" value='{{post.id}}'> <button type="submit" class="like-btn{{post.id}}"> {% if user not in post.liked.all %} Like {% else %} Unlike {% endif %} </button> <div class="like-count{{post.id}}">{{ post.num_likes }} Likes</div> </form> Here is the Script <script> $( document ).ready(function() { let display = false $('.like-form').submit(function(e){ e.preventDefault() const post_id = $(this).attr('id') const likeText = $(`.like-btn${post_id}`).text() const trim = $.trim(likeText) const url = $(this).attr('action') let res; const likes = $(`.like-count${post_id}`).text() const trimCount = parseInt(likes) $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), …