Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I get my Django serializer to save my foreign key objects?
I'm using Python 3.8 and Django 3. I have the following models. Notice the second has foreign keys to the first ... class ContactMethod(models.Model): class ContactTypes(models.TextChoices): EMAIL = 'EMAIL', _('Email') PHONE = 'PHONE', _('Phone') type = models.CharField( null=False, max_length=5, choices=ContactTypes.choices, ) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) class Meta: unique_together = ('phone', 'email',) class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() Using the Django rest framework, I have crated the following serializers to help save data ... class ContactMethodPhoneSerializer(serializers.ModelSerializer): class Meta: model = ContactMethod fields = ['type', 'phone'] read_only_fields = ['type'] extra_kwargs = {'type': {'default': 'PHONE'}} class CoopSerializer(serializers.ModelSerializer): types = CoopTypeSerializer(many=True, allow_empty=False) addresses = AddressTypeField(many=True) phone = ContactMethodPhoneSerializer() email = ContactMethodEmailSerializer() class Meta: model = Coop fields = '__all__' def to_representation(self, instance): rep = super().to_representation(instance) rep['types'] = CoopTypeSerializer(instance.types.all(), many=True).data rep['addresses'] = AddressSerializer(instance.addresses.all(), many=True).data return rep def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ coop_types = validated_data.pop('types', {}) phone = validated_data.pop('phone', {}) email = validated_data.pop('email', {}) instance = super().create(validated_data) for item in coop_types: coop_type, _ = β¦ -
Division in Django Query
Model: class Vote(models.Model): thumbs_up = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='thumbs_up') thumbs_down = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='thumbs_down') View: qs = Vote.objects.all() percent_min = request.GET.get('min-rating') percent_max = request.GET.get('max-rating') qs = qs.annotate(percent=(Count('thumbs_up')/(Count('thumbs_down')+Count('thumbs_up'))) * 100).filter(percent__gte=percent_min) qs = qs.annotate(percent=(Count('thumbs_up')/(Count('thumbs_down')+Count('thumbs_up'))) * 100).filter(percent__lte=percent_max) I also tried this which also didn't work. qs = qs.annotate(up=Count('thumbs_up', distinct=True), combined=Count('thumbs_up', distinct=True) + Count('thumbs_down', distinct=True), result=(F('up')/F('combined'))*100).filter(result__gte=percent_min) I'm attempting to filter by min and max percentages based on user votes (up and down) but I can't seem to get it to work properly. Using the current code if I, for example, put a maximum percentage of 74% in then it filters out everything rated 100% and leaves the remaining. The opposite happens if I enter 74% as a minimum percentage, it filters everything except those rated 100%. Currently no 0 rated entries as I have to tackle the divide by 0 issue next. Any insights would be greatly appreciated. -
How to split a string in django template [duplicate]
there is a way on how to split a string in template from the previous year which is not already working already on django 3.1 , I'm trying to do some solutions i found online but seems not working already. So how can I split a string inside the template in django? -
Django User Posts filter by year
In Django I needed user Posts filter by year, so I did the following in views: from django.db.models import Count def about (request): model = Book context = { 'books': Book.objects.values('author') .filter(date_posted__year=2019) .annotate(total_books = Count('author')) } In the HTML books.author.id books.author books.total_books It worked, it shows the total but instead of printing de Author username, it prints the Author ID, and the author ID is blank. Django Version 3.0.8 -
How to not refresh a page when a button is pressed
I have been working on a like/unlike function on my django project in which a user can like like a post and if so the user can dislike it like in instagram. Now to finish with this part of the project I need to make the not refresh the page when a like or unlike button is pressed but the problem is that I am very very new to ajax. How can I acomplish this? models.py class Post(models.Model): text = models.CharField(max_length=200) user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username') liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') updated = models.DateTimeField(auto_now=True) created =models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.text) def get_absolute_url(self): return reverse('comments', args=[self.pk]) LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike'), ) class Like(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) def __str__(self): return str(self.post) 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 = Like.objects.get_or_create(author=user, post_id=post_id) if not created: if like.value == 'Like': like.value == 'Unlike' else: like.value = 'Like' like.save() return redirect('home') def home(request): contents = Post.objects.all() context = { "contents": contents, } print("nice2") return render(request, 'home.html', context) urls.py urlpatterns = [ path('', β¦ -
"TypeError: 'module' object is not iterable" after submitting form, while rendering template
I am trying to make an auctions app where as part of the app, users can place bids by submitting the BidForm. In views.py: ''' def listing_page(request, listing_id): listing_selected = Listing.objects.get(pk=listing_id) form = BidForm() bids = [] winning = False if request.user.is_authenticated: person = Person.objects.filter(user=request.user).filter(watchlist=listing_selected) else: person = False if listing_selected.current_bid: bids = Bid.objects.filter(listing=listing_selected) if listing_selected.current_bid.user == request.user: winning = True if request.method == "POST": form = BidForm(request.POST) if not request.user.is_authenticated: # render template with error message if form.is_valid(): bid = Bid() bid.user = request.user bid.listing = listing_selected bid.amount = form.cleaned_data['amount'] bid.save() messages.success(request, 'Bid placed successfully.') return render(request, "auctions/listing_page.html", context={ "listing": listing_selected, "person": person, "num_bids": len(bids) + 1, "winning": winning, 'form': form, 'messages': messages }) else: return render(request, "auctions/listing_page.html", { "listing": listing_selected, "person": person, "num_bids": len(bids), "winning": winning, 'form': form }) ''' When I submit the bid form, I get this error: ''' C:\Users\USERNAME\Documents\cs50_web\commerce\commerce\.venv\lib\site-packages\django\template\defaulttags.py in render values = list(values) ''' What does this error mean? Where should I be looking? Thank you. -
Change request headers between subsequent retries
Consider an http request using an OAuth token. The access token needs to be included in the header as bearer. However, if the token is expired, another request needs to be made to refresh the token and then try again. So the custom Retry object will look like: s = requests.Session() ### token is added to the header here s.headers.update(token_header) retry = OAuthRetry( total=2, read=2, connect=2, backoff_factor=1, status_forcelist=[401], method_whitelist=frozenset(['GET', 'POST']), external_api=self, session=s ) adapter = HTTPAdapter(max_retries=retry) s.mount('http://', adapter) s.mount('https://', adapter) r = s.post(url, data=data) The Retry class: class OAuthRetry(Retry): def increment(self, method, url, *args, **kwargs): # refresh the token here. This could be by getting a reference to the session or any other way. return super(OAuthRetry, self).increment(method, url, *args, **kwargs) The problem is that after the token is refreshed, HTTPConnectionPool is still using the same headers to make the request after calling increment. See: https://github.com/urllib3/urllib3/blob/master/src/urllib3/connectionpool.py#L787. Although the instance of the pool is passed in increment, changing the headers there will not affect the call since it is using a local copy of the headers. This seems like a use case that should come up frequently for the request parameters to change in between retries. Is there a way to change β¦ -
Python Django multiple lines form
I am new to Django and trying to build a form within the page. The form has multiple fields and all the fields are displayed in the same line on the page. I am using the following code in the template: <form action='' method='post'> {% csrf_token %} {{form}} <input type='submit' value='submit'> I want a form that each field appears in a different line. Is there a way to do this from the django framework or css? thanks! -
i can't find Django
After greeting . kindly help me to fix this error below Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? thanks in advance -
Django Girl tutorial ( template extending)
So I got stuck at the template extending page of the django girls tutorial and I hope someone can see what I've done wrong. (I checked if blog/base.html exists and it does) [base.html],1 post_list.html, error -
Show and not show image if button is clicked in javascript
so I have a file button that lets a user select a video to upload it and another button that uploades the video but when a video is selected a preview has to appear before it is uploaded. The problem is that even tho there is no video selected, there is alot of space of where the video should be and the goal that if the video button is not clicked then the video should be on display: none but if it is clicked then the video has too appear. It is like the video or image preview of facebook. const realFileBtn = document.getElementById("id_video"); const customBtn = document.getElementById("custom-b"); customBtn.addEventListener("click", function() { realFileBtn.click(); }); $(document).on("change", ".file_multi_video", function(evt) { var $source = $('#video_here'); $source[0].src = URL.createObjectURL(this.files[0]); $source.parent()[0].load(); }); input { border: none; order: 0; font-family: sans-serif; padding: 5px; border-radius: 7.5px; width: 100%; height: 35px; display: flex; } #custom-b { border: none; font-family: sans-serif; padding: 5px; order: 1; border-radius: 7.5px; width: 15%; display: flex; justify-content: center; } .preview-image { width: 100%; height: 100%; display: flex; order: 0; padding-top: 8px; padding-bottom: 8px; align-self: center; } .uploades .submit-button { border: none; font-family: sans-serif; padding: 5px; order: 2; display: flex; border-radius: 7.5px; width: 100%; margin-top: 16px; β¦ -
How can I specify custom choices for the django_filters DateRangeFilter function?
I am using the django_filters DateRangeFilter() function. My filter class looks like this: class ListingFilter(django_filters.FilterSet): ship_docking = django_filters.DateRangeFilter() class Meta: model = Listing fields = ['orig', 'dest', 'ship_sailing', 'ship_docking'] I want to change the choices of range - default choices are Today, Yesterday, Past 7 days, etc. How can I specify a different list of choices? Thanks and regards...Paul (Django newbie) -
Django .simple_tag multiple arguments
I have a simple tag that takes 2 positional arguments like this: from django import template from django.utils.safestring import mark_safe @register.simple_tag def multi(a,b): html='<h1> a+b </h1> return mark_safe(a+b) and I'm trying to use the function in my html file but I don't know how to pass the second argument, this is how I'm doing it. any ideas how can i get it ? I got an error that says missing 1 required positional argument 'b' {% load my_tags %} {% multi 'text1' 'text2' %} -
JSONField contains in djongo
Hi im trying to know if a list contains another list, for this im using django + djongo, but i dont if i'm doing the query correctly My model is class Item(models.Model): name = models.CharField(max_length= 255) _id = models.ObjectIdField(primary_key = True) sku = models.JSONField(null= True) providers= models.JSONField(null= True) generic = models.JSONField(null= True) is_validated = models.BooleanField(default = False) tags = models.JSONField(null= True) objects = models.DjongoManager() My serializer class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ( '__all__' ) and the query im doing items = models.Item.objects.filter(generic__contains = ['martillo']) if i give a string to the contains lookup it works perfectly but if i give a list to it, it just returns all items in my database What i'm doing wrong? -
Is it safe to put secret key in heroku config
regarding this post: Git/Heroku - How to hide my SECRET_KEY? follow up question here: when you set: heroku config:set SECRET_KEY="..." there is no way for a third party to access the entered secret key, correct? -
django custom blog post urls
I am learning django by building a simple blogging app. While its all but done, I currently have individual posts having a url in the format https://my_site_dot_com/blog/entry/38/ where the number 38 corresponds to the primary key of said post. What i want is it to have the format https://my_site_dot_com/blog/entry/this_is_custom_title/ where "this_is_custom_title" corresponds to the heading of the post. I have no idea how to accomplish this. Can anyone offer any assistance? My model looks like: class Entry(models.Model): entry_title = models.CharField(max_length=50) entry_text = models.TextField() image = models.FileField(upload_to="media", blank=True) entry_date = models.DateTimeField(auto_now_add=True) entry_author = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = "blog" def __str__(self): return self.entry_title I want the entry_title to the the custom url instead of the primary key. My urls.py looks like this: urlpatterns = [ path('', HomeView.as_view(), name="blog-home"), path('entry/<int:pk>/', EntryView.as_view(), name="entry-detail"), path('create_entry/', CreateEntryView.as_view(success_url='/'), name='create_entry'), ] I'm an absolute noob in django and come from android/java. So please give an easy to understand explanation. Thanks in advance -
filtering modelchoicefield by currently logged in user
I have the below modelchoicefield with the values of the dropdown populated by a model query. I want to add a filter too, where the logged in user = the username in the model field (called user), I can't seem to get it working, can you please help? forms.py class UploadFileForm(forms.Form): title = forms.ModelChoiceField(queryset=projects.objects.filter(user=user).values_list('project_name', flat=True).distinct()) file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) views.py def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES, user=request.user) zz = 0 x = request.POST.get('title') -
Authentication credentials were not provided Django on All calls
I am quite new to django and i am trying to use Djoser for Authentication but i am getting "Authentication credentials were not provided" on every call. Following is my settings file. """ Django settings for django_dir project. Generated by 'django-admin startproject' using Django 1.11.5. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os import environ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT_DIR = environ.Path(__file__) - 2 APPS_DIR = ROOT_DIR.path('my_apps') MEDIA_ROOT = str(APPS_DIR('media')) # https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/' # APPS_DIR = os.path.join(BASE_DIR, 'my_apps'), env = environ.Env() # STATIC FILE CONFIGURATION # ---------------------------------------------- STATIC_ROOT = str(ROOT_DIR('staticfiles')) # STATIC_URL = '/static/' STATICFILES_DIRS = ( str(APPS_DIR.path('static')), # str(ROOT_DIR.path('frontend')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) TEMPLATES_DIR = os.path.join(BASE_DIR, 'my_apps/templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'm!nh54$kig!!=in(fqny#grtd!e(_$jjrph-95g0_52xsdw*&c' ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ # django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # new 'allauth', # new 'allauth.account', # new 'allauth.socialaccount', 'rest_auth', 'rest_auth.registration', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', # local apps 'my_apps.users.apps.UsersConfig', ] # β¦ -
How to use dropzonejs with django to submit file and other field on clicking submit button?
My template has 2 fields one is name and other dropzone's dropbox to drop file and a submit button. I had also used autoProcessQueue: false, to upload file on button click but things are not working. Either i am getting multidictkey error or on clicking submit button the progress bar inside the dropzone completes but no actual process starts on page. Do i need to change things in django views as well ? Any body who can give me a rough road map on how in to use django and dropzone (including file handling).It would be of much help. Thanks in advance. -
How do I filter parents properties of ManyToMany Object
I am new to django and had a problem today I have two models, Program and Member. models.py from django.db import models class Program(models.Model): name = models.CharField(max_length=200) fee = models.IntegerField(default=10) # Arbitrary Property class Member(models.Model): programs = models.ManyToManyField(A, related_name='members') name = models.CharField(max_length=200) # I tried this but it gives me all of the sum of all the programs' fees : # fees_for_member = models.IntegerField(default=Program.objects.prefetch_related('members').aggregate(Sum('fee'))['fee__sum']) # This results in an error: # fees_for_member = programs.aggregate(Sum('fee'))['fee__sum'] Each Program has a fee, and Member has an IntegerField called "fees_for_member" or just "fees" whose default value is the sum of all the Program fees the Member has signed up for. My question is, how do I filter just the Programs which the member is in? I have tried Program.objects.prefetch_related('members').aggregate(Sum('fee'))['fee__sum']) but it returns the sum of all the Programs' Fees. I also tried programs.aggregate(Sum('fee'))['fee_sum'] but it gives me this error : AttributeError: 'ManyToManyField' object has no attribute 'aggregate' What can I do for this? I know I am missing something, but I'm not sure what it is. I spent hours searching through Django docs and SO, but I just can't find the answer so any help is appreciated. Thanks in Advance! -
How to remove csrf token from search result url in Django?
I am trying to implement a form for advanced search in django templates using crispy forms. But when I search and get redirected to the results page, I have the csrf token in the URL. http://127.0.0.1:8000/search/?csrfmiddlewaretoken=EjwC5ExYEy8A9j4X9zAqXKIXrKSiApvoUeQYXgr0ieUJmo0m69uJY2zCLFaWz8Xe&name=test_csc&room=&form_index= I do have a POST form later in the index.html file that I use a csrf token with, but even if I remove all instances of {% csrf_token %} anywhere, the url still has the csrf token in it. I do not explicitly mention anything to do with csrf in my views file. The advanced search in index.html: <form action ="{% url 'app:search_results' %}" method="GET" id="form_index"> <div class="form-group"> {% crispy form_index %} </div> </form> <footer class="major"> <ul class="actions special"> <li><button type="submit" class="button" form="form_index" name="form_index">Search</button></li> </ul> </footer> I should mention that form_index is also used as a form to add something to the database. But I did create a separate form specifically for advanced search to test if it changed anything with the csrf in the url, and it didn't: it was still in the url with the separate form. I have read the Django documentation concerning the csrf token. I haven't used {% csrf_token %} with a GET request. I have looked at and β¦ -
How can I combine fields in a Django Queryset?
I am new to Django and I am trying to figure out how to create a Model Multiple Choice Filter. I am currently trying to create a filter that will filter pets by type, for example cat, dog, bird, etc. The problem I'm running into is that there are a bunch of breeds (ex: husky in dogs), so when I do a queryset that orders by animal type I get way more options than I want. Is there a way to make it so the filter will only display the animal type, but when clicked, will actually query for all the breeds within that type? -
Django append on same list from multiple for loop
This may be pretty basic but I am new to Python and Django. So I can use some help. I am trying to appent data from multiple source. My code is: name = [] for i in soup1.find_all('span', class_='one'): name.append(i.text) for i in soup2.find_all('span', class_='two'): name.append(i.text) dict = {'name': name} The problem is I am getting result from the first loop only. Please help to append name from multiple for loops. -
How to use Bootstrap/static files in Django templates
Okay so I know there are a lot of SO questions on this and I have combed through all of them trying to find an answer but nothing is working for me. My issue is that whenever I try to load the static files into a Django template it just won't work. Here is my file structure: MainProjectDir | +-- DjangoProject | | | +-- MainDjangoSub | | | | | +-- __init__.py | | +-- settings.py (all the other usual folders below) | | | +-- StaticPages (this is my App directory) | | | | | +-- templates (will contain all templates for StaticPages app) | | | | | | | +-- StaticPages (directory containing html templates for the Static Pages App) | | | | | | | | | +-- main.html | | | | +-- navbar.html | | | | | +-- __init__.py | | +-- views.py (all other usual app files below) | | | +-- static (contains all static files for the project) | | | | | +-- Bootstrap (subdirectory containing the Bootstrap static files) | | | | | | | +-- css (directory containing all css files from Bootstrap β¦ -
HTML content not updating in Django
I believe I have a quite complex tree structure in my Django project. It's a framework, so, I didn't start it from scratch. My problem happens when I try to make text changes to HTML files and start the browser. Some <file>.html accept those changes, while others do not. The HTML files that do accept those changes are in the test_project directory, the same directory in which I run python manage.py runserver. I would say that it's mandatory to start the server from this directory. If i try the main directory, that includes the primary manage.py i get the error no such table: django_session. The HTML files that do not accept the changes are in the qa folder. What should I do to update the HTML files in both test_project and qa directories? I hope i have put foward enough information. Thank you! . βββ AUTHORS.rst βββ CONTRIBUTING.rst βββ HISTORY.rst βββ LICENSE.md βββ MANIFEST.in βββ Makefile βββ README.rst βββ docs β βββ Makefile β βββ base.rst β βββ conf.py β βββ index.rst β βββ installation.rst β βββ make.bat β βββ settings.rst βββ manage.py βββ qa # DO NOT ACCEPT CHANGES β βββ __init__.py β βββ __pycache__ β β βββ __init__.cpython-37.pyc β¦