Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django | formfield_for_manytomany - name display in admin
I am just learning Django, please forgive any ignorance here. Here's my models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) admin = models.BooleanField("Admin Status") class Team(models.Model): name = models.CharField("Team Name", max_length=20, default="") admins = models.ManyToManyField(User, related_name="admins") members = models.ManyToManyField(User, related_name="members") Here's my admin.py from django.contrib import admin from .models import Team, Profile from django.contrib.auth.models import User class ProfileAdmin(admin.ModelAdmin): list_display = ('user', 'admin') admin.site.register(Profile, ProfileAdmin) class TeamAdmin(admin.ModelAdmin): list_display = ('name',) def formfield_for_manytomany(self, db_field, request, **kwargs): print(db_field) if db_field.name == "admins": kwargs["queryset"] = Profile.objects.filter(admin=True) return super(TeamAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Team, TeamAdmin) This works perfect, but the admins on my admin page are showing as "Profile object (1)," "Profile object (2)," etc... What am I doing wrong? Or where do I change the way those display? -
How to save state from button input in Django?
I want to have an option to turn on or off certain features using buttons. If the button is clicked = True, enable some option to be visible, if clicked again disable it. I want to have multiple buttons in the same form, but getting it to work with one should be sufficient in order for me to continue. The problem is that if I check it to true and save it, after going to another page the state is lost and reverts back to default. models from django.db import models class Settings(models.Model): enable_name = models.BooleanField() forms from django import forms from . import models class SettingsForm(forms.ModelForm): class Meta: model = models.Settings fields = ["enable_name"] views def settings(request): if request.method == 'POST': form = SettingsForm(request.POST) if form.is_valid(): form.save() return render(request, 'settings.html', {'form': form}) else: form = SettingsForm() return render(request, 'settings.html', {'form': form}) HTML {% block content %} <div class="main"> <form action="{% url 'settings' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <input type="submit" value="save"> </form> </div> {% endblock %} -
Is it possible to return api response instead of model/database in rest framework?
I am proudly say that i am completely newbie. I am trying to understand rest framework model-view relations. But, i have a question which is i couldn't find answer in docs. I want to show some datas from outsources not my database. For example: Receive a post parameters --> SEND ANOTHER POST REQUEST TO ANOTHER SERVER --> RECEIVE RESPONSE and Return Json Response to client/visitor. All of trainings for models and showing items from database but what about if i want to show some data from another sources. Thank you in advance. I will be appreciated if you can share some documentations with me. -
Accessing javascript variables within Django HTML
I'm adding data to include in a form in Chart.js in Django. I originally had: home_data.push({x: "{{transaction.transaction_time.month}}/{{transaction.transaction_time.day}} {{transaction.transaction_time.hour}}:{{transaction.transaction_time.minute}}", y: {{transaction.price}}}) But now what I'm trying to do is adjust the transaction.transaction_time value in order to do this I want to assign it to a separate variable to later get the value of that variable. Here's what I tried doing: var transaction_adjusted = {{transaction.transaction_time}} home_data.push({x: "{{transaction_adjusted.month}}/{{transaction_adjusted.day}} {{transaction_adjusted.hour}}:{{transaction_adjusted.minute}}", y: {{transaction.price}}}) In my console window: I see that the values evaluated such as {{transaction_adjusted.month}} evaluate to nothing. Why is this? -
Can we make two static folders or more and define their roots in STATICFILES_DIRS in django?
Well my question is quite straight forward. Can we have more than one static folders in django project. In case I want to put static files and templates files in each django app dir separately. Is it possible ?. Right now my each app has its template file but the static file is one for all. I want to make that just like template approach. Can i do that. Do i have to define path of each static folder inside my STATICFILES_DIR in settings.py e.g: STATICFILES_DIRS = [ BASE_DIR / "static", '/var/www/static/', 'myapp_1/static/', 'myapp_2/static/' ] -
Django - how to make OR query for unknown number of values
I'm working on small app where user passes list of cities in GET request. I need to fetch all data where given city exists. My current solution works but I'm looking for something more efficient. Currently I'm creating separate array and adding following querySets in loop. Is there a way to make it within one query ? I also thought about raw query but I'm not sure if it is recommended. def get(self, request): search_phrase = request.GET["search"] cities = request.GET["city"].split(",") found_results = [] for city in cities: found_results += Job.objects.filter(position__icontains=search_phrase, city=city) return render(request, "search.html", {"results":found_results}) -
Many to Many - Django - Related Fields
Let's say I have a Django project with a model called "Genres" and another model called "Books." from django.db import models class Genres(models.Model): name = models.CharField(max_length=15) class Books(models.Model): name = models.CharField(max_length=50) genres = models.ManyToManyField(Genres) Setting it up this way, I am able to access a book in my Admin page and view all the genres associated with it. I can also add and remove genres from a book there. Is there a way I can set this up so that I can ALSO open a genre in my admin page and view all the books that fall under that genre, also being able to add and remove books. I want to be able to update what books fall under a genre on the genre itself and have it ALSO update the genres on the books affected. I hope that makes some sense. -
Prevent Importing Duplicate Records In Django Admin Interface
I am trying to prevent importing duplicate records in the Django admin interface. I did this my adding this to my models class ScanData(models.Model): field1 = models.CharField(max_length=30, null=True) field2 = models.CharField(max_length=30, null=True) field3 = models.CharField(max_length=30, null=True) field4 = models.CharField(max_length=35, null=False) field5 = models.CharField(max_length=150, null=True) field6 = models.CharField(max_length=150, null=True) field7 = models.CharField(max_length=150, null=True) field8 = models.CharField(max_length=200, null=True) field9 = models.CharField(max_length=150, null=True) class Meta: constraints = [ models.UniqueConstraint(fields=['field3', 'field5', 'field7'], name='uniqueUploadsOnly') ] However, when I go to the Django admin interface, I can easily import as many duplicates as I want :( What else can I try without much grief? Django is already adding the id primary key, and I have no other single unique field. -
class based views -TypeError: super(type, obj): obj must be an instance or subtype of type
I am building an app in Django, it uses class based views. In my views.py I have this class based view that allows to inspect details of objects in my model Product: class ProductDetailView(DetailView): queryset = Product.objects.all() template_name = "products/detail.html" def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) return context As I try to run the server I get this traceback: Traceback (most recent call last): ... context = super(ProductListView, self).get_context_data(*args, **kwargs) TypeError: super(type, obj): obj must be an instance or subtype of type What is the problem? -
Adding HTML <a> href Attribute to Javascript is not working
I am trying to implement a Live Search using Javascript for my Django Project, I search by words is working but I am only capable of getting Titles only as a result. I am trying to add the Href so that It can direct the title to the url. Here is what I have tried: class Item(models.Model): title = models.CharField(max_length=100) image = models.ImageField(blank=False, upload_to=upload_design_to) price = models.DecimalField(decimal_places=2, max_digits=100) discount_price = models.DecimalField(decimal_places=2, max_digits=100, blank=True, null=True) timestamp = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse("store:product-detail", kwargs={'slug': self.slug}) Here is the views.py class ItemListView(ListView): model = Item paginate_by = 12 template_name = "store/product_list.html" ordering = ['-timestamp'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs_json"] = json.dumps(list(Item.objects.values()),cls=DjangoJSONEncoder) return context Here is the template.html <input id="search_here" class="mb-2 form-control" placeholder="Type to search..."> <!--Card--> <div id="box" class='row card-group'> {% for item in object_list %} <div class="col-4 mb-3"> <div class="card h-100"> <a href="{{item.get_absolute_url}}"> <embed src="{{ item.image.url }}" class="card-img-top" alt="..."/> </a> <div class="card-body"> <h5 class="card-title">{{ item.title }}</h5> <p class="card-text"> {% if item.description %} {{ item.description }} {% endif %} </p> </div> <div class="card-footer"> <small class="text-muted">{{ item.timestamp }}</small> </div> </div> </div> {% endfor %} </div> <!--Card--> Here is the JS <script> const data = '{{qs_json}}' const rdata = JSON.parse(data.replace(/&quot;/g, '"')) console.log(rdata) const input … -
Django user details
I am doing a project in Django. In route /players I have list of all players in my database. On each player's card, I would like to have a link, which redirects me to a player profile, like /players/username. I tried it with some URL parameter but after some attempts I need some help. I know how to do it in Node, but in django it seems a bit complicated for me. I got this error Reverse for 'player-profile' with no arguments not found. 1 pattern(s) tried: ['players/(?P<username>[^/]+)/$'] This is my link on each player card in players.html <a href="{% url 'player-profile' %}" class="btn btn-primary">Profil</a> This is URL pattern in urls.py path('players/<username>/', views.player_profile, name='player-profile') This is player_profile function in views.py def player_profile(request, username): return render(request, 'blog/player_profile.html``` -
Django how to specify custom alias for table in query?
I've got this huge annotation for a query. One of the annotations is a subquery on Postgres (Django 3.1.5) and the only way for it to work is to have that custom alias "U" (shortened for question sake): SELECT ( WITH recursive cte AS ( SELECT id, parent_id FROM hello WHERE id = U."id" UNION ALL SELECT t.id, c.id FROM hello t, cte c WHERE t.parent_id = c.id ) SELECT Count(*) - 1 FROM cte ) AS "num_blah", U."id" FROM "hello" U I still want to use the ORM since the rest of my annotations rely on the ORM (and dynamically generated). So how would I force Django to specify that U? -
workaround for two dimensional Arrays in django
I would like to make a Ingredientslist for recipies(model named articles) and therefore need to assign unique values to Ingredients out of a Many to Many Infredient list. I know that there is no straight forward way to implement a two dimensional array in django but I hope someone here has had this issue and knows a workaround. Here I have my models being part of this issue: class Ingredient(models.Model): name = models.CharField(max_length=200, null=False) kcal = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(800)], blank=True, default=0) carbs = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)], blank=True, default=0) protein = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)], blank=True, default=0) fat = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)], blank=True, default=0) class Article(models.Model): banner = models.ImageField(null=True, default='dashboard-BG.jpg') headline = models.CharField(max_length=200, null=False, default='Unnamed') subtitle = models.CharField(max_length=300, null=False, default='Unnamed') article_body = models.CharField(max_length=4000, null=False, default='Lorem Ipsum') date_created = models.DateTimeField(auto_now_add=True) ingredientList = models.BooleanField(null=True, default=False) ingredients = models.ManyToManyField(Ingredient, blank=True) kcal = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3000)], null=True, blank=True) carbs = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3000)], null=True, blank=True) protein = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3000)], null=True, blank=True) fat = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3000)], null=True, blank=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) ingredients = self.ingredients totalCalories = 0 totalCarbs = 0 totalProtein = 0 totalFat = 0 for i in ingredients: totalCalories += i.kcal totalCarbs += i.carbs totalProtein += i.protein totalFat += i.fat if i == 0: return self.kcal = totalCalories … -
Issue evaluating variable values in Django HTML script?
I am adding data to include in a form in Chart.js in Django. I originally had: home_data.push({x: "{{transaction.transaction_time.month}}/{{transaction.transaction_time.day}} {{transaction.transaction_time.hour}}:{{transaction.transaction_time.minute}}", y: {{transaction.price}}}) But now I want to adjust the transaction.transaction_time value and to do so I want to assign it to a separate variable and then get the value of that variable. Here's what I did: var transaction_adjusted = {{transaction.transaction_time}} home_data.push({x: "{{transaction_adjusted.month}}/{{transaction_adjusted.day}} {{transaction_adjusted.hour}}:{{transaction_adjusted.minute}}", y: {{transaction.price}}}) In my console window: I see that the values evaluated such as {{transaction_adjusted.month}} evaluate to nothing. Why is this? -
Why is my context object in the views.py file causing a particular page to return html code in the browser of my Django app?
I am creating a web app with Django and its standard SQLite3 database. Everything I have put together so far renders exactly as I had planned, however, when implementing a context object into a view class and returning it, the page shows as HTML code only. No errors are given in the terminal except, Not Found: /dist/js/bootstrap.min.js [08/Jan/2021 21:09:01] "GET /dist/js/bootstrap.min.js HTTP/1.1" 404 2857 Views.py def example(request): item = Task.objects.all() context = {'items':item} return render(request, 'example.html', {'header': 'Example', 'title': 'Example'}, context) example.html {% extends 'base.html' %} {% block body %} {% load static %} <br> <div> <table class="table table-hover"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Description</th> <th>Assigner</th> <th>Progress</th> </tr> </thead> <tbody> <tr> {% for item in tasks %} <td>{{ item.id }}</td> <td>{{ item.title }}</td> <td>{{ item.desc }}</td> <td>{{ item.assigner }}</td> <td>{{ item.progress }}</td> {% endfor %} </tr> </tbody> </table> </div> {% endblock %} RETURNS in Browser... 127.0.0.1/8000/example <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to- fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>CLASS&trade; - Example</title> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <link href="/static/css/dashboard.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow"> <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="/">Student Sprint</a> <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search"> <ul class="navbar-nav px-3"> … -
How to create tab views for a website, where each tab acts as a webpgae?
My overall target is to have different tab views that essentially each act like a different web page. I want all pages to have the same starting page but you can change what happens on each one. However they all have the same functions so it should be just having one webpage multiplied a few times. So far this is what I've got. HTML <!DOCTYPE html> <html> <head> <title> </title> </head> <body> <link href="{% static 'homepage/main.css' %}" rel="stylesheet" type="text/css"> <div class="tabcontainer" id="tabcon" style="background-color: aquamarine"> <ul id="navigation1"> <li class="tabli" id="button1"><button class="tabs" >tab 1</button></li> <ul id="navigation2"> <li id="tabli"> <button onclick="newTab()" class="addbut" style="text-align: center"> + </button> </li> </ul> </ul> </div> <div id="smallSearch"> </div> </body> </html> CSS @font-face { font-family: "amazon"; src: local("Abc"), url("/static/homepage/OfficinaSansStd-Bold.otf") format("opentypefont"); } * { margin: 0 auto; outline: 0; } .flexxcontainer { display: flex; flex-direction: row; flex-wrap: nowrap; height: 3.125em; } #title { float: left; font-size: larger; text-align: justify; padding: 0; } button { height: 3.125em; border: none; width: 7.5em; } #myTextInputID::-webkit-input-placeholder { color: #f2f2f2; font-size: 23px; font-family: amazon; } #myTextInputID::-moz-placeholder { color: #f2f2f2; font-size: 23px; font-family: amazon; } #myTextInputID:-ms-input-placeholder { color: #f2f2f2; font-size: 23px; font-family: amazon; } #myTextInputID::placeholder { color: #f2f2f2; font-size: 23px; font-family: amazon; } .search { margin-top: … -
Common file folder design for django and react
I am using django and react as frontend. so my project folder is like this djangoproj/ #django project --djangoproj/ --defapp/ --static/defapp/mysample.wave --frontend/ #react --node_module/ --public/ --src/ I create the wave file by python code and use the file from React frontend For now, I put mysample.wave in static/defapp folder However in this case, frontend react can't access static/defapp directory(is it correct?) Next idea, put the file in frontend/public folder. However is it good?? because frontend and django independency is corrupted. How is the best practice in this case?? -
Theme Mode Saving not working Properly in Django Project using Serializer
I have created a new App called Mode so that the user can choose a Theme either dark or light mode, and my goal was to have it saved unless the user chooses another mode by clicking the other button. So far, I have reached that the user can choose which mode and his choice is saved back in the database but my problem is that when I refresh the page it returns back to the original light mode although it is still in the db showing dark.css and even when I refresh it doesn't change. I am new to Javascript, I am currently learning to debug errors so here is what I am receiving in console: Data: {message: "User don't have a setting."} message: "User don't have a setting." __proto__: Object I am assuming there could be something wrong with the serializer as this error is raised due to it I have set in the views.py Here is the base template: <link id="mystylesheet" href="{% static 'css/app-light.css' %}" type="text/css" rel="stylesheet"> <!-- Mode --> <div id="mode" class="section" style="padding-top: 1rem; padding-bottom: 3rem;text-align: right"> <button onclick="swapStyles('app-light.css')" type="button" class="btn btn-secondary">Light Mode</button> <button onclick="swapStyles('app-dark.css')" type="button" class="btn btn-dark">Dark Mode</button> </div> <!-- Mode --> Javascript <script type="text/javascript"> … -
How to solve “Send to messenger” Plugin problem?
I have the "send to messenger" plugin that supposed to work, but doesn't work. If this helps you in any way that would be supreme. My page: <body> <script> window.fbAsyncInit = function () { FB.init({ xfbml: true, version: 'v9.0' }); FB.Event.subscribe('send_to_messenger', function (e) { console.log(e); }); }; (function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js'; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <div class="fb-send-to-messenger" messenger_app_id="XXXX" page_id="XXXX" data-ref="anything" color="blue" size="large"> </div> </body> The Django view implementation: class MyBot(generic.View): # verify Facebook token def get(self, request, *args, **kwargs): return HttpResponse(verify_fb_token(self.request.GET['hub.verify_token'], self.request.GET['hub.challenge'])) # The dispatch method for attempting to delegate to a method that matches the HTTP method def dispatch(self, request, *args, **kwargs): return generic.View.dispatch(self, request, *args, **kwargs) # Post function to handle messages def post(self, request, *args, **kwargs): # Converts the text payload into a python dictionary incoming_message = json.loads(self.request.body.decode('utf-8')) for entry in incoming_message['entry']: for message in entry['messaging']: print(message) if 'message' in message: try: if 'quick_reply' in message['message']: pass... except Exception as e: print(e) return HttpResponse() I added my webhook to the whitelist, as well as, I allowed the cookies. I used everything in production (Heroku PasS), but the … -
Django db_table schema dynamically
I have 3 schemas on my database. A, B, C. When a user log in my application, I have a field which identifies the client and I need to pass this value to {} which is related to A, B or C schemas from my PostgreSQL database. I need to fill {} from db_table dynamically. Does anyone know how can I do this? I've tried django-tenants with no luck (did everything from docs but with no success). Bellow is a sample of one of my class model. I really appreciate any help. class AcademicUniversity(models.Model): id_unity = models.AutoField(primary_key=True) id_unity_ies = models.CharField(max_length=100, unique=True, null=True) unity_name = models.CharField(max_length=100, null=True) sigla = models.CharField(max_length=100, null=True) co_localidade = models.ForeignKey(Localidade, on_delete=models.CASCADE, db_column='co_localidade', related_name='localidade_unidade_academica', null=True) class Meta: managed = False db_table = '{}"."academicunity'.format() --> here, {} needs to be filled dynamically and will be related to one of my schemas. I've saw related problems to mine but none of them worked for me. -
Docker / Django - Migrate inside a container
everyone. I have Django in Docker and it seems to work pretty normal. But I have added a field in my model. I tried this order: docker-compose up -d docker exec -it ff71e5e414a4 python manage.py makemigrations user No changes detected in app 'user' But they are docker exec -it ff71e5e414a4 python manage.py migrate - No migrations to apply My expected response is to add a new field of existing model to DB Sorry for a nooby question Thank you -
Dynamic required fields according to user's selection in Django form
I would like to make two fields (repertoire and performer) required only if the user selects and submits a type="performance". This is my model: class Event(models.Model): EV_TYPE = ( ('performance', 'performance'), ('other', 'other'), ) title = models.CharField(max_length=200) type = models.CharField(max_length=15, choices=EV_TYPE, default="performance") repertoire = models.ManyToManyField(Work, blank=True) performer = models.ManyToManyField(Profile, limit_choices_to={'role__type__contains': 'Performer'}) My form: class EventForm(forms.ModelForm): class Meta: model = Event fields = [ 'type', 'submitted_by', 'title', 'repertoire', ] My view: def event_create_view(request): if request.method == 'POST': form_event = EventForm( request.POST, repertoire_required=(not (active_user.id == 17)), # if the user is NMS then the repertoire field is not compulsory initial={'submitted_by' : active_user.profile.id} ) form_venue = AddVenueForm() form_profile = ProfileForm() form_work = WorkFromEventForm() if form_event.is_valid(): this_event = form_event.save() return redirect('event-edit', id=this_event.id) This is what I tried. In the above 'form_event.is_valid', I did: if form_event.is_valid(): this_event = form_event.save(commit=False) if this_event['type'] == 'performance' and this_event['performer'] and this_event['repertoire']: this_event.save() return redirect('event-edit', id=this_event.id) This doesn't work though (I still get a 'this field is required' when I submit). How can I achieve what I want to do? Addendum This is also not working: if this_event['type'] == 'performance' and not this_event['performer'] or not this_event['repertoire']: messages.error(request, form_event.errors) else: this_event.save() return redirect('event-edit', id=this_event.id) -
Django - Team/User relationships
I'm at a loss... I'm just learning Django and I am really rather confused about how to make a field work the way I would like it to. I understand that Django has a native "Groups" model. However, I am looking to build my own teams model for customization and practice. Here is my models.py file for my Users app: from django.db import models from django.contrib.auth.models import User class Team(models.Model): members = models.ManyToManyField(User) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) admin = models.BooleanField("Admin Status") Here's where I'm confused. I would like to be able to call the team that the user is part of directly from User.Profile. So, I want to add a field to my Profile class that will automatically populate with the team name when a user is added to a team. A potential problem I can see is that, currently, I can assign a user to multiple teams. This doesn't bother me, perhaps I can have a Profile model field that automatically populates with a list of all the teams that the user is associated with. Regardless, I can't figure out what type of field I would need to use, or how to do this. Does that make … -
How to display all datetime objects in a different timezone in Django
I am relatively new to Django. All of my datetime objects are in UTC and my settings.py file has TIME_ZONE = 'UTC' When these datetime objects show up in my html template using {{obj.datetime}}, they are dislayed in UTC, I want to display them in UTC-5. How can I change this? Note: I am using class-based views -
Django Filter queryset if property exists
I'm attempting to filter out objects that don't have a custom field existing on them. For example: the returned list might have the following properties customfield_1: value customfield_2: value_2 customfield_3: value_3 In the returned list not all objects might have the property customfield_3, so I'd like to filter those values out. Doing something like queryset.exlude(customfield_3=None) does not work because it isn't that the property has a value of null, but that the property does not exist on the object at all. So, is it possible to add a filter to the queryset that checks if the object has the existence of a property?