Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Semantic UI active link with django not working properly
Thank you for trying to help. Here's my problem. I'm starting to do a simple blog project with Django and to learn something new for the styling I'm doing it with Semantic UI. In the menu, I tried to do the active links dynamically and did it with 'active link tags' in Django. It's working properly in the 'About' tab, but the 'Home' tab is constantly active. Here's my code in the template. <div class="ui pointing menu"> <a class="item {% active_link 'home' %}" href="{% url 'home' %}"> Home </a> <a class="item {% active_link 'about' %}" href="{% url 'about' %}"> About us </a> </div> Here is how the menu looks like when I'm on 'About' -
Django - Get image link from form and save to database
My form: <label class="label-input100" for="imagelink">Image Link*</label> <div class="wrap-input100"> <input id="imagelink" class="input100" type="text" name="imagelink" placeholder="Please paste an image link of the item you are donating" required> <span class="focus-input100"></span> </div> I want the user to paste an image link in the input box (For example, https://images.unsplash.com/photo-1481349518771-20055b2a7b24?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8cmFuZG9tfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80), and then have Django associate it with an imagefield, save it, and then I can render it out on another page. My view: (There is a lot of stuff here that do not pertain to my question, I just included it in case it is needed) def donate(request): if request.method == "POST": title = request.POST['donationtitle'] phonenumber = request.POST['phonenumber'] category = request.POST['category'] quantity = request.POST['quantity'] location = request.POST['location'] description = request.POST['description'] date = datetime.datetime.now().date() ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, date = date ) ins.save() # New part. Update donor's stats. UserDetail.objects.filter(user=request.user).update(donations=F('donations') + 1) UserDetail.objects.filter(user=request.user).update(points=F('points') + (quantity * 2)) return HttpResponseRedirect( '/thankyou/', ) return render(request,'donate.html') As you can see above, this view takes data from other parts of the form, and saves them to the database. I am not sure how to do it with the imagelink part of the form, i … -
How to make a user loged in (authenticated) in django with Reactjs? i'm using Django rest api to connect django and react
Here is the view i created in Django Views to verify the if the user is authenticated or not, but even if the user is valide, whene i try to get the currect user i get Null class LoginView(APIView): def get(self,request): data = request.data usr = authenticate(username=data["username"], password=data["password"]) if usr in not None: login(request,usr) return Response(status=status.HTTP_200_OK) else: return Response(status = status.HTTP_404_NOT_FOUND) -
Is it posssible to have a terminal that can ssh using iframe?
I am trying to make a website where you are able to access a docker container using ssh, Is there any way to have a window in the website that shows a terminal. (I was trying to use iframe but had no luck) -
How to display Data of foreign key in Django html page?
I want to display a Company header and the products below its related company. I am new to django i do not understand this fully. My models.py class Company(models.Model): name = models.CharField(max_length=250) def __str__(self): return str(self.name) class Products(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="display") engine = models.CharField(max_length=250, blank=True) cyl = models.CharField(max_length=250, blank=True) bore = models.CharField(max_length=250, blank=True) def __str__(self): return str(self.engine) + " (ref:" + str(self.ref) + ")" My views.py: def Companies(request): context = { 'categories': Company.objects.all() } return render(request, 'product_list.html', context) My html: {% for category in categories %} <h2>{{ category.name }}</h2> {% for item in category.item_set.all %} {{ item_engine }} {% endfor %} {% endfor %} -
how to display an image from a url in django
I am creating a donation web application. Users are able to fill out a form and there donation is submitted into the database. I want to collect an image url, save it to the database, and render it on a separate page. How would I go about doing this? This is the form: <label class="label-input100" for="image">Image</label> <div class="wrap-input100"> <input id="phone" class="input100" type="text" name="image" placeholder="Please enter the url of your image" required> <span class="focus-input100"></span> </div> -
Psycopg2-binary issue
Using Django and using the psycopg2-binary library, and a postgres DB, when i try to makemigrations I get the following error-- ```/Users/renoaverill/codePlatoon/week7/django-todo/project/venv/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so: mach-o, but wrong architecture``` any and all help will be much appriciated! -
Apply filtering in Django-admin inline section
I'm stuck in filtering my Django-admin section using NestedTabularInline. Trying to get it right using a custom Modelform. I want to filter the plan method on the selected plan activity parent. 2 problems: The print(filter_id) generates only output when the first relation is stored in the database, which makes sense. But off-coarse you want to filter your first planmethod as well. I can't figure out how to create the queryset correctly. get(id=11) works but I need to plug in the self.instance in some way. Some suggestions needed here. model.py: class Activity(models.Model): activity = models.CharField(max_length=30, default=0) def __str__(self): return self.activity class Method(models.Model): method = models.CharField(max_length=30) activity = models.ForeignKey(Activity, on_delete=models.CASCADE, null=True) def __str__(self): return self.method class PlanActivity(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE, null=True) activity = models.ForeignKey(Activity, on_delete=models.CASCADE, null=True) position = models.PositiveIntegerField(default=0, blank=False, null=False) class Meta: ordering = ('position', ) class PlanMethod(models.Model): planactivity = models.ForeignKey(PlanActivity, on_delete=models.CASCADE, null=True) method = models.ForeignKey(Method, on_delete=models.CASCADE, null=True) position = models.PositiveIntegerField(default=0, blank=False, null=False) class Meta: ordering = ('position', ) admin.py: class PlanMethodAdminForm(ModelForm): def __init__(self, *args, **kwargs): super(PlanMethodAdminForm, self).__init__(*args, **kwargs) filter_id = self.instance.planactivity_id print(filter_id) self.fields['method'].queryset = Method.objects.filter(activity_id=PlanActivity.objects.get(id=11).activity_id) class PlanMethodAdminInline(SortableHiddenMixin, NestedTabularInline): model = PlanMethod sortable_field_name = "position" extra = 0 form = PlanMethodAdminForm class PlanActivityAdminInline(SortableHiddenMixin, NestedTabularInline): model = PlanActivity sortable_field_name = "position" … -
Django - Filter for Multiple Foreign
Assume I have models like so: class Story(...): name = models.CharField(...) class Chapter(...): title = models.CharField(...) story = models.ForeignKey('Story', ..., related_name='chapters') How can I filter for stories that have chapters with N specifc titles, i.e.: titles = ['Beginning', 'Middle', 'End'] # is there a better way to do this? stories_with_these_chapters = Story.objects.filter( chapters__title = titles[0] ).filter( chapters__title = titles[1] ).filter( chapters__title = titles[2] ) -
How to retain all EXIF metadata in images on a Wagtail website?
Wagtail seems to clear all (EXIF) metadata in generated thumbnails and custom sized copies of an image. Is this correct? Is there a simple Wagtail way, in leaving all the image metadata? (SEO, Copyright...) Thank you! -
How to get a Groupby count for my django template tag?
I'm trying to get a total count of number of times a category has been used. @register.inclusion_tag('blog/components/categories_list.html', takes_context=True) def categories_list(context): categories = Category.objects.all() return { 'request': context['request'], 'categories': categories, 'categories_count': categories.count() } 'categories_count': categories.count() does not work, as it just counts the total amount of objects in categories Is there a simple way on doing this without working too much at the database level? I would like to get a count for the amount of times an object in categories has been used. -
Getting random object of a model with django-rest-framework after applying filters
So going based on this Stack Overflow question: Getting random object of a model with django-rest-framework I am trying to figure out how to do this, but after applying the filter backend. I have this class with these methods class DictionaryRandomView(generics.ListAPIView): def get_queryset(self): return Dictionary.objects.all() def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) And several filter backends (can include if desired). The problem is that I need to apply the filter backend before querying. Should I do this inside the list method, or the get_queryset method? For example, I have levels associated with a dictionary (for learning a language). I want to limit my query to ONLY words with say, level 6, but then get random values (a dynamic number that I can pass as a filter) inside that set. So pseudo-code for what I am trying to do would be something like this: get_random_value("SELECT * FROM dictionary WHERE level = 6") How can I do that in a DRF listAPIView? -
Filtering multiple M2M fields in a queryset - Django
I'm building a search bar for a crm software with DRF and NextJS. Here is a simplified version of my models. class Person(models.Model): name = models.CharField() contact_of = models.ForeignKey( Team, related_name='contacts' class Organization(models.Model): name = models.CharField() contact_of = models.ForeignKey( Team, related_name='org_contacts' class Team(models.Model): name = models.CharField() I want to get a search param and check if there are any organizations or people with that name and I'm struggling to create the appropriate queryset. This is what I tried(and failed) so far. class SearchView(generics.ListAPIView): def get_queryset(self): search = self.kwargs['search'] qs = Team.objects.filter( Q(contacts__name__icontains=search) | Q(org_contacts__name__icontains=search) ) ... A little help from my fellow Djangonauts would be appreciated. -
format='json' has no effect on APITestCase.client.get
I was testing my Django Rest Framework webserver using the APITestCase class. I have multiple tests with the same format and code. Even the backend for parsing the request is the same. But in the case below, it gives me a parse error. the test that gives me the error: def test_friends(self): data = {"type": "friends"} response = self.client.get(path=f"http://127.0.0.1:8000/api/friends", data=data, format='json') json_response = response.json() print(json_response) self.assertEqual(response.status_code, 200) The view for that test : class FriendsListView(APIView): authentication_classes = [authentication.TokenAuthentication, JWTAuthentication] permission_classes = (IsAuthenticated,) def get(self, request): print(request) data = JSONParser().parse(request) return JsonResponse({'the_type': data['type']}, status=200) Any helps that could help this? As I mentioned, I have multiple views with the same code. They work but this one does not work. Except this one is a get request with some JSON data. They are all put or post or delete. The error: {'detail': 'JSON parse error - Expecting value: line 1 column 1 (char 0)'} -
How to add image url field to an html form in django
I am creating a donation web application. Users are able to fill out a form and there donation is submitted into the database, I was wondering how I can have the user submit a url of an image and save it in the database, and then render it on another page. For example (the full form is down bellow), if the user fills out the form and submits a url like https://images.unsplash.com/photo-1481349518771-20055b2a7b24?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8cmFuZG9tfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80, how would I save it to the database and render it out on another page? All help is appreciated. My code is down bellow. Html Form: <label class="label-input100" for="image">Image</label> <div class="wrap-input100"> <input id="phone" class="input100" type="text" name="image" placeholder="Please enter the url of your image" required> <span class="focus-input100"></span> </div> View: if request.method == "POST": image= request.POST['image'] return redirect('thankyou.html') Model: image = models.ImageField(null = True, blank = True) I am always on my computer so feel free to ask if you have any questions -
Django unable to add to ManyToMany field
I have Listings and Watch models. In Watch.listings is a ManyToManyField for Listings. When I try to add a listing to a watch instance it does not get added and I am getting no errors. in models.py: class Listings(models.Model): CATEGORY_CHOICES = [ ("None", "Optional"), ("Home", "Home"), ("Auto", "Auto"), ("Farm", "Farm"), ("Recreation", "Recreation"), ("Sporting Goods", "Sporting Goods"), ("Watercraft", "Watercraft"), ("Electronics", "Electronics") ] user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField(max_length=2000) photoURL = models.URLField(blank=True) category = models.CharField(max_length=15, choices=CATEGORY_CHOICES, blank=True) starting_bid = models.DecimalField(max_digits=12, decimal_places=2) highest_bid = models.DecimalField(max_digits=12, decimal_places=2, blank=True, default=0) date_created = models.DateField(auto_now_add=True) def __str__(self): return f"User: {self.user}, Listing: {self.title}." class Watch(models.Model): listings = models.ManyToManyField(Listings, related_name="watching", blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.user}, watching: {self.listings}" in views.py: def get_listing(listing_id): try: return Listings.objects.get(pk=listing_id) except: return None def get_watching(user): try: return Watch.objects.get(user=user) except Watch.DoesNotExist: return None def watch(request, listing_id): if request.method == "POST": if request.POST["watch"] == "watch": listing = get_listing(listing_id) if not listing: return HttpResponseBadRequest("Bad Request: listing does not exist.") watching = get_watching(request.user) if not watching: # save user to watch and add print("creating and saving to watch list") watch = Watch(user=request.user) watch.save() # saves no errors watch.listings.add(listing) # listing not added to watch print("watch = ", watch) # prints: watch … -
How to set SendGrid API key programmaticaly with Django Anymail
I'm writing multitenant application with Django Anymail and SendGrid. It works great when there is only one SendGrid API key, but every tenant have it's own API key. How can I set API key for every email message sent, so each tenant will use it's own key? I've tried this, but it won't work: msg = EmailMultiAlternatives(...) msg.connection = get_connection('anymail.backends.sendgrid.EmailBackend', api_key='THEACTUALTENANTAPIKEYHERE') msg.send() How can I set API key for every email message sent, so each tenant will use it's own key? -
Django Model From API Call
I would like to take advantage of an API that returns a JSON object. This object I would like to convert into a Django model so that I can interact with it just like a model, but instead of it storing it in the database, the API would act as the database. Is this possible? Does this require a custom "database" backend to accomplish it? The reason why I would like to map the data into a pseudo model is so that I can work with the data in class based views easier. -
Djongo ArrayReferenceField .add() strange behaviour
I have a model that has a Djongo ArrayReferenceField, and when I add elements with .add(), the elements goes to the start of the array and not to the end. For example: collection.elements.add(Element.objects.get(id=1)) collection.elements.add(Element.objects.get(id=2)) collection.elements.add(Element.objects.get(id=3)) And in mongo, the array will be in the order [3,2,1]. How can I avoid this behaviour? Thanks -
How to see posts using functions based view in django?
In my current django project I had to make a function to render the home page so that I could make a form in it, which form is in the base.html so that can be rendered in every page post of the website, the current code is this: def contactView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject, message, email, ['example@gmail.com'], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('home') return render(request, "index.html", {'form': form}) which works, but the view for every post is a class-based-view that display the form perfectly: class PostDetail(generic.DetailView): model = Post extra_context = {'form': ContactForm()} template_name = 'post_detail.html' The only problem is that the form in the homepage works because there is the code, the same code that I do not know how to call into a class (otherwise I would have used a class even for the home) for more detail the urls.py is: from django.urls import path from . import views urlpatterns = [ path('', views.contactView, name = 'home'), path('<slug:slug>/', views.PostDetail.as_view(), name = 'post_detail'), ] Basically, in the post form there is the slug that get added … -
Is it possible to generate hash from a queryset?
My idea is to create a hash of a queryset result. For example, product inventory. Each update of this stock would generate a hash. This use would be intended to only request this queryset in the API, when there is a change (example: a new product in invetory). Example for this use: no change, same hash - no request to get queryset there was change, different hash. Then a request will be made. This would be a feature designed for those who are consuming the data and not for the Django that is serving. Does this make any sense? I saw that in python there is a way to generate a hash from a tuple, in my case it would be to use the frozenset and generate the hash. I don't know if it's a good idea. -
Calculate Sum of aggregated fields in a Subquery
How can I calculate the sum of all aggregated fields in a subquery? For example, I have three models: A, B, C. B has FK to A. C has FK to B. I have a query: A.objects .annotate( total_revenue=Subquery( B.objects.filter(...) .revenue() .values("id") .annotate(b_renevue=Sum("revenue")) ) ) where B.revenue() is a method that sums up all related fields and then multiplies them by one of its fields. The problem is that revenue is aggregated and isn't calculated at the moment when I try to sum it. The original exception is : django.core.exceptions.FieldError: Cannot compute Sum('revenue'): 'revenue' is an aggregate -
How to link a field of a model to another models's field in django?
I want to link first_name and last_name field of my extended user model to the base User of Django so that changing the values of the fields in one model also affects the values in the other model. I have extended the Base User Model to store additional information about the user and I need to enable the users to edit all those values along with first_name and last_name with a single form. class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = "Linked to first_name of base User Model" last_name = "Linked to last_name of base User Model" other fields.... -
extends base html issue
i got main page at index.html , i want to transfer my template to base.html. I used {% extends 'base.html' %} at index.html , but he doesn't see this file with *Unresolved template reference ''base.html'' * folder of base.html: project/templates myproject/app/views.py from django.shortcuts import render def index(request): return render(request, 'mainsite/index.html') project/app/urls.py from django.urls import path from .views import * urlpatterns = [ path('', index, name='home'), ] project/setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainsite.apps.MainsiteConfig', ] project/url.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainsite.urls')), ] -
Wagtail Customising User Account Settings Form With One-to-One Model
I have a model in my app called "portal", in portal/models.py: from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save from wagtail.snippets.models import register_snippet from wagtail.admin.edit_handlers import FieldPanel @register_snippet class StaffRoles(models.Model): role = models.CharField(max_length=154, unique=True, help_text="Create new staff roles here, these roles an be assigned to 'staff' users.") panels = [ FieldPanel('role'), ] def __str__(self): return self.role class Meta: verbose_name = "Staff Role" verbose_name_plural = "Staff Roles" @register_snippet class Staff(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=1024, blank=True) roles = models.ManyToManyField(StaffRoles, blank=True) def __str__(self): return str(self.user.first_name) + " " + str(self.user.last_name) class Meta: verbose_name = "Staff" verbose_name_plural = "Staff" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created and instance.is_superuser: Staff.objects.create(user=instance) Any new superuser is automatically given the Staff model. Any existing (non superuser) user can also be added as Staff. I want Staff members to be able to set a bio and a role. Roles can be added through the Snippets page in Wagtail admin. Right now, Staff is registered as a snippet, this means any Staff member can edit another Staff member's Staff attributes. I want to customise the Wagtail User Account Settings by adding a form to each user's respective …