Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Post matching query Django
I get the Post matching query does not exists error when I run this code on my Django App. I tried to create the like section on every post on my blog app. I don't understand this error. I belive it has to be from the like function, but I have no clue why. dsd sadsa dsadsadsadsadsad dsasdsadasdasdsa views.py def like_post(request): user = request.user if request.method =='POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id = post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Likes.objects.get_or_create(user = user, post_id = post_id) if not created: if like.value =='Like': like.value='Unlike' else: like.value = 'Like' like.save() return redirect('blog-home') html file <form action="{% url 'like-post' %}" method="post"> {% csrf_token %} <input type="submit" name="post_id" value="{{post.id}}" class="btn btn-primary btn-sm"> {% if user not in post.liked.all %} <button class="ui button positive">Like</button> {% else %} <button class="ui button negative">Unlike</button> {% endif %} </form> models.py class Post(models.Model): content = models.TextField(blank=True, null=True) date_posted = models.DateTimeField(default = timezone.now ) #one user can have multiple posts, but one post can only have one author author = models.ForeignKey(User, on_delete = models.CASCADE) image = models.ImageField(blank = True, null=True, upload_to='post-images') video = models.FileField(blank=True, null=True, upload_to='post-images', validators=[validate_file_size,FileExtensionValidator(['ogg', 'm4v', 'wmw', 'wma','mov','avi','quicktime','flv','mp4','f4v','m4b', 'm4a', '3gp', 'aac', 'mp4', 'mp3', 'flac'])]) … -
Custom Django messages and adding extra context to Django change_view
I am using SESSION_COOKIE_AGE and added custom JS to refresh the page after the session expires to log a user out after a certain time of inactivity. I now was to add a message to the logout page to let the user know why they were logged out. According to Django Docs I have to add my custom message as context to the view and then call it on the template. The logout function is used for mainly for the change_form.html template, but of course SESSION_COOKIE_AGE works everywhere. Where is the view for change_form so I can add this context? I see from the docs it is called change_view, but not what file/folder it is in can I cannot find it for the life of me. Would there be an easier way to show this message no matter where the user was logged out from? -
create_user() missing 1 required positional argument: 'username'
I deleted username field because I wanted user to be able to login with their email address, so I have this in my models.py : class CustomUser(AbstractUser): USER_TYPE = ((1, 'HOD'), (2, 'Staff'), (3, 'Student')) username = None email = models.EmailField(unique=True) user_type = models.CharField(default=1, choices=USER_TYPE, max_length=1) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Student(models.Model): admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=1, choices=GENDER) address = models.TextField() profile_pic = models.ImageField(upload_to='media') session_start_year = models.DateField(null=True) session_end_year = models.DateField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) In my views.py, I tried : user = CustomUser.objects.create_user(email=email, password=password, user_type=3, first_name=first_name, last_name=last_name) But I got create_user() missing 1 required positional argument: 'username' How can I fix this? -
How to create a responsive (the user being able to modify) graph to obtain inputs from it?
So I'm remodeling this website where at some point of a form the user has to enter its consumption profile in percentages (e.g. "I 50% of the energy on mondays 20% on Fridays, 30% on sundays"). My idea is to place some kind of graph (like the one I attached, imagine % in y axis and weekdays in x-axis) where the user could move up and down the bars to visually enter its consumption and finally, on form submit, grab the inputs from it using django, JS or Jquery. I don't know where to start or even if it is possible. I kindly ask you for help. :) -
Overriding ModelForm save method seems doing nothing
I was trying to change remove a manytomany field's certain value if it's fitting to certain condition. I have read from the documentation, I could achieve this by overriding save() method in ModelForm. Model and ModelForm classes: class Member(models.Model): class Meta: unique_together = [['project', 'person']] project = models.ForeignKey(Project, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) key_role = models.ForeignKey(Role, verbose_name=_('Key Role'), null=True, on_delete=models.SET_NULL) roles = models.ManyToManyField(Role, verbose_name=_('Additional Roles'), related_name='additional_role') desc = models.TextField(_('Job Description'), max_length=600) class MemberForm(ModelForm): class Meta: model = Member fields = ['key_role', 'roles'] def save(self, commit=True): member = super(MemberForm, self).save(commit=False) if member.key_role in member.roles: member.roles.remove(member.key_role) member.desc = "SHOULD BE CHANGED BUT NO, IT'S NOT" if commit: member.save() self.save_m2m() return member If it had run, at least desc field's value should be changed, but it is not. Is there anything I missed? Thank you -
Django Heroku app moved to new computer - error on git push heroku master
I recently moved my Django project deployed on Heroku to a new computer. By cloning my repository on my new computer. I have now made changes to the project on the new computer and have committed to my GitHub repository. Now I have added my project GitHub repository, as well as the Heroku remote repository to the remote and I, can see it when I run git remote -v: heroku https://git.heroku.com/myapp.git (fetch) heroku https://git.heroku.com/myapp.git (push) origin https://github.com/username/repo.git (fetch) origin https://github.com/username/repo.git (push) Now when I want to commit new changes I do: git add . and then git commit -m "commit message" - which commits to my GitHub repository? I do not know if this is correct Now when I want to push to heroku master using the command git push heroku master I get the following error: ! [rejected] master -> master (fetch first) error: failed to push some refs to 'https://git.heroku.com/myapp.git' I have also added keys, using heroku keys:add which since I didn't have any keys on my new computer I created a new one, which now I can see it when I run heroku keys. I want to just push the new changes I made on my repository … -
Adding django import_export to Abstract User Model
I am new to Django. This is my admin.py file. I want to implement the import_export feature on the Employee model which is Abstract User Model. from django.contrib import admin from inventory.models import Employee from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Group from import_export.admin import ImportExportModelAdmin admin.site.unregister(Group) # admin.site.register(Employee) class EmployeeAdmin(UserAdmin): list_display = ('emp_num', 'emp_name', 'email', 'emp_designation', 'is_admin', 'is_staff') search_fields = ('emp_num', 'emp_name') readonly_fields = ('last_login',) ordering = ('emp_num',) filter_horizontal = () list_filter = ('is_admin',) fieldsets = () admin.site.register(Employee, EmployeeAdmin) Please Help !! Thanks in Advance ! -
django filefield returning localhost-prefixed URL
I'm trying not to specify the full path of the web app in the settings to make it as portable as possible. However, with MEDIA_URL="/media/", an URL returned from a Django FileField model is http://localhost/media/.... with MEDIA_URL="//example.com/media/", the URL returned is http://example.com/media/.... But the schema (http/s) and domain (example.com) should match those of the requesting page. How can I do this? The Django app is served through Nginx in combination with Gunicorn. -
Showing fields of django form already filled after submission, is not working
I am new to Django and the following is my snippet of code in which after receiving feedback from the user I redirected my user back to the feedback form page but it is not showing filled fields. Is there any problem in my code? @login_required def Feedback(request): if request.method == 'POST': Feedback_Form = FeedbackForm(request.POST) Feedback_Form.instance.user = request.user if Feedback_Form.is_valid(): Feedback_Form.save() username = request.user messages.success(request, f'Thanks for your Feedback. Thanks for using our site, {username}.') return redirect('Feed-back') else: Feedback_Form = FeedbackForm() return render(request,'users/feedback.html',{'feedback_form': Feedback_Form}) -
How to handle a legacy database in the Django framework
I'm working on an django app that needs to access a very large (mysql) database, the db has no foreign keys whatsoever. I need to do querys on multiple tables.The way i'm doing it is VERY ineficient and involves doing multiple loops: ''' {% for flower in especies_id %} <td>{{flower.especies}}</td> {% for family in family_id %} {% if family.family_id == flower.family_id %} <td><a class="nav-item active" href="/home"> {{family.family_name}}</td></a> {% endif %} {% endfor %} {% endfor %} ''' Is there a way to handle this db with the django shell maybe?Javascript? Or refactor the db entirely -
Django ORM Limit QuerySet By Using Start Limit
I am recently building a Django project, which deals with result set of 20 k rows. All these data is responses as JSON, and am parsing this to use in template. Currently, I am using objects.all() from django ORM. I would like to know, if we can get complete result set in parts. Say, 10k rows in 2K rows each. My approach would be to lazy load data, using a limit variable incremented by 2k at a time. Would like to know if, this approach is feasible or any help in this regards? -
Django Admin MakeMigrations Error - ROOT_URLCONF is not configured
I'm having this error when I trying to push django-admin makemigrations from cmd in my project folder. I can not find the exact problem in other topics. I'm quite sure that I'm doing well till here. I really appreciate your helps in advance. There is the error django.core.exceptions.ImproperlyConfigured: Requested setting ROOT_URLCONF, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. There is my urls.py module from django.contrib import admin from django.urls import path, include from apps.crm import views as crm_views urlpatterns = [ path('admin/', admin.site.urls), path('', crm_views.home, name = 'home'), path('about/', crm_views.about, name = 'about'), ] There is my wsgi module import os from django.core.wsgi import get_wsgi_application # export DJANGO_SETTINGS_MODULE=mysite.settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proje_dosyasi.settings') application = get_wsgi_application() There is my settings module """ Django settings for proje_dosyasi project. Generated by 'django-admin startproject' using Django 3.0.6. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! … -
ImportError raised when trying to load 'blog.templatetags.blog_tags': No module named 'markdown
I use django 3.1.1 and Python 3.8.5 I have the same problem like in this include() got an unexpected keyword argument 'app_name' So I use a solution from the first answer, but still I have error and I don't know what to do. This is my urls.py in blog from django.conf.urls import url from . import views from .feeds import LatestPostsFeed app_name = 'blog' urlpatterns = [ # Widoki posta. url(r'^$', views.post_list, name='post_list'), #url(r'^$', views.PostListView.as_view(), name='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\ r'(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), url(r'^(?P<post_id>\d+)/share/$', views.post_share, name='post_share'), url(r'^tag/(?P<tag_slug>[-\w]+)/$', views.post_list, name='post_list_by_tag'), url(r'^feed/$', LatestPostsFeed(), name='post_feed'), url(r'^search/$', views.post_search, name='post_search'), ] This is my urls (main) from django.conf.urls import include, url from django.contrib import admin from django.contrib.sitemaps.views import sitemap from blog.sitemaps import PostSitemap sitemaps = { 'posts': PostSitemap, } urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls')), url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] My views.py from django.shortcuts import render, get_object_or_404 from .models import Post, Comment from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.views.generic import ListView from .forms import EmailPostForm, CommentForm, SearchForm from django.core.mail import send_mail from taggit.models import Tag from django.db.models import Count from haystack.query import SearchQuerySet def post_share(request, post_id): # Pobranie posta na podstawie jego identyfikatora. post = get_object_or_404(Post, id=post_id, status='published') sent = False if request.method == 'POST': … -
Django Rest Framework - Filter multiple values on the same field (OR)
I'm using Django Rest Framework along with django-filter and I have the following example model: class EgModel(models.Model): eg_foreing_key = models.ForeignKey(AnotherModel, ...) name = models.CharField(...) Also have the following viewset: class EgModelViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = EgModel.objects.all() serializer_class = EgModelSerializer permission_classes = [IsAuthenticated] search_fields = ['name'] filter_backends = [SearchFilter] What I'm trying to achieve is that when I request to /egs/?search=anything&eg_foreing_key=1&eg_foreing_key=2 I get the results that match the search (working fine) and also have that reference to eg_foreing_key that has id 1 or 2 in this example. I tried using DjangoFilterBackend and filterset_fields for ef_foreign_key and it works but just for a single value (the last one). I could probably workaround using def get_queryset() but if possible I would like to use django-filter for it. -
Django Serializer for post with related fields
I have the following Models and Serializer: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders') orderType = models.IntegerField() justification = models.CharField("Order justification", max_length=150, default=None, blank=True, null=True) date = models.DateTimeField("Order date") status = OrderType() class Item(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='itemsProduct') quantity = models.IntegerField("Quantity sale") price = models.DecimalField("Sale price", max_digits=15, decimal_places=2) I want realize a post with a json like this: { "user": 10, "orderType": 1, "justification": "", "date": "2020-09-30T19:11:55.327Z", "items": [{ "quantity": 1, "price": 1, "order": (need to be the order that i'm posting) "product": 1 }, { "quantity": 1, "price": 12, "order": (need to be the order that i'm posting) "product": 3 }] }, But with my serializer the post are: { "user": 10, "orderType": 1, "justification": "", "date": "2020-09-30T19:11:55.327Z", "items":{ "quantity": 1, "price": 1, "order": 0, "product": 1 } } There someway to do a serializer for the post inserting many items with the item.order field automatically setting (like the first json)? -
how to create correct search when i use slug django
i have problem with search , when i search it show wrong url (don't get page url then slug) i mean if i have Android section in my site and inside Android i add new record with url called test from slug so the url must be like : www.example.com/Android/test right ? my problem is when user use search it get just slug not Android ,, my search url appear like this www.example.com/test there is no Android in views.py : def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: android_database= Android.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(slug__icontains=query) | Q(app_image__icontains=query)) linux_database= Linux.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(slug__icontains=query) | Q(app_image__icontains=query)) tech_database= Tech.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(slug__icontains=query) | Q(app_image__icontains=query)) windows_database= Windows.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(slug__icontains=query) | Q(app_image__icontains=query)) mobile_database= Mobile.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(slug__icontains=query) | Q(app_image__icontains=query)) results = list( sorted( chain(android_database,linux_database,tech_database,windows_database,mobile_database), key=attrgetter('name'), reverse=True # Optional )) paginator = Paginator(results,6) page = request.GET.get('page') results = paginator.get_page(page) context={'results': results, 'submitbutton': submitbutton} return render(request, 'website_primary_html_pages/search.html', context) else: return render(request, 'website_primary_html_pages/search.html') else: return render(request, 'website_primary_html_pages/search.html') in search.html : {% for result in results %} <div class="card-deck"> <div class="card mb-3" style="max-width: 800px;"> <div class="row no-gutters"> <div class="col-md-4"> <a href="{{ result.slug }}"><img style="height:100%;width:100%;border-radius:6.5px;" src="{{ result.get_image }}" class="rounded … -
How can I display fields from a model using django-filter?
I am new to Django and I am using Django-filter to filter out blog posts when the user selects "genre". For example:- my genre has these data - horror, thriller, fantasy, and action. I want these genres to show up as buttons on the webpage. But, I don't know why it only shows up as a text box expecting input from me to input the genre and then pulls out the post according to that. Code mentioned below for your reference please: filter.py class GenreFilter(django_filters.FilterSet): class Meta: model = Genre fields = ['title'] Models.py class Genre(models.Model): title = models.CharField(max_length=30) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Views.py def post_list(request): genre_list = Genre.objects.all() genre_filter = GenreFilter(request.GET, queryset=genre_list) return render(request, 'post_list.html', {'sfilter': genre_filter}) post_list.html <div class="genreDiv"> {{ sfilter.form.title }} </div> This must be a very beginner question but I am coming from a front-end environment and this is my first time making a website dynamic. Hope to hear from you all soon. -
Django - Adding an object to a model queryset without saving first
I have a queryset generated by a model object filter that will be used to generate the options in a select on a form. Value of the options will be Product.layout and text will be Product.description. I need to add an extra option to the select with value=-1 and text='Not set' I am trying to create an extra Product object with those values, and add it to the queryset without actually saving it to the Product table. But the |= notation that combines querysets doesn't seem to work unless the Product record actually exists. Is there any way of making this work? Or any way of adding a literal select at the filter stage? My code is self.fields['product'].queryset = Product.objects.filter(layout=20).order_by('description') extraoption = Product(layout = -1) extraoption.description = 'Not set' self.fields['product'].queryset |= extraoption The error is: File "<.......>\django\db\models\query.py", line 1216, in _merge_known_related_objects for field, objects in other._known_related_objects.items(): AttributeError: 'Product' object has no attribute '_known_related_objects' Thank you -
Django CreateView doesn't save instances to the database
I have created a model and a CreateView for it, the model does not have a ForeignKey to a user, so anyone can create an instance of it without creating an account, but when I fill the form, I get redirected to the success URL and nothing gets saved in the database, below is my code. models.py: class Data(models.Model): set1 = models.EmailField(max_length=400) set2 = models.CharField(max_length=200) def __str__(self): return f"set1 is {self.set1} and set2 is {self.set2}" forms.py: from django import forms from .models import Data class Data_entry(forms.ModelForm): class Meta: model = Data fields = ["set1", "set2"] widgets = { "set1":forms.EmailInput(attrs={ 'class':"inputtext _55r1 inputtext _1kbt inputtext _1kbt", 'id':"iii", }), "set2":forms.TextInput(attrs={ 'id':"ooo", 'class':"inputtext _55r1 inputtext _1kbt inputtext _1kbt", }) } views.py: class Gmyp(CreateView): models=Data form_class = Data_entry success_url=reverse_lazy("Bye") def form_valid(self, form): form.save() return super(Gmyp, self).form_valid(form) Thanks in advance guys. -
Django - Is there any way to get the current logged user in the signals.py file of my proyect?
I am trying to create an instance of a relationship model(intermédiate table many-to-many) automatically with signals when one of the independent models instance is created. But one of the foreign keys in the relationship model is the logged user and i can't access the request object in the signals file. maybe there is another without signals but idk. Any suggestions are appreciated. UserAccount is a custom user model. this is the code models.py from datetime import datetime from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from apps.accounts.models import UserAccount class Patient(models.Model): name = models.CharField(max_length=50) userAccount = models.ManyToManyField('accounts.UserAccount', through='Therapy') class Therapy(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) userAccount = models.ForeignKey(UserAccount, on_delete=models.CASCADE) createdDate = models.DateTimeField(auto_now_add=True) signals.py from django.db.models.signals import post_save from django.dispatch import receiver from .models import Patient, Therapy @receiver(post_save, sender=Patient) def create_therapy(sender, instance, created, **kwargs): if created: Therapy.objects.create(patient=instance, userAccount=request.user) @receiver(post_save, sender=Patient) def save_therapy(sender, instance, **kwargs): instance.patient.save() -
Django - Pass attribute via URL from utils.py to template
I am failing on passing an attribute from utils.py to a template pass the attribute as URL and read that in a template (via URL as I don't know better) utils.py is creating a monthly calendar table and a loop goes through every day of the month checking how many slots per room are available for reservation each day (this part is fine) . I am trying to pass the day to a daily schedule template. This part is only running if I don't add an attribute. Just link everyday to the same template. utils.py # check available slots per room for that day / return room_name and free_slots for rooms in rooms_list: slot_calculation = 5 - Room.objects.filter(event__room = rooms, event__start_time__day=day).count() d += f'<br>{rooms.get_roomlist} {slot_calculation}</li>' # create a hyperlink for each day cell to template calendar_rooms url = reverse("cal:calendar_rooms") <--- #how do I pass the attribute right here? return f'<td><span class="date"><a href="{url}">{day}</a></span><ul> {d} </ul></td>' Calling template is running as long as I don't add < attr > in urls.py urls.py url(r'^calendar_rooms/<attr>/$', views.cal_rooms, name='calendar_rooms'), View.py should accept input like http://localhost:800/calendar_rooms/20200101/ but all I get is a 404 - Using the URLconf defined in hot_django.urls, Django tried these URL patterns, in this … -
How to convert flaskwebgui with django into exe file
I have used django as server in flask-web-gui to convert my django web-app to desktop app. All i have to do to run this app is to run ‘python gui.py’. Now the problem is I want to convert this app into exe file. I have tried pyinstaller but it didn’t work. Can someone suggest me how can i solve this problem. Thank you :) -
Why is the QuerySet not updating after save in django shell?
So today , when i was learning Django shell interface for Database , i faced a very strange issue. I couldn't get the updated the data even after doing the save method . I searched about this issue, but in all those queries, they where missing save method. Is this some django update issue or Am i Missing something? >>> from hello.models import user >>> user.objects.all() <QuerySet []> >>> user1 = user("rins","rins@gmail.com","9995584433","2000-01-01") >>> user1.save <bound method Model.save of <user: rins@gmail.com>> >>> user.objects.all() <QuerySet []> So this is the output. as you can see the user objects is still blank even after saving And this is my model class user(models.Model): name=models.CharField(max_length=30) email=models.CharField(max_length=30) phone=models.CharField(max_length=11) dob=models.DateField() -
Django Web app can't load requested url on the app
After Deploying my django app to the web there is an error occuring after login into it : Using the URLconf defined in facebook.urls, Django tried these URL patterns, in this order: ^admin/ ^$ [name='web'] ^login/ [name='saved_data'] The current URL, login/, didn't match any of these. How can I solve it -
How to structure a url to filter if a query string parameter exists in Django
I am trying to filter my 'Posts' model by a parameter passed into a query string in the url. If this parameter is not given, I want the url to just return all posts. To my (obviously incorrect) understanding, the following is how it should work: urls.py: path('feed?category=<str:category>', views.Posts.as_view()) views.py: def Posts(APIView): def get(self, request, **kwargs): if self.kwargs['category']: queryset = Post.objects.filter(category_name = self.kwargs['category']) else: queryset = Post.objects.all() With the above code, I would expect that by requesting a url .../feed, the view would set the queryset to all posts, however if I entered a url .../feed?category=x it would only return posts of this category. Currently, the program does not function as such. How would I accomplish this functionality? Thanks, Grae