Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get first news of any category in Django?
i created 2 table News and Category at models.py file in my Django project. I use first_news = News.objects.first() to have the first news in database. How can i do if i want to get first news of any category? -
how much mysql knowledge i need for python django? and how to be more efficient in back end development?
i recently learned basics of python and library like requests , and i want to go ahead for django and back end development with python , but i need some help, and i didnt find my answers in google how much database knowledge i need? i know , for a back end developer , i should know how database works and what is sql and nosql databases i know what are these, but going further and deeper, in technical section, how much i should learn, to be more efficient? my knowledge about sql , nosql , how they work + mysql.connector and pymongo python libraries , is enough? do you have any suggetion for me to become a back end developer? -
Django admin template not loading (Wrong path)
When i try to load my web page, i get: Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /usr/lib/python3/dist-packages/django/contrib/admin/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/lib/python3/dist-packages/django/contrib/auth/templates/index.html (Source does not exist) Inside django/contrib/admin/templates/ there are two folders, admin and registration. The correct path would be django/contrib/admin/templates/admin/index.html The path is almost correct, but not quite. How do i go about this? Thank you. -
why it cant find the image , please view the image
here the error I put the image everywhere also in src I change the direction like ../ or ../.. but it did not find it -
Django objects.get() function does not work but objects.filter().first() works
When I look up for the user with User.objects.get(username=username) it shows error User matching query does not exist but it works fine with User.objects.filter(username=username).first() why does this happen? -
Create a table in dbshell with django
here is my code : frontgreat=> CREATE TABLE contact_titlemessagesuggestion; ERROR: syntax error at or near ";" LINE 1: CREATE TABLE contact_titlemessagesuggestion; i don't understand why it's not working and why it's an syntax error. frontgreat=> DROP TABLE contact_titlemessagesuggestion; ERROR: table "contact_titlemessagesuggestion" does not exist have no syntax error and work fine. Regards -
post related with django-taggit not showing results
tried to build related post on post detail view using django-taggit plug-in, everything seem right but no result. views.py def news_detail(request, post): post = get_object_or_404(Article, slug=post, status=“published”) post_related = post.tags.similar_objects() return render( request, “blog/post/news_detail.html”, {“post”: post, “post_related”: post_related}, ) news_detail.html {% extends "blog/base.html" %} {% block content %} <img src="{{ post.images.url }}" width="100%"> <h1>{{ post.title }}</h1> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|safe|linebreaks }} <p> {% for tag in post.tags.all %} <a href="{{ tag.slug }}">{{ tag.name }}</a> {% endfor %} </P> {% for post in post_related %} <h1>{{ post.post_title }}</h1> {% endfor %} {% endblock %} thanks for any help -
Download file after payment with Django
I am building a digital ecommerce platform with Django. When my customers pay for a digital product, I want that the digital product gets downloaded immedately after payment. So when they complete a payment they get automatically the file downloaded. For now after a payment I am getting rendered back to the home page and get a succesful payment. But instead of rendering back to home page I want the file to be downloaded after payment, so I want to be rendered to something like I return redirect( {{item.file.url}} ) instead of return redirect("/" ) (see last line of Views). My code in Views and Models is as follows: Views class PaymentView(View): def get(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) context = { 'order': order } return render(self.request, 'dashtemplates/payment.html', context) def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total() * 100) try: charge = stripe.Charge.create( amount=amount, currency="usd", source=token ) #create payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() #assign the payment to the order order_items = order.items.all() order_items.update(ordered=True) for item in order_items: item.save() order.ordered = True order.payment = payment order.save() messages.success(self.request, "Your order was succesful!") return redirect("/" ) Models … -
is_valid() not running after my form request.POST
This is my views.py. I am creating my product from by creating an object and trying to store values posted from my html form This is my models. My product form inherits all of the fields from the models. -
Why is Django ORM so slow?
This code - raw SQL - takes 2.6 sec: ''' q_sku = MainData.objects.raw(f'SELECT id as id, COUNT(DISTINCT sku) as "count" FROM imports_maindata WHERE feed_id={feed.id}') q_loc = MainData.objects.raw( f'SELECT id as id, COUNT(DISTINCT locale) AS "count" FROM imports_maindata WHERE feed_id={feed.id}') q_spec = MapSpecs.objects.raw( f'SELECT id as id, COUNT(DISTINCT f_feat_id) AS "count" FROM imports_mapspecs WHERE feed_id={feed.id}') q_mapped = MapSpecs.objects.raw( f'SELECT id as id, COUNT(DISTINCT ic_feat_id) AS "count" FROM imports_mapspecs WHERE feed_id={feed.id} AND ic_feat_id IS NOT NULL') q_date = MainData.objects.raw( f'SELECT id as id, MAX(last_update) as "last_date" FROM imports_maindata WHERE feed_id={feed.id}') print(q_sku[0].count, q_loc[0].count, q_spec[0].count, q_mapped[0].count, q_date[0].last_date) ''' While this one - ORM only - takes 3.1 sec: ''' f = Feed.objects.all() for feed in f: prods_count = f.filter(maindata__feed_id=feed.id).values('maindata__sku').distinct().count() locales_count = f.filter(maindata__feed_id=feed.id).values_list('maindata__locale', flat=True).distinct() total_specs = f.filter(mapspecs__feed_id=feed.id).count() mapped_specs = f.filter(mapspecs__feed_id=feed.id, mapspecs__ic_feat_id__isnull=False).all().count() try: last_update = f.filter(maindata__feed_id=feed.id).values('maindata__last_update').distinct().order_by('-maindata__last_update').first()['maindata__last_update'] except TypeError: pass ''' And this one, using ORM but different approach, is returned in 3.1-3.2 sec: ''' f = Feed.objects.all() prods = f.annotate(num_prods=Count('maindata__sku', distinct=True)) locs = f.annotate(num_locs=Count('maindata__locale', distinct=True)) total_sp_count = f.annotate(num_books=Count('mapspecs__f_feat_id', distinct=True)) total_sp_mapped = f.filter(mapspecs__ic_feat_id__isnull=False).annotate( num_books=Count('mapspecs__ic_feat_id', distinct=True)) ''' So how come that Django ORM is so inefficient and slow? The timings are for a low number of rows in DB (below 50K)... So it's not only slower than raw … -
How to write URL and VIEWS
Below is my model class Movie(models.Model): name = models.CharField(max_length=55) artists = models.ManyToManyField(Artist) def __str__(self): return self.name Below is the View: def moviesView(request): movies = Movie.objects.all() context = { "movies": movies } return render(request, 'movies/movies.html', context=context) def movieView(request, name): print(name) movie = Movie.object.get(name=name) context = { "movie": movie } return render(request, 'movies/movie.html', context=context) Below are the URLS: urlpatterns = [ path('movies', moviesView, name='movies'), re_path('movies/(\d+)', movieView, name='movie'), path('artists', artistView, name='artists') ] Below is the template: <h1>Movies</h1> {% for movie in movies %} <a href="{% url 'movie' movie.name %}">{{ movie.name }}</a> <h3>{{ movie.name }}</h3> {% for artist in movie.artists.all %} <ul> <li><a href="{{ artist.wiki }}">{{ artist.name }}</a></li> </ul> {% endfor %} {% endfor %} If I click a movie avengers, it should carry to another page with movie details of avengers as mentioned in the model: I need to frame the url as: http://127.0.0.1:8000/movies/avengers -
How do I pass parameter to the form in Django?
So as the title states, I'm trying to pass a parameter from views to forms. I've seen several Stack Overflow posts regarding this issue, but none of them solved my problem :( So what I'm trying to build is basically a question-and-answer application. Each user answers to pre-provided questions. I want to make an answering template for each corresponding question. So here's my code: forms.py class AnswerForm(forms.ModelForm): main_answer = formsCharField(required=True) # Some other fields def __init__(self, *args, **kwargs): self.q = kwargs.pop('q') super(AnswerForm, self).__init__(*args, **kwargs) self.fields['main_answer'].label = q.main_question views.py def createAnswer(request, pk): thisQuestion = Question.objects.get(question_number=pk) AnswerFormSet = modelformset_factory(Answer, form=AnswerForm(q = thisQuestion), extra=1) formset = AnswerFormSet(queryset=Answer.objects.filter(authuser=request.user.id, question_number=pk)) # And some other codes I'm supposed to show this formset in my template using {% crispy_formset%}. However I keep getting this error: "name 'q' is not defined". What is the problem here? -
How to remove the default order by set by Django admin changelist on primary key
Django admin automatically sets sorting on primary key when rendered on changelist (Django Admin) which causes quite a lot amount of query cost of data (5-6lakhs) records. The same issue is faced due to which the page is giving 504. How can the default sorting be removed. I have checked and the ordering is set in base class (main.py) in get_queryset (method). Overriding that particular method causing extra queries. What can be the best way to remove that default ordering. -
Django: Included template does not appear
I am implementing messages system with ajax. Everything works fine when I post new message. I mean new message appears without reloading, but when I go to create message page I cannot see included template(with messages), it includes after posting message. I tried to include other template and it worked. My code below, thanks for help in advance. views.py class MessageCreateView(CreateView): model = Message fields = ['content'] template_name = 'users/create_message.html' def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): if request.method == 'POST': sender = self.request.user.profile receiver_pk = self.kwargs['profile_pk'] print(receiver_pk) receiver = Profile.objects.get(id=receiver_pk) new_message = Message.objects.create( message_by=sender, message_to=receiver, content = form.cleaned_data['content']) return JsonResponse({'message': model_to_dict(new_message)}, status=200) else: return self.form_invalid(form) def get_context_data(self, **kwargs): context = super(MessageCreateView, self).get_context_data(**kwargs) context['profile_pk'] = self.kwargs['profile_pk'] return context def messages(request, profile_pk): current_user_profile = request.user.profile second_profile = Profile.objects.get(pk=profile_pk) messages = Message.objects.filter( Q(message_to=current_user_profile, message_by=second_profile)| Q(message_to=second_profile, message_by=current_user_profile)).order_by('date_of_create') context = { 'messages': messages } return render(request, 'users/messages.html', context=context) urls.py urlpatterns = [ path('login/', CustomLoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('register/', register, name='register'), path('profile/<int:pk>/', ProfileDetailView.as_view(), name='profile_detail'), path('profile/follow/<int:pk>', follow_profile, name='follow_profile'), path('results/', search, name='search'), path('create_message/<int:profile_pk>/', MessageCreateView.as_view(), name='create_message'), path('messages/<int:profile_pk>/', messages, name='messages') ] create_message.html {% extends 'users/base.html' %} {% load crispy_forms_tags %} {% block title %}Chat{% endblock %} {% block content %} <div class="messages"> {% include 'users/messages.html' … -
Switch two Unique Constraint Form Fields Django
I have a Unique Constrained model where a Client can have a primary and a secondary supporter, which is indicated by a BooleanField on the model. A supporter is basically someone who if responsible for the client in an internal ticketing system. When trying to switch primary and secondary supporter in a form, or removing the current primary supporter and instead replacing it with the current secondary, the form throws a UniqueConstraint ValidationError. Any idea as to how to overcome this? Tried multiple things in regards to manipulating the forms post-validation, like reversing the supporter field changes if primary_supporter_form.initial['supporter'] == secondary_supporter_form.cleaned_data['supporter].id, flipping the BooleanFields on each form instead and removing thrown UniqueConstraint error the forms; however the forms ignore the change all together. Very frustrating, as manipulating the form post-validation doesn't seem to be documented anywhere. Models: class Client(models.Model): name: str = models.CharField(max_length=255) created: datetime = models.DateTimeField(auto_now_add=True) class ClientSupporter(models.Model): supporter: User = models.ForeignKey(User, on_delete=models.CASCADE, related_name='clients') primary: bool = models.BooleanField(default=False) client: Client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='supporters') class Meta: constraints = [ UniqueConstraint(fields=['client'], condition=Q(primary=True), name='unique_primary_supporter') ] unique_together = ('client', 'supporter') ordering = ('-primary',) Forms: class ClientSupporterForm(forms.ModelForm): supporter = forms.ModelChoiceField(queryset=User.objects.all(), required=False, label='') class Meta: model = ClientSupporter fields = ('supporter', 'primary', 'id', 'client') … -
Crontab job not executing in django project
I am using crontab to execute certain function, however when i run the server the job is not processed. When i use the command crontab show , it shows me the job , bit again when i run the server its not executed. I followed this documentation https://pypi.org/project/django-crontab/ and watched YT tutorial as well but nothing worked. crontab -l. shows this : '*/1 * * * * /Users/nourelgeziry/.local/share/virtualenvs/Equal_Distribution_maintainance-M-bcKwQz/bin/python /Users/nourelgeziry/Desktop/MyProjects/Equal Distribution maintainance/EDMS/manage.py crontab run bd84e5bec9ad4805b334e11fafec1b5c # django-cronjobs for EDMS' . Also worth mentioning i am using pipenv for the virtual env. Let me know if there is anything i can provide more . Thank you in advance -
django combine multiple ListView using get_query and search form
in my project, I have three models models.py class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, null=True, blank=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children') class Tag(models.Model): tag = models.CharField(max_length=75, verbose_name='Tag') slug = models.SlugField(null=True) class Post(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(max_length=150, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) tags = models.ManyToManyField(Tag, related_name='tags', blank=True) and I created search filter view in views.py def is_valid_queryparam(param): return param != '' and param is not None class SearchPepsiView(ListView): template_name = "blog/NewSearch.html" model = Post paginate_by = 10 def get_queryset(self): return Post.objects.filter(category__slug=self.kwargs['slug']) def get_context_data(self, *args, **kwargs): context = super(SearchPepsiView, self).get_context_data(*args, **kwargs) context['category'] = Post.objects.filter(category__slug=self.kwargs['category']) return context def get(self, request, *args, **kwargs): request = self.request qs = Post.objects.all() categories = Category.objects.filter(parent=None).order_by('name') PostOrAuthor_query = request.GET.get('PostOrAuthor') SearchCategory_query = request.GET.get('SearchCategory') if is_valid_queryparam(PostOrAuthor_query): qs = qs.filter(Q(title__icontains=PostOrAuthor_query) | Q(content__icontains=PostOrAuthor_query) | Q(author__username__icontains=PostOrAuthor_query)).distinct() if is_valid_queryparam(SearchCategory_query) and SearchCategory_query != 'Choose...': qs = qs.filter(category__name=SearchCategory_query) count = qs.count() or 0 return render(request, self.template_name, { 'queryset': qs, 'categories': categories, 'count': count, }) and I created Post Per Category View in views.py class PostPerCategoryCBV(ListView): model = Post template_name = 'blog/Category_Projects.html' def get_queryset(self): self.category = Category.objects.get(slug=self.kwargs['slug']) return Post.objects.filter(category=self.category) def get_context_data(self, **kwargs): context = super(PostPerCategoryCBV, self).get_context_data(**kwargs) context['category'] = self.category return context and I created Post Per Tag View … -
Add an additional form to a formset using POST without Javascript and validation
I want to use a Django formset, but with pure server rendering and without the need of Javascript to add additional forms to it. The user should just click a button on the page and the page should reload with an additional form in the formset. All user input should be preserved! The relevant part in the view is: if request.POST.get('add_form') == "true": cp = request.POST.copy() cp['form-TOTAL_FORMS'] = int(cp['form-TOTAL_FORMS']) + 1 fs = MyFormSet(cp) The problem is that when MyFormSet(cp) renders a form representation it adds validation errors to it (like "This field is required"). This is ugly and not acceptable. How can I render it without the errors (they should only be present when the whole form was submitted)? MyFormSet(initial=...) seems not to be an option as it must also work in a UpdateView (the docs are pretty clear that initial is only for extra forms) and also the POST data can't be directly used as initial values. I am super thankful for any hint as it took me several hours without getting anywhere (and it seems to be such a common feature as the rest of Django is so Javascript unaware). -
Cache control decorator has no effect on rendered page in Django
I am trying to add cache control to a page in a Django application: from django.contrib.auth.decorators import login_required from django.views.decorators.cache import cache_control from django.shortcuts import render @login_required @cache_control(no_cache=True, must_revalidate=True, no_store=True) def fooView(request): return render(request, 'foo.html') But no meta information is appearing in the head section of the page. Does this decorator not work in conjunction with render, or in development mode (DEBUG = False)? Also I couldn't find any documentation on the parameters for the cache control decorator. I'm wondering what are the defaults. -
How can I count my followers in django template?
This is my second time when i am asking this question again because i guess first time this question didn't reach to the people who can tell me the solution of this question. Well here i just want to count followers and following, but i don't know how can i count tell and show them in a profile detail template. I don't understand how can i find followers and following respectively with a single follower field which is mentioned in model.py. If anybody know answers than please answer. I shall be very thankful to you. models.py. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) objects = ProfileManager() def __str__(self): return f'{self.user.username}' view.py(profile detail view) def get_context_data(self, *args, **kwargs): context = super(UserProfileDetailView, self).get_context_data(*args, **kwargs) user = context['user'] '''#Trying with this but it is not working i guess this is wrong way to this but i am not sure!!''' allprofile = UserProfile.objects.all() followers = 0 for u in allprofile.follower: if u == user.userprofile: followers+=1 context['followers']=followers return context if more detail is require than tell me in a comment session. I will update my question with … -
What is the "|" character in Django called?
"|" is equivalent to Angular Pipes but what is it called in Django? Like in the official Django Polls App tutorial enter image description here vote{{ choice.votes|pluralize }} is to let Django automatically appends an "s" character after the string "vote" if there are more than 2 votes being rendered from the databse, otherwise don't but I don't know what is called in Django. On another hand, this equivalent technology in Angular is called Angular Pipes. -
How to pass a key field's value to filter dependent field's values in Django / jquery-autocomplete
In my Django app, I am using jQuery autocomplete for fields to complete a transaction. For an independent field, i.e. the entered value in the field not based on another field's value, the routine is successfully completed. There are situations, where the entered (field) value has a parent object, and I need to use a .filter (as explained in subsequent paragraphs) in order to get the correct value/s of the (dependent) field. This is akin to cities assigned to a specific country. In the transaction, the user has to first enter the parent field's value (e.g. "Country Id" in the following code example). And later select a value from one of the dependent values (e.g. the cities). My auocomplete routine is as follows: Template: $(function() { $( "#id_city_cd" ).autocomplete({ source: "{% url 'city_search' %}", select: function(e, ui) { $("#id_city_cd").val(ui.item.city_cd : '' ); $("#id_city_name").val(ui.item.label); return false; }, change: function(ev, ui) { $("#id_city_cd").val(ui.item? ui.item.city_cd : '' ); $("#id_city_name").val(ui.item.label); }, minLength: 1, delay: 0, autoFocus: true, }); }); My View is as under: def CitySearch(request): if request.is_ajax(): tmpCountryId = "some_value" // Here I want a value for Country Id (e.g. "DE") q = request.GET.get('term','') city_search = City.objects.filter(country_id=tmpCountryId).filter(city_name__icontains=q).annotate(value=F('city_name'), label=F('city_name')).values('city_id', 'value', 'label') // I have … -
Getting error in dependent ChoiceField form django?
I am trying to create a Dependent Dropdown in django(Country->State->City).My model structure is class Country(models.Model): name = models.CharField(max_length=100) class State(models.Model): name = models.CharField(max_length=100) country = models.ForeignKey(Country, on_delete=models.CASCADE) class City(models.Model): name = models.CharField(max_length=100) state = models.ForeignKey(State, on_delete=models.CASCADE) class Organization(models.Model): name = models.CharField(max_length=50) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) COUNTRIES = [(choice.pk, choice) for choice in Country.objects.all()] COUNTRIES.insert(0, ('', 'Select Country')) My forms.py class OrganizationForm(forms.ModelForm): name = forms.CharField(label='Company name', min_length=2, error_messages={ 'required': 'Company name should not be empty', 'min_length': 'Atleast 2 characters required', 'max_length': 'Should not exceed 50 characters'}) country = forms.ChoiceField(choices=COUNTRIES, error_messages={ 'required': 'Country should not be empty'}) state = forms.ChoiceField(error_messages={ 'required': 'State should not be empty'}) city = forms.ChoiceField(error_messages={ 'required': 'City should not be empty'}) class Meta: model = Organization fields = ['name','city'] templates/states.html <option value="">Select State</option> {% for state in states %} <option value="{{state.id}}">{{state.name}}</option> {% endfor %} My rendering part works fine.But when I submit the form it displays an error for state field as Select a valid choice. 70 is not one of the available choices. where 70 is id of a state. And one more doubt, is it ok to store only city as foreign key in my organization model or do I need to store country and … -
How to import dajngo models with their ForeignKeys ond new ids?
I need to import some data in django and I stopped on one problem. I have few models in JSON file and they are all connected via ForeignKey field. In my app I potentialy could have some models with the same ids as those in file, and I would like to keep both. Therefore, for each model in file, while saving it, I would need to generate new id, which as ar as I know is done automatically, if 'id' section in file is empty. My problem is: what with ForeignKeys? How to keep connection between models, and in the same time for each of them generate new id? -
How can I display a single post while they are giving me the error (No post found matching the query)
I am working with a django project to design a blog app. I am at the stage of displaying the posts, but I tried to display a single post (127.0.0.1:8000/post/1/), but I met error below: * Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/post/1/ Raised by: rymapp.views.PostDetailView No post found matching the query * ** See my views.py ** from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post def home(request): return render(request, 'rymapp/home.html', {'title': 'home'}) def about(request): return render(request, 'rymapp/about.html', {'title': 'about'}) def blog(request): context = { 'posts': Post.objects.all() } return render(request, 'rymapp/blog.html', context) class PostListView(ListView): model = Post template_name = 'rymapp/blog.html' #<app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] class PostDetailView(DetailView): model = Post Below is my urls.py from django.urls import path from .views import PostListView, PostDetailView from .import views urlpatterns = [ path('', views.home, name='rymapp-home'), path('about/', views.about, name='rymapp-about'), path('blog/', PostListView.as_view(), name='rymapp-blog'), path('post/<int:pk>/', PostDetailView.as_view(), name='rymapp-post_detail'), ] And here it is my post_detail.html {% extends "rymapp/base.html" %} {% block content %} <article class="media content-section mt-2"> <div class="media-body"> <lu class="list-group mr-5"> <li class="list-group-item list-group-item-light"> <div class="article-metadata"> <img class="rounded-circle article-img" width="50" height="50" src="{{ object.author.profile.image.url }}"> <a class="mr-2 ml-2" href="#"> {{ object.author }} </a> <small class="text-muted"> {{ object.date_posted …