Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am repeatedly getting [NameError: name '_mysql' is not defined in] in pythonanywhere where i deployed my django web app?
I have installed requirements.txt[mysql, django etc].created the database . Migrated and viewed the mysql(with the same credentials as in the settings) on the pythonanywhere shell. all is fine. All the tables are present but i cant find what is wrong. Please help with this error. these are the related files:- (django 3.1.1 python3 3.8.0 mysql Ver 14.14 Distrib 5.7.27, for Linux (x86_64) using EditLine wrapper) auto generated wsgi.py import os import sys # # assuming your django settings file is at '/home/proj/mysite/mysite/settings.py' # # and your manage.py is is at '/home/proj/mysite/manage.py' path = '/home/proj/proj' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'project3.settings' # # then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() database settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'proj$proj', 'USER': 'proj', 'PASSWORD': '*****', 'HOST': 'proj.mysql.pythonanywhere-services.com', } } errors log 2020-09-04 17:07:32,532: NameError: name '_mysql' is not defined 2020-09-04 17:07:32,532: File "/var/www/proj_pythonanywhere_com_wsgi.py", line 39, in <module> 2020-09-04 17:07:32,532: application = get_wsgi_application() 2020-09-04 17:07:32,532: 2020-09-04 17:07:32,532: File "/home/proj/proj/vad_env/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-09-04 17:07:32,532: django.setup(set_prefix=False) 2020-09-04 17:07:32,533: 2020-09-04 17:07:32,533: File "/home/proj/proj/vad_env/lib/python3.8/site-packages/django/__init__.py", line 24, in setup 2020-09-04 17:07:32,533: apps.populate(settings.INSTALLED_APPS) 2020-09-04 17:07:32,533: 2020-09-04 17:07:32,533: File "/home/proj/proj/vad_env/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate 2020-09-04 17:07:32,533: app_config.import_models() 2020-09-04 17:07:32,533: 2020-09-04 17:07:32,533: File "/home/proj/proj/vad_env/lib/python3.8/site-packages/django/apps/config.py", … -
How to save json data that i got from api call in the database while working in django?
[{'year': '2014', 'petroleum_product': 'Diesel', 'sale': 901393}, {'year': '2018', 'petroleum_product': 'Diesel', 'sale': 813399}] If I have JSON data as above how do I save it in the database using Django? I want the year, petroleum_product, and sale to be in the same table. Do I have to first create a model and loop through the data and store it? (If so how can it be achieved?) Or is there a shortcut way of doing it? -
How to handle user data (via browser) that was entered into the webapp
I am new to django, however I wrote my first project and am having trouble getting it started. I transferred the project to another computer for testing. My web application is built for an intranet. So, the project is up and running, I can log in from another computer and everything also works, but when I enter to web app, the user on whose pc where project is running is authorized (one of the authorization conditions is to get a Windows username for verification), I use request.META['USERNAME'] for this. So, it's an essence of the problem: after transferring, i become META data of the PC on which the project is running, from the client I only receive their IP. Please tell me how to be, and forgive my English. Thaks and have a nice day! -
Django bulk_create for many2many field on MySQL
I have the model: class Content(models.Model): can_see = m.ManyToManyField('users.User',blank=True,related_name='can_see') can_edit = m.ManyToManyField('users.User',blank=True,related_name='can_edit') can_delete = m.ManyToManyField('users.User',blank=True,related_name='can_delete') text = m.CharField(max_length=160, blank=True) name = m.CharField(max_length=160, blank=True) I am trying to create many "Contents" by using bulk_create and making a user choose which users can manage contents by filling the fields as this: def handle_csv(request): if request.method == 'POST': form = UploadCSVForm(request.POST, request.FILES) if form.is_valid(): data_can_see = form.cleaned_data['can_see'] data_can_edit = form.cleaned_data['can_edit'] data_can_delete = form.cleaned_data['can_delete'] csvfile = TextIOWrapper(request.FILES['csvfile'].file, encoding='utf-8') table = csv.reader(csvfile) created = Content.objects.bulk_create([Content(text=data[0],name=data[1]) for data in table]) ... return render(request, 'importing/success.html') I now wish to add the manytomany relation to give to the selected users the permissions I want on the Content objects, but I can't set m2m relations in a bulk_create. I tried this: for content in created: content.can_see.set(data_can_see) content.can_edit.set(data_can_edit) content.can_delete.set(data_can_delete) But it's not working since it says the object needs to have an ID before the m2m relation can be set, and I can't understand why the objects list I have have no ID. I think I am not understanding how to create multiple objects with bulk_create. I also tried to add a content.save() in the above mentioned loop, but that is resulting in a double set of objects being created, … -
how to convert Django object into json?
Hi I'm trying to convert a Django queryset object into JSON but every time I try do it with the python JSON module I get this error: "TypeError: Object of type QuerySet is not JSON serializable". Here is the Django object: titles = Queries.objects.values('Topic').distinct(). and here is what it returns `<QuerySet [{'Topic': 'Phone or Web'}, {'Topic': 'Time or Money'}, {'Topic': 'Power or Wisdom'}, {'Topic': 'Luxure or Camp!'}]>. Now even when I try to use the django serilizers to try to solve this problem I get this error: "AttributeError: 'dict' object has no attribute '_meta'." Can anyone help me solve this? Here is my code for both situation. code of the django serializers situation: from django.shortcuts import render from django.http import HttpResponse from .models import Queries import json from django.core.serializers import json from django.core import serializers def data_json(): titles = Queries.objects.values('Topic').distinct() titles_json = serializers.serialize('json', titles) with open('topic.json', 'w') as file: data = json.dumps(titles_json) print(data, file=file) print(titles) def index(request, query_title): queries = Queries.objects.all() page = Queries.objects.filter(Topic=str(query_title)) # print(page) data_json() return render(request, 'Querie/index.html', {'queries': page}) and here how my code looked like when I was using the regular json module so the data_json funtion was like this: import json def data_json(): titles = … -
How to get rid of label generated with django forms
aim: to just have 2 input boxes without a label ontop problem: using django form app a label appears ontop of input boxes: see image. my models.py code is: # Create your models here. class Customer(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) def __str__(self): return self.first_name + ', ' + self.last_name and my 0001_inital.py is # Generated by Django 2.1.7 on 2019-11-01 19:21 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Customer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=200)), ('last_name', models.CharField(max_length=200)), ], ), ] -
Django - Save audio file
I'm using this for images: newimage = ContentFile(base64.b64decode(b64image), name='{}.{}'.format(image_name, 'jpg')) But when I try to do the same with audio: newaudio = ContentFile(base64.b64decode(b64audio), name='{}.{}'.format(audio_name, 'mp3')) I get this error: Media resource .../media/audio/1471985664.mp3 could not be decoded, error: Error Code: NS_ERROR_DOM_MEDIA_METADATA_ERR (0x806e0006) Thank you for any suggestions -
Although it works in css on other pages, it doesn't work on category page Django
I built blog site. Although it works in css on other pages, it doesn't work on category page. What can i do? Codes here STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') def category_detail(request, cats): category_posts=Blog.objects.filter(category_id=cats) context = { 'cats': cats, 'category_posts': category_posts, } return render(request, 'post/category.html',context) from django.conf.urls.static import static from django.urls import include, path from blog.views import blog_detail, category_detail from home.views import home_view, about_view urlpatterns = [ url(r'^adminerdo/', admin.site.urls), url(r'^$', home_view), url(r'^about/$', about_view), url(r'^(?P<slug>[\w-]+)/$', blog_detail , name= 'detay'), url(r'^category/(?P<cats>[\w-]+)/$', category_detail, name='category'), ] urlpatterns += static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) -
Topics arent being added
Im pretty new to both python and django , currently reading the Python Crash Course by Eric Matthes . Im trying to code a simple learning log , but im having some issues adding new topics using the django form . Heres the code: urls.py: from django.urls import path , re_path from . import views urlpatterns = [ #Home page path('', views.index, name='index'), path('topics/', views.topics , name='topics'), re_path(r'^topics/(?P<topic_id>\d+)/$' , views.topic , name = 'topic'), re_path(r'^new_topic/$' , views.new_topic , name = 'new_topic') ] app_name = 'learning_logs' part of view.py: def new_topic(request): if request.method != 'POST': form = TopicForm else: form = TopicForm(request.POST) if form.is_valid(): form.save return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form' : form} return render(request , 'learning_logs/new_topic.html' , context) new_topic.html: {% extends 'learning_logs/base.html' %} {% block content %} <p>Added a new topic:</p> <form action="{% url 'learning_logs:new_topic' %}" method="post"> {% csrf_token %} {{form.as_p}} <button name='submit'>add topic</button> </form> {% endblock content %} topics.html: {% extends 'learning_logs/base.html' %} {% block content %} <p>Topics</p> <ul> {% for topic in topics %} <li><a href="{% url 'learning_logs:topic' topic.id %}">{{topic}}</a></li> {% empty %} <li>No topics have been added yet.</li> {% endfor %} </ul> <a href="{% url 'learning_logs:new_topic' %}">Add a new topic:</a> {% endblock content %} -
how to send Django view response to modal?
Im trying to create note detail in modal popup window. Here is the modal invoke anchor tag <a class="fa fa-pencil" data-toggle="modal" href="{% url 'post_detail_view' %}" data-id="{{ todo_item.content }}" data-target="#modal" title="edit item" data-tooltip></a> here is the view function in views.py: def post_detail_view(request, content): all_items1 = TodoItem.objects.get(content=content) return render(request, 'todo.html', {'all_items1': all_items1}) here is my urls.py : path('post_detail_view/<str:content>/', views.post_detail_view, name='post_detail_view'), This is my modal code in todo.html <div class="modal-dialog" role="document"> <div class="modal-content"> <form action="/addTodo/" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabe2">Edit Info</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% if all_items1 %} <label for="content">Title :</label><br> <p>{{ all_items1.content }}</p> <p>{{ all_items1.data }}</p> <input type="text" id='c' name="content" value="{{ all_items1.content }}"/><br> <label for="data">Description :</label><br> <textarea id="data" rows="4" cols="50" value="">{{ all_items1.data }}</textarea> <br> <label for="tags">Tags :</label><br> <input type="tags" name="tags" value="{{ all_items1.tags }}"/><br> <a href="{{ all_items1.file.url }}"> {% load static %} <img src="{% static 'ico.png' %}" style="width:30px;height:30px" alt="download"> </a> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> {% endif %} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save changes</button> </div> </form> </div> </form> </div> This code is not working. I can see modal is popping up but no data is displayed. I'm still learning Django. Can someone please … -
Populate a Django form field with data from a model
I'm have been struggling on this for 2 days, really. I want to populate Timesheet form field from Employees model as a select field / dropdown list. Here are my files and I tried so far. MODEL.PY class Employees(models.Model): # MONTHLY = 'MONTHLY' # SEMIMONTHLY = 'SEMIMONTHLY' # BIWKEEKLY = 'BIWKEEKLY' # WEEKLY = 'WEEKLY' # DAILY = 'DAILY' PAY_PERIODS = [ ('Monthly', 'Monthly'), ('Bi-weekly', 'Bi-weekly'), ('Weekly', 'Weekly'), ('Daily', 'Daily'), ] user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) is_active = models.BooleanField(default=True, verbose_name='Employee is actives') first_name = models.CharField(max_length=50, verbose_name='First Name.', null=True, blank=False) middle_name = models.CharField(max_length=50, verbose_name='Middle Name or Initials.', null=True, blank=True) last_name = models.CharField(max_length=50, verbose_name='Last Name.', null=True, blank=False) full_name = models.CharField(max_length=50, null=True, blank=True) phone = PhoneField(blank=True, null=True) email = models.EmailField(max_length=150, blank=True, null=True) state = USStateField(null=True, blank=True) street_address = models.CharField(max_length=150, blank=True, null=True, verbose_name='Street Address.') zip_code = models.CharField(max_length=50, blank=True, null=True, verbose_name='Zip Code.') hourly_rate = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) pay_frequency = models.CharField(max_length=100, choices=PAY_PERIODS, blank=True) hire_date = models.TimeField(auto_now_add=True) def __str__(self): return self.full_name def save( self, *args, **kwargs ): self.full_name = f'{self.first_name} {self.middle_name} {self.last_name}' super().save( *args, **kwargs ) class Timesheet(models.Model): """A timesheet is used to collet the clock-ins/outs for a particular day """ employer = models.ForeignKey(User, on_delete=models.CASCADE, null=True) full_name = models.CharField(max_length=100, null=True, blank=False, verbose_name='Select YOUR Name') start_date = … -
Why does Django perform UPDATE before INSERT when PK is None?
I've got a model with a UUID primary key: id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False, null = False, blank = False, help_text = 'The unique identifier of the Node.' ) The issue I'm trying to solve is that Django always seems to try an Update before an Insert. The Django Docs seem to be explicit on what the behavior should be: If pk is None then it will try an INSERT first, otherwise an UPDATE. When I create a ModelInstance, it autopopulates id with a UUID, so it's not none. Is there a way I can make it not do this? Regardless, even if I set id and pk to None on create, it still does an UPDATE first: my_totally_new_node = Node(data = data, id = None, pk = None) my_totally_new_node.id > None my_totally_new_node.pk > None reset_queries() my_totally_new_node.save() connection.queries > [{'sql': 'UPDATE "connection_p...::uuid", 'time': '0.002'}, {'sql': 'INSERT INTO "connect...::bytea)", 'time': '0.001'}] To summarize: Is there a way I can cause default behavior for the ID field to be not to populate on create, but to still populate on Save? Any ideas why Django isn't following the documented behavior when pk is None and is … -
HTML order list mess up with un-order list in django template
I have some data about users such as first name, last name, and email. Now I am trying to view it on the browser. But its ordering number is totally odd. My Template Code <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>User List</title> <link rel="stylesheet" href="{% static "css/mystyle.css" %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> </head> <body> <div class="container"> <h1> Here is yours users: </h1> {% if user_info %} <ol> {% for user in user_info %} <li>{{ user.first_name }}</li> <ul> <li>First Name: {{ user.first_name }}</li> <li>Last Name: {{ user.last_name }}</li> <li>Email: {{ user.email }}</li> </ul> {% endfor %} </ol> {% endif %} </div> </body> </html> My View Code def userlist(request): user_info = UserInfo.objects.all() content = { "user_info":user_info, } print("User List") return render(request, "practiceApp/user-list.html", context=content) And My Browser enter image description here -
Accidentally deleted django project database, now I cannot access mysql
I am developing a project on Django, and was working on a project named project, which I deleted via DROP DATABASE *project* to start over from scratch, thinking I could simply create a new one via CREATE DATABASE *project*. The problem I'm having is that now, no matter what command I run: python manage.py migrate mysql (sudo) mysql -u root I get the same error: ERROR 1049 (42000): Unknown database '*project*' So, I cannot even access mysql to create a new database. Any ideas? -
How to post out of model fields django forms
How to post a checkboxFiled without django user.contrib fields in forms forms.py class Meta: model = User fields = ("user_type","email","password1","password2",'is_email_promotions') widgets = {'is_email_promotions':forms.CheckboxInput()} #it is out of user model also not related any model -
Django - nested query to reply on comments
I have the following two models to make it possible that users can answer/reply onto a comment class Comment(models.Model): objects = None id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=1000, blank=False) published_date = models.DateTimeField(auto_now_add=True, null=True) class Comment_Answere(models.Model): objects = None id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=1000, blank=False) published_date = models.DateTimeField(auto_now_add=True, null=True) Creating a reply works like a charm but I don't know how I properly pull all answers/reply's for a specific comment at my template/View def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) list_comments = Comment.objects.get_queryset().filter(post_id=pk).order_by('-published_date') # not sure how the comment_answers query has to look like comment_answers = Comment_Answere.objects.filter(post_id=pk).order_by('-published_date') paginator = Paginator(list_comments, 10) page = request.GET.get('page') comments = paginator.get_page(page) args = { 'post': post, 'comments': comments, 'comment_answers': comment_answers, } return render(request, 'post_detail.html', args) At my template I later than do something like this: {% for comment in comments %} {% for comment_answer in comment_answers %} {% endfor %} {% endfor %} Would be awesome if smb. could give me a hint on how I have to stack comments and there reply's together as I currently have all reply's … -
Cannot run paho mqtt client -> “ImportError: cannot import name 'client' "
I installed Eclipse Paho, clone the repository and install whit these comands: pip install paho-mqtt git clone https://github.com/eclipse/paho.mqtt.python cd paho.mqtt.python python setup.py install it's ok. but when i run the project, i have this error: File "/home/andrius/Scrivania/django_python/CalendarEsit/Calendar/__init__.py", line 1, in <module> from . import aws_iot File "/home/andrius/Scrivania/django_python/CalendarEsit/Calendar/aws_iot.py", line 10, in <module> from paho.mqtt.client import client ImportError: cannot import name 'client' -
How to fix ? IntegrityError at /profiles/profile/ NOT NULL constraint failed: profiles_userprofile.user_id
I am using Django 3.0.3 and python 3.8.5 I am running through an error :IntegrityError at /profiles/profile/ NOT NULL constraint failed: profiles_userprofile.user_id Can you anyone tell where I am actually making mistake ? I am trying with the code given. profile/models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(("First Name"), max_length=50) last_name = models.CharField(("Last Name"), max_length=50) profile_pic = models.ImageField(upload_to='Displays', height_field=None, width_field=None, max_length=None) phone_number = models.IntegerField(("Phone Number")) email = models.EmailField(("Email Address"), max_length=254) city = models.CharField(("City"), max_length=50) bio = models.CharField(("Bio"), max_length=50) def __str__(self): return self.email def get_absolute_url(self): return reverse("profiles:userprofile_detail", kwargs={"pk": self.pk}) def create_profile(sender, **kwargs): if kwargs['created']: profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) profiles/forms.py class Meta: model = UserProfile fields = ("profile_pic","first_name","last_name",'email',"phone_number","bio","city",) def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) self.fields['first_name'].label = 'First Name ' self.fields['last_name'].label ='Last Name ' self.fields['profile_pic'].label = 'Profile Picture' self.fields['phone_number'].label = 'Phone No. ' self.fields['bio'].label ='Bio' self.fields['city'].label ='City' self.fields['email'].label = 'Email Address' profiles/views.py class UserProfileCreateView(CreateView): redirect_field_name = 'profiles/userprofile_detail.html' form_class = UserProfileForm model = UserProfile def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["created"] = 'created' return context class UserProfileDetailView(DetailView): model = UserProfile class UserProfileUpdateView(UpdateView): redirect_field_name = 'profiles/userprofile_detail.html' form_class = UserProfileForm model = UserProfile profiles/userprofile_form.html {% extends 'base.html' %} {% block content %} {% if 'created' in created %} <a href ="{% url 'profiles:update' pk=userprofile.pk … -
SMTP data error.550 b the form address doesn't match a verified sender identity
I am trying to send mail in my django project. Whenever I try to send email it shows the error like the screenshot. here I generated API in sendgrid and used it in my project. And I also disable two step verification in my email and allow less secure app enable. My setting is : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = "this is the API_KEY that I generated in sendgrid" EMAIL_PORT = 587 EMAIL_USE_TLS = True -
Django Channel Error wile building a chat application
I am trying to build a chat application using Django and channel. But I am getting not able to get my view file (room.html) My main project name is "techChat" and I have a app called "chat" I ma trying all this code from :- https://channels.readthedocs.io/en/latest/tutorial/part_2.html When i enter the lobby name i get page not found. I also have the asgi file if you take a look at my file structure whose img is below. Help! My Code views.py :- chat/urls.py (App urls file):- techChat/urls.py (main project urls file) My room.html template file:- My index.htm file template My Index Page output :- Now when I Enter the "lobby" in the text box I get Page Not Found Error! -
i have a problem with load lazy pagination in my django website
this is my views.py in the views.py i have some filter like this: def home8(request): context = {} qs=Post.objects.all().order_by('-pub_date') city = request.GET.get('city') area= request.GET.get('area') def is_valid_queryparam(param): return param != '' and param is not None if is_valid_queryparam(city): qs1=qs.filter(city=city) if is_valid_queryparam(area): qs1=qs.filter(area=area) paginator = Paginator(qs1, 8) page_request_var = "page" page = request.GET.get(page_request_var) try: paginated_queryset = paginator.page(page) except PageNotAnInteger: paginated_queryset = paginator.page(1) except EmptyPage: paginated_queryset = paginator.page(paginator.num_pages) context['queryset'] = paginated_queryset return render(request, 'index.html',context) and in my index.html i set this code to loadlazy pagination by scroll {% if queryset %} {% for post in queryset %} <div class=" col-12 col-md-6 col-lg-4 infinite-item px-1 mb-3" id="col"> <div class="card " id="card"> <div class="card-horizontal "> <a href="{{ post.get_absolute_url }}"> <img src="{{ post.image1.url }}" class="card-img-top " /> </a> <div class="card-body " > <h5 class="card-title text-truncate">{{ post.title1 }}</h5> <span class="text-muted">{{post.whenpublished}}</span> </div> </div> <div class=" card-footer"> <div class="row" id="place"> <span class="text-truncate place" ><i class="fa fa-map-marker" aria- hidden="true"></i> {{post.city}} | {{ post.area }}</span> <span class="price float-left mr-auto" >{{ post.after_off1|intcomma }}<span class="org"> </span></span> </div> <div class="row"> <div id="badge "> <span class="badge badge-pill float-right " style=""><span class="percent"> ٪{{ post.off1 }} </span> </span> </div> {% if post.original_amount1 %} <s class=" org-price text-muted float-left mr-auto" >{{ post.original_amount1|intcomma }}<span class="off"> </span></s> {% endif %} … -
How to append img src and it's url in jquery for ajax view in django?
I want to use ajax where user can post image or text . But first i have to show ajax list which i don't know how to. this is the post i want to append to jquery for ajax view. It has image of the author of the post and the title and img posted by user. {% for object in object_list %} <div class="post-card" > <p> <img class="rounded-circle profile-image" src="{{ object.author.profile.image.url }}"> <span class="auth-span"><b>{{ object.author }} </b><i class="fa fa-check-circle"></i> </span> <span class="date-span">{{ object.date_created|timesince }} ago</span> </p> <p><a href="{% url 'detail' object.id %}" class="title">{{ object.title }}</a></p> <div> {% if object.Image %} <p><a href="{% url 'detail' object.id %}"><img src="{{ object.Image.url }}" class="img-fluid" alt="Responsive image" ></a></p> {% endif %} </div> <div class="icon-div" > <p class="icon" style="mt"> <i class="fa fa-comments"></i> <i class="fa fa-heart" ></i> <i class="fa fa-share-square"></i> <i class="fa fa-eye"></i> </p> </div> </div> {% empty %} {% if request.GET.q %} <p style="color: var(--text-color);margin-top: 20px;margin-left: 250px;">NO tweets found</p> {% else %} <p>NO tweets yet.</p> {% endif %} {% endfor %} I have already setup serializers and others and it worked fine. Every img and post is working fine without ajax . So all i want to know is the method to append the elements … -
How to Display value in Drop-down in Django Template?
I am trying to display value in dropdown from databse, and I am getting value through id, but it's displaying only one value which is save in my database. But i want all dropdown value. Please let me know how i can display all values in dropdown. Here is my models.py file where dropdown code is written... TYPES = [ ('A', 'Active'), ('D', 'Not Active'), ] and these values are savingin another modes using choices,and A and D are storing in my Database. Here is my views.py file.. def getdata(request, id): display=Mymodel.objects.filter(pk=id).first() context={'display':display} return render(request, 'page.html', context) and here is my page.html file where I am displaying data in dropdown.. <select name='types'> <option value="{{display.types}}">{{display.get_types_display}} </option> </select> but this is displaying in dropdown Active values only, but i want both values, I want to edit data using this form. ANd if A is saved in my database then in default Active should be select and if D is saved in my database then Not Active should be select in default, rest values should be display in dropdown. -
Unexpected models generated by `model_bakery` in Django unit test
I've used model_bakery (and before that, model_mommy) a fair amount, so this bug is making me feel like I'm taking crazy pills. from model_bakery import baker # BaseTestCase inherits from django.test.TestCase # it creates a tenant object assigned to self.tenant in BaseTestCase.setUp class TestSchemas(BaseTestCase): def setUp(self): super().setUp() self.assertEqual(Tenant.objects.count(), 1, "This one passes") self.assertTrue( Tenant.objects.filter(pk=self.tenant.pk).exists, "The only tenant I expect is here, persisted, and correct." ) self.campaign_schema = baker.make( "Schema", tenant=self.tenant, ) # This is the failing assert self.assertEqual( Tenant.objects.count(), 1, "This case fails. I _expect_ no additional Tenant objects to have been created." ) from django.db import models class Tenant(models.Model): tenant_xid = models.BigIntegerField("Tenant ID", primary_key=True) class Schema(models.Model): form_schema_xid = models.BigIntegerField("schema ID", primary_key=True) tenant = models.ForeignKey( Tenant, models.CASCADE, db_column="tenant_xid", related_name="schemas" ) As indicated in the assertion messages, the setUp method starts off how I expect, with one Tenant object. I use baker to create a Schema. I expect the schema to use the existing Tenant, yet it seems to be creating a second one instead, as the final assert shows AssertionError: 2 != 1 I've simplified the case down to the bare minimum, but I'm struggling to understand what's happening. There aren't any overridden methods on the models, the BaseTestCase isn't … -
django rest framework - How can I edit the header with drf_yasg?
I develop an API with DRF and I implemented swagger in It throught drf_yasg. When I use swagger UI to test my endpoints, the basic header is not good enough. I need to add an acceptance parameter wich is the version of my API.