Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django: better way to save publication date
Hey I implemented a very bad solution to get around the datetime issue I was having inorder to save posts and show posts according to user timezone (because the server timing was set to UTC) but I was hoping if someone could help me get a cleaner, more concise way of doing the same thing. I have written down comments in the code but here the summary. The user fills in the publication date and time of the post and sets his timezone in the frontend. Since server is in UTC and suppose the user is from UTC+5, even if the user sets his current time the post will be published 5 hours later. So I Subtract the publication date with the difference of user local time and server time. Here is the code request.POST["datetime] from frontend form filed by the user as a publication date Used string operation to get things like day, month year, hour, and min dateandtime = request.POST["datetime"].split("-") year = dateandtime[0] month = dateandtime[1] day = dateandtime[2][:2] time = dateandtime[2][3:].split(":") hour = time[0] min = time[1] dateandtime = datetime( int(year), int(month), int(day), int(hour), int(min), 0 ) The user also fills in the timezone so I can … -
Django Html İnput Field "> Character
I'm trying to shape up my login page form as per django. I'm facing an extra >" characters at the end of my entry fields. There is the image error. You might need to pay attention to right up corner of the input fields. Is there any idea, where is this "> came from ? Thanks for your time! <form method="POST"> {% csrf_token%} <div class="field"> <span class="fa fa-user"></span> <input type="text" required placeholder="Email Adress" for="{{form.username}}"> </div> <div class="field space"> <span class="fa fa-lock"></span> <input type="password" class="pass-key" required placeholder="Password" for="{{form.password}}"> <span class="show">SHOW</span> </div> <div class="pass"> <a href="#">Forgot Password?</a> </div> <div class="field"> <input type="submit" value="LOGIN"> </div> </form> -
Django how to find sum of reverse FK and its reverse FK
Due to an absolutely fantastic DB design, I've stumbled across an issue. I'm counting the number of reverse FK matches and ITS reverse FK matches (following the method in this SO question: Django QuerySet ordering by number of reverse ForeignKey matches). I tried doing: assert 6 == Model.objects.annotate(counting=Count(f"blah1") + Count(f"blah1__blah2")).get(id=1).counting But I'm getting 6 == 7 as in my query is always giving me an extra 1. Why is that? -
Python words of my message are being cut on my website
I created a simple function that generates numbers between each word of my message. Here is an example : As you can see, the word "message" is being cut. Is there a way to know the numbers of characters left before python will go to the line? I use Django (that's why I can use python) and the picture you saw is the result fo the code displayed on my web-page. Here is the python code: def generate_grid(message): final_message = [] message_split = message.split(" ") words = [] for word in message_split: words.append(list(word)) # if I want to use letter insstead of numbers upper_case_alphabet = string.ascii_uppercase lower_case_alphabet = string.ascii_lowercase for word in words: final_message.append('<strong>') for i in range(len(word)): final_message.append(word[i].upper()) final_message.append('</strong>') random_number = random.randint(1, 3) for _ in range(random_number): random_char = random.randint(0, 9) final_message.append(str(random_char)) return mark_safe(" ".join(final_message)) Here is the HTML code: <div class="col-md-4 white nopadding text-center d-flex flex-column align-self-center justify-content-center"> <div class="sub-lead"> {{ "This is an example message" | generate_grid}} </div> </div> (If there is another way to do it, tell me please :) ) -
How could I send objects from django template to views?
Let's suppose I am sending a dict of objects to html page: {5: [<InterestAnswer: Cat>, <InterestAnswer: Dog>, <InterestAnswer: Parrot>], 6: [<InterestAnswer: Cinema>, <InterestAnswer: Netflix>]} I want to send them from html to views.py as objects, but currently I am receiving them as strings, how could I do that correctly? <form action="." method="post"> {% for key, value in questions.items %} <div class="question"> {{value.0.question}} {% csrf_token %} {% for answer in value %} <div class="answer"> <input type="checkbox" name="answer-checkbox" value="{{ answer }}"> {{ answer }} </div> {% endfor %} </div> {% endfor %} -
Django How to use OuterRef in RawSQL
I have a query that annotates with a subquery. That subquery uses RawSQL, but I can't get it to refer to the outer ID: from django.db.models.expressions import OuterRef, RawSQL table_name = model._meta.db_table model.objects.annotate( blah=RawSQL(f""" WITH RECURSIVE cte AS ( SELECT id, parent_id FROM {table_name} WHERE id = "{table_name}"."id" UNION ALL SELECT t.id, c.id FROM {table_name} t, cte c WHERE t.parent_id = c.id ) SELECT COUNT(*) - 1 FROM cte """, params=(), output_field=BigIntegerField(),) ).values("blah").all()[:5] It's just this line: WHERE id = "{table_name}"."id" where "{table_name}"."id" is incorrect because when I'm doing this counting it just counts the entire table. That's supposed to be the OuterRef("id"), but I can't input OuterRef("id") into params. So how would I refer to the outer ref ID from RawSQL? -
Django configure logging using Gunicorn
Im currently trying to configure logging for my django application using Gunicorn but im not able to get my applications log into a file execpt debug is set to true this is my settings.py logging config: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'formatter': 'simple', 'filename': '/var/log/app/app.log', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file'], 'propagate': True }, } } This is how I start my gunicorn processes: gunicorn App.asgi:application \ --workers $GUNI_WORKERS \ --bind=127.0.0.1:8000 \ --log-level info \ --user=$USER \ --capture-output \ --disable-redirect-access-to-syslog \ --access-logfile /var/log/app/access.log \ --error-logfile /var/log/app/error.log \ --worker-class uvicorn.workers.UvicornWorker I basically just want to print out all logs if debug is set to true at the console and if debug is set false I only want to log to a file. -
Django adds "index" to empty url
I am just learning Django. I can't understand why "index" is being added to the empty URL. I need the address to be http://127.0.0.1:8000/, but in the address bar it immediately changes to http://127.0.0.1:8000/index/. However, if I enter http: // localhost: 8000 / there are no such problems. -
Any way to integrate HTML snippets with django snippets?
I have two extensions installed one is Django (Baptiste Darthenay) and other is HTML Snippets (Mohamed Abusaid). By default every .html file was getting detecting as django-html and it had no intellisense so I changed the file.associations to following: this has solved problem for html files which are not inside **/tempaltes/**/* but anything in side it doesnt have any intellisense at all.