Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can not display Django form
I am trying to make a contact form but it's html template does not see {{ form }} template. What am I doing wrong? Where is an error. My code is attached above. models.py class Contact(models.Model): listing = models.CharField(max_length=200) listing_id = models.IntegerField() name = models.CharField(max_length=200) email = models.EmailField() phone = models.CharField(max_length=100) message = models.TextField(blank=True) file = models.FileField(upload_to='files/%Y/%m/%d/', blank=True) contact_date = models.DateTimeField(default=datetime.now, blank=True) user_id = models.IntegerField(blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('listings', kwargs={'pk': self.pk}) In views.py file class ContactCreate(CreateView): model = Contact fields = ['name','email','phone','file'] form_class = ContactForm redirect_field_name = '/' class ContactUpdate(UpdateView): model = ContactForm fields = ['name','email','phone'] urls.py from django.urls import path from . import views urlpatterns = [ path('listings/<int:pk>/', views.ContactCreate.as_view(), name='contact-create') ] html <form action="{% url 'contact-create' pk=listing.pk %}" method="post"> {{ form }} {% csrf_token %} <input type="submit" value="Send" class="btn btn-block btn-secondary"> </form> Could you help me out, please -
Getting Error: MultiValueDictKeyError at /__debug__/render_panel/ 'store_id'
I'm trying to access debug_toolbar and this error shown up MultiValueDictKeyError at /debug/render_panel/ 'store_id' -
Django: Adding Context From View Throws Module Not Found Error
I am trying to add context to a Django template by calling a function from another module. The code in the other module works, but when called from the get_context_data function inside the view class, it throws a module not found error - not finding the module of one of the function's dependencies. I have getplex.py that works fine when run in Python Console: from plexapi.myplex import MyPlexAccount # [PLEX CREDENTIALS] servername = 'xxxxxxx' username = 'plex@xxxx.com' password = 'xxx-yyy-yyy' baseurl = 'http://111.0.1.1:32400' try: account = MyPlexAccount(username, password) plex = account.resource(servername).connect() print('Plex connected') login_status = True except: print('Could not reach plex') login_status = False def new_tv(): shows_list = [] new_tv = plex.library.section('TV Shows').recentlyAdded() shows = [show for show in new_tv] for show in shows: summary_item = show.grandparentTitle + ' - ' + show.parentTitle shows_list.append(summary_item) new_seasons = [] for i in shows_list: if i not in new_seasons: new_seasons.append(i) if len(new_seasons) == 5: break return new_seasons I have views.py where I am trying to add the output of new_tv() to the context: from django.views.generic import TemplateView import plexigram.getplex from plexigram.getplex import new_tv class HomePageView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): tv_shows = new_tv() context = dict() context['new_tv'] = tv_shows return context I … -
How to make django forms change as user enters information
I'm trying to make a django form that allows users to make some selections and then, depending on what selections they make, shows them the rest of the options that make sense. Here's an example of the logic I'm thinking: 1. Users selects their gender (radio button) [magic happens] 2(a). Male users select their clothing options - trousers, shorts, shirt, jacket 2(b). Female users select their clothing options - skirt, trousers, shorts, dress, shirt, jacket So my big question here is how do I make the magic happen so 2(a) or 2(b) only shows after the selection in (1) has been made? P.S. I have some code, but it doesn't really interact with the [magic] - should I include it or not? -
Is Django ORM Supports Snowflake and How
I want to connect snowflake db with Django and Use the Django ORM, I couldnt find database settings for the snowflake -
Is it possible to do a redirect on class based views
Is it possible to do a redirect on class based views. Like i have other contexts to return but if assuming I have blocked the user, i want to redirect to home page and make it such that they cannot view the detail page. Sorry! am new to class based views class DetailBlogPostView(BlogPostMixin,DetailView): template_name = 'HomeFeed/detail_blog.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog_post=self.get_object() blog_post.save() context['blog_post'] = blog_post account = Account.objects.all() context['account'] = account if blog_post.author in self.request.user.blocked_users.all(): return redirect('HomeFeed:main') return context -
How to change hairstyle in user photo(just like in snapchat) to show various style in a salon app?
I am working on a salon app in Django3.1 and I want to add a feature in it. I want to take input a photo from the user and according to the style chosen I want to change the hairstyle in the photo. But I don't know how to do it, do I need to do it in Django-REST? -
only staff user should post a product in django
hi everyone i am working with an ecommerce app where everone who login can post their product but i want only staff user to post the product when the staff user is true: my models.py is: class User(AbstractBaseUser): email = models.EmailField(max_length=255 ,unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) #can login staff = models.BooleanField(default=False) #staff user non super user admin = models.BooleanField(default=False) #superuser time_stamp = models.DateTimeField(auto_now_add=True) #USERNAME_FIELD and password are required by default USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] object = UserManager() def __str__(self): return self.email def get_full_name(self): if self.full_name: return self.full_name return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self , app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active and my views.py for creating product is: class ProductCreateView(LoginRequiredMixin,CreateView): model = Product template_name = 'product-form.html' fields = ['title', 'price' , 'status' , 'size' , 'color', 'image' , 'description'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) and also i want that if staff is true then navbar show create product for user. rightnow if user is authenticated navbar show him to post the product {% if request.user.is_authenticated %} <li class="nav-item {% if request.path == … -
Django app share cookies with a chrome extension
I want to be able to set cookie on the client side with the Django app. So I can use as authentication for my API to be use for chrome extension. But I've been problems in finding most updated answer for using them and how to access them. -
How to get the related objects from a queryset?
models class Question(DateTimeEntity): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_questions') question = models.CharField(max_length=300) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='questions') class Answer(DateTimeEntity): question = models.ForeignKey(Question,on_delete=models.CASCADE, related_name='ques_answers') answer = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='answers') Here in the product detail view I am passing the questions context like this. product = Product.objects.get(pk=1) questions = product.product_questions.all().order_by('-created_at') answers = ... # I want to get the related answers of each question object from questions I can show the answers in the template from question like this {% for question in questions %} {% for ans in question.ques_answers.all %} {{ans}} {% endfor %} ... But with some reason I have to send answers of every question from view as a context. How can I achieve this from view ? -
Set default serializer for user in django
I created a rest-framework API in django for signup and its serializer is like this: class SignupSerializer(ModelSerializer): class Meta: model = User fields = ('email', 'password', 'first_name', 'last_name') read_only_fields = () def create(self, validated_data): with transaction.atomic(): new_user = User.objects.create_user(....) return new_user Now its working perfectly fine, but problem is that it also returns password hash in response object. Or if i include user in any other serializer and set depth=1 it still returns every field including password How can I set default serializer for user? so that it only returns those fields which I set by myself? -
How do I get the designation of a model field?
How can I put a designation (such as label in forms) in the model so that later it can be obtained, as here, for example: models: class characterist_0001_pkModel(models.Model): a1 = models.CharField('Процессор. Процессор', label = 'Процессор', max_length= 40, null= True) view: # хочу получить: Процессор characterist_0001_pkModel.a1.label -
Get objects that are not in manytomany relationship of a different model?
Lets say I have two models and a form: class Person(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Car(models.Model): plate = models.CharField(max_length=255) persons = models.ManyToManyField(Person) class CarAddForm(forms.ModelForm): plate = forms.CharField() persons = forms.ModelMultipleChoiceField(queryset=Person.objects.all()) class Meta: model = Car fields = [ 'plate', 'persons' ] Is there a way to get ModelMultipleChoiceField queryset of people that are NOT associated with any car? In case of editing Car model object, the queryset should contain people that are NOT associated with any car PLUS people that are associated with the car being edited PS: maybe there is a better way to achieve this? -
Django: objects are not showing at index page
This is my first project with Django and I got a problem. In the backend I created news, but I have an issue displaying the news on the frontpage. Models should be fine since I can create news into the admin panel. But I can't figure out where is my mistake. I have app 'pages'>views.py from django.shortcuts import render, redirect, get_object_or_404 from mainnews.models import Mainnews # Create your views here. def home_view(request): main = Mainnews.objects.all() context = { 'main' : main } return render(request, 'index.html', context) root>urls.py from pages.views import home_view urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name = 'home'), ] and app mainnews>views.py from django.shortcuts import render, get_object_or_404 from .models import Mainnews # Create your views here. def index(request): main = Mainnews.objects.all() context = { 'main' : main } return render(request, 'index.html', context) and the template mainnewsandevents.html that extends to index {% block content %} <!-- Section 2 News and Events --> <div id="news-container"> <div class="jumbo-news"> <img id = 'jumboImgUrl' class='jumbo-img' src="{{ main.image.url }}"> <h2 id = 'jumboTitle' class='jumbo-title'>{{ main.title }}</h2> <h4 id = 'jumboDescription' class='jumbo-parag'>{{ main.description }}</h4> </div> {% endblock %} -
No such application (or application not configured) A2 hosting django [closed]
** I have create that app already but it still show it while i restart the app ** -
Django Error ModelForm has no model class specified
Can't get past this error for a while now, checked all the related topics and everyone had a typo/syntax problem. I have checked everything and the code looks fine and I really can't tell what could be the problem, if anyone sees the issue pls help. Below I'll place my code and the error. I created a form so I can add a new subject via a button which I call inside my view and render in a template, very simple. TRACEBACK Environment: Request Method: GET Request URL: http://127.0.0.1:8000/addsubj/ Django Version: 3.1.5 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', 'crispy_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\D\Documents\django\project\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\D\Documents\django\project\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\D\Documents\django\project\project\App\decorations.py", line 7, in wrap return function(request, *args, **kwargs) File "C:\Users\D\Documents\django\project\project\App\views.py", line 40, in add_subject_view newsubj = AddSubjectForm() File "C:\Users\D\Documents\django\project\env\lib\site-packages\django\forms\models.py", line 287, in __init__ raise ValueError('ModelForm has no model class specified.') Exception Type: ValueError at /addsubj/ Exception Value: ModelForm has no model class specified. MY FORMS.PY from django.forms import ModelForm from django import forms from django.contrib.auth.forms import UserCreationForm from .models … -
Submitting data from 1 table to another table
I am trying to submit data from a checklist using forms. The checklist is generated from a database table and after submission the checked items are inserted into another database table. I am getting the error as form is invalid. This is my models.py CustomStudent is the database from where I am taking value and Reports is the database where I am submitting values class CustomStudent(models.Model): _id = models.AutoField sname = models.CharField(max_length = 50) slname = models.CharField(max_length = 50) password = models.CharField(max_length = 255, default = '') def __str__(self): return str(self.slname) return str(self.sname) class Report(models.Model): # _id = models.AutoField() tname = models.CharField(max_length = 100) sname = models.CharField(max_length = 100) fdate = models.DateField() tdate = models.DateField() dailydate = models.DateField() objective = models.CharField(max_length = 512) tplan = models.CharField(max_length = 512) how = models.CharField(max_length = 512) material = models.CharField(max_length = 512) extra = models.CharField(max_length = 512) topic = models.CharField(max_length = 512) pftd = models.CharField(max_length = 512) activity = models.CharField(max_length = 512) comment = models.CharField(max_length = 512) thought = models.CharField(max_length = 512) admin_comment = models.CharField(max_length = 255) def __str__(self): return str(self.tname) return str(self.sname) This is code from my forms.py to use the database. sname = forms.ModelMultipleChoiceField(queryset=CustomStudent.objects.all().values_list('sname', flat=True), required = False, widget =forms.CheckboxSelectMultiple( attrs ={'class':' … -
How do I keep select option after form validation has failed in Django?
After validation fails, I want to keep values entered by user, but have issues with dropdowns. In models.py GENDER = [ ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ] gender = models.CharField(max_length=1, choices=choices.GENDER, default='') In template <div class="col-md-4"> <label for="gender">Gender</label> <select class="form-control form-control-lg" id="gender" name="gender" required> <option selected></option> {% for choice in form.gender.field.choices %} <option value="{{ choice.0 }}" >{{ choice.1 }}</option> {% endfor %} </select> </div> In views.py if form.is_valid(): return render(self.request, 'success.html') else: form_content = {'form': form} return render(self.request, 'template.html', form_content) -
Want to run test on postgresql and not sqlite: sqlite3.OperationalError: no such function: Now
I have a Django app set with Docker and different developpement environment: dev, preprod, prod. I use a postgresql database / pgaadmin 4 in my local Windows environment I want to write and run tests 'outside' Docker in a VSCode terminal (because if I use web container to run tests, changes in my tests.py are not updated so I need to down, build and re-run my containers) so I run the command py manage.py test cafe.tests.CafeTestCase --settings=core.settings.preprod where I speficy the settings to consider But I got an error sqlite3.OperationalError: no such function: Now because some data migrations use timezone.now() that i not available in sqlite but I have specify test_database in my settings and given access to user so test should consider postgresql no? base.py DATABASES = { 'default': { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, 'db.sqlite3')), "USER": os.environ.get("SQL_USER", "user"), "PASSWORD": os.environ.get("SQL_PASSWORD", "password"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", "5432"), 'TEST' : { 'NAME': 'test_cafetropical', } } } environment variables are set in a .env.preprod file -
Error while executing raw sql query in django
I am trying to use raw query in django view : but it is showing error: database table named auth_user: my point is: 'where' clause should check for column named "username" why it checking for column "chaitanya360" which is obviously not present in table. -
Follow/unfollow button without reload page [Django, AJAX]
I made 'Follow user' functionality. It works fine. You can follow and later unfollow somebody. But it's not enough... Now when you click follow or unfollow button the page have been reload. I need 'Follow user' functionality without reload the page. I don't know how implement AJAX here. Can you help me with this? In my template.html i have: {% with total_followers=profile.followers.count %} ({{ total_followers }} Follower) <br> {% endwith %} <form action="{% url 'users:follow_user' %}" method="POST" class="follow-form" id="{{ profile.id }}"> {% csrf_token %} <input type="hidden" name="user_id" value="{{ profile.id }}"> <button type="submit" class="follow-btn{{ profile.id }}"> {% if request.user not in profile.followers.all %} Follow {% else %} Unfollow {% endif %} </button> </form> In my view.py i have function to follow or unfollow: def follow_user(request): user = request.user if request.method == 'POST': user_id = request.POST.get('user_id') user_obj = Profile.objects.get(id=user_id) if user not in user_obj.followers.all(): UserFollowing.objects.get_or_create(following_from=user, follow_to=user_obj) else: UserFollowing.objects.filter(following_from=user, follow_to=user_obj).delete() return redirect('profile', slug=user_obj.slug) In my models.py i have: class UserFollowing(models.Model): following_from = models.ForeignKey("Profile", related_name="following_from", on_delete=models.CASCADE) follow_to = models.ForeignKey("Profile", related_name="follow_to", on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: db_table = 'users_userfollowing' constraints = [models.UniqueConstraint(fields=["following_from", "follow_to"], name="unique_followers")] ordering = ("-created",) def __str__(self): return f"FROM:{self.following_from} TO:{self.follow_to}" class Profile(AbstractUser, HitCountMixin): following = models.ManyToManyField("self", through=UserFollowing, related_name="followers", symmetrical=False) def save(self, … -
more than one primary key error in django
I have a problem with two of my models. When tying to migrate it always ends up with the error that I have more than one primary key. I have googled and tried lots of different solutions but nothing works. models: class Adress(Model): street=CharField(default='',max_length=100) snumb=CharField(default='',max_length=15) town=CharField(default='',max_length=100) postn=CharField(default='',max_length=5,validators=[postnvali]) def __str__(self): return 'city: ' + self.town class Meta: ordering=('street','town') class Person(Model): fname=CharField(default="",max_length=100) lname=CharField(default="",max_length=100) mobil=PhoneField(default='9999999999') mail=EmailField(default='contact@gmail.com') padress=OneToOneField(Adress,on_delete=CASCADE) def __str__(self): return 'person: ' + self.fname class Meta: ordering=('fname','lname') migration file: # Generated by Django 3.1.4 on 2021-01-20 13:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('kammem', '0029_auto_20210120_1354'), ] operations = [ migrations.AddField( model_name='person', name='id', field=models.AutoField(auto_created=True,serialize=False, verbose_name='ID'), preserve_default=False, ), migrations.AlterField( model_name='person', name='padress', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='kammem.adress'), ), ] -
Post is not liking or Disliking
I am making a Blog app and I built a Like or Dislike Feature BUT that is not working. It is showing custom error. views.py def post_like_dislike(request, post_id): post = get_object_or_404(Post, pk=post_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse({'action': 'undislike_and_like'}) elif request.user in post.likes.all(): post.likes.remove(request.user) return JsonResponse({'action': 'unlike'}) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) # Dislike elif request.GET.get('submit') == 'dislike': if request.user in post.likes.all(): post.likes.remove(request.user) post.dislikes.add(request.user) return JsonResponse({'action': 'unlike_and_dislike'}) elif request.user in post.dislikes.all(): post.dislikes.remove(request.user) return JsonResponse({'action': 'undislike'}) else: post.dislikes.add(request.user) return JsonResponse({'action': 'dislike_only'}) else: messages.error(request, 'Something went wrong') return redirect('home') detail.html <form method="GET" class="likeForm d-inline" action="{% url 'comments:post_like_dislike' post.id %}" data-pk="{{post.id}}"> <button type="submit" class="btn"><i class="far fa-thumbs-up"></i> <span id="id_likes{{post.id}}"> {% if user in post.likes.all %} <p style="color:#065FD4;display: inline">{{post.likes.count}}</p> {% else %} <p style="color:black;display: inline">{{post.likes.count}}</p> {% endif %} </span> Like</button> </form> <form action="{% url 'comments:post_like_dislike' post.id %}" method="GET" class="d-inline dislikeForm" data-pk="{{ post.id }}"> <button type="submit" class="btn"><i class="far fa-thumbs-down"></i> <span id="id_dislikes{{post.id}}"> {% if user in post.dislikes.all %} <p style="color:#065FD4; display: inline;">{{post.dislikes.count}}</p> {% else %} <p style="color:black; display: inline;">{{post.dislikes.count}}</p> {% endif %} </span> Dislike </button> </form> urls.py path('post_like_dislike/<int:post_id>/',views.post_like_dislike, name='post_like_dislike'), models.py class Post(models.Model): description = models.TextField() likes = models.ManyToManyField(User, related_name='post_like', blank=True) dislikes = models.ManyToManyField(User, related_name='post_dislike', blank=True) ERROR When i click … -
Django returns relative path to image field not url
I have following AdminUserSerializer serializer and PersonSerializer serializer class AdminUserSerializer(serializers.ModelSerializer): persons = PersonSerializerForUser(many=True) verifications = serializers.SerializerMethodField('users_for_verification') class Meta: model = User fields = ['id', 'persons', 'verifications'] @staticmethod def users_for_verification(obj): persons = obj.persons.filter(status=1, paid=True) serializer = PersonSerializer(persons, many=True) return serializer.data class PersonSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField('paginated_comments') images = ImageSerializer(source='image_set', many=True) class Meta: model = Person exclude = ('paid', 'status', 'register_date', 'paid_date') def paginated_comments(self, obj): .... The request returns { "id": "bf6e227b-5037-4475-b07e-7dbf44bcbfa1", "persons": [ { "id": "8aec320c-2f0d-4f46-8ba9-1ad9428e2218", "images": [ {"image": "http://127.0.0.1:8000/media/images/1_skR8WG9.jpg"} ], "name": "123", "city": "123", "bio": "123" } ], "verifications": [ { "id": "8aec320c-2f0d-4f46-8ba9-1ad9428e2218", "comments": {} ] }, "images": [ {"image": "/media/images/1_skR8WG9.jpg"} ], "name": "123", "city": "123", "bio": "123", ]} For person.images.image contains url to image, but verifications.images.image returns a relative path to image, but i want an url -
how do I apply bootstrap styles only for django-crispy-forms not for other tags in the html template
Upto know I used Bootstrap for the total project. But now I wanted to use my own styling for my Whole project. And I want to use crispy form tags for some forms like registration and login form.But when I tried it bootstrap styles are applying to my whole project.I don't want that I just want styling for only forms from crispy_forms. How can I achieve this. Thanks in advance. {% extends '../base.html' %} {% load crispy_forms_tags %} {% block extra_head %} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> {% endblock extra_head %} {% block content %} <form method="post"> {{ form|crispy }} <button class="btn btn-outline-primary" type="submit">SignUp</button> #styles applying for this button also </form> {% endblock content %}