Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django-plolty-dash errors: for ImportError: Can't import 'Dash' from 'dash'
Python version: 3.7.9 Django version: 3.1.1 django_plotly_dash: 1.4.2 I have tried to install dash_plotly_dash package after I tested the Django project could work properly. That is to say, the development server works fine and the webpage can be opened without problems. However, after I install the dash_plotly_dsah package and add the following to the project settings: INSTALLED_APPS = [ ... 'django_plotly_dash.apps.DjangoPlotlyDashConfig', ... ] Immediately, I had an error ImportError: cannot import name 'Dash' from 'dash' (project\app_init_.py) -
A field in my Django model already exists in the PostgreSQL database
I have a Django app with a model MyModel and some field my_field. My PostgreSQL database already has a field of that name under the mymodel table, since it was added manually in the past. When I make migrations, Django generates an AddField operation, which is in conflict. Currently I manually edit every generated migration to remove the conflict. Is there a way to tell Django that the field already exists? Unfortunately this is a live product, so I cannot lose any data. -
Django Football Simulation - Getting "too many redirects" warning when looping through views
I have a list of 16 games to simulate for Week 1 of this football simulation. I have a VIEW called "simulate_game" that kicks off simulation of the first game in the list using list index=0 (redirecting to some other views, html templates in the process), adds 1 to the index variable, and then redirects back to the "simulate_game" view in order to simulate game #2, and so on and so forth. When testing, i keep getting "too many redirects" warnings. Is there a better way to loop through data than this? I've been searching the internet for a while now with no luck. I feel like there is some fundamental concept that i'm unaware of. Thanks! -
Django REST Framework dynamic forms generation
I am using Django REST Framework as my API for a React frontend. I have forms that are dynamically created by the user. A bit like Google Forms. I am having trouble setting up the models for this. For Example, the user wants a CharField, a SelectField, and a Checkbox. I should return a JSON Object representing the fields with their types and attributes like "required", "options" (for a selectfield), etc. As I said, it is like Google Forms. How do I go about this? -
Set up two media directories
I am doing Django project. I installed django-watermark from PyPI to make watermarks on my pictures. Here you see my media directory, when pictures are uploaded to django, they appear in Media root. Next, watermark library grabs those pictures, adds watermarks and drops them to "watermarked" folder. Eventually, pictures have to be fetched from "watermarked" directory. Website works perfectly when debug=True, however on my server (I use AWS, IIS Windows for hosting), when I set debug=False, instead of pictures I get 404 error. My virtual directory for IIS is set to be my Media root directory these are my settings and url files -
Django ORM getting cx_Oracle.DatabaseError: ORA-00933: SQL command not properly ended
I've got class in models: class Region(models.Model): region_id=models.AutoField(primary_key=True,db_column="region_id") region_name=models.CharField(max_length=4000,blank=True,db_column="region_name") def __str__(self): return f"region_id={self.region_id}, region_name={self.region_name}" class Meta: db_table = "regions" Now I'm trying to query database from shell: python manage.py shell >>>s=Region.objects.all() >>>s When I'm connected to PostgreSQL everything is fine, but when I connect to Oracle (has same table) I'm getting "cx_Oracle.DatabaseError: ORA-00933: SQL command not properly ended" doing the same as with PostgreSQL. Is there some bug in cx_Oracle or what? Please help, I spent few hours on that issue. -
How to resolve: TypeError: __init__() got an unexpected keyword argument 'max_Length' I've tried everything
Here's another similar question that didn't worked for me even it's almost the same situation How to resolve TypeError: __init__() got an unexpected keyword argument '_MAX_LENGTH' in Django from django.db import models import string import random def generate_unique_code(): lenght = 6 while True: code = ''.join(random.choices(string.ascii_uppercase, k=lenght)) if Room.objects.filter(code=code).count() == 0: break return code # Create your models here. class Room(models.Model): code = models.CharField(max_Length=8, default="", unique=True) host = models.CharField(max_Length=50, unique=True) guest_can_pause = models.BooleanField(null=False, default=False) votes_to_skip = models.IntegerField(null=False, default=1) created_at = models.DateTimeField(auto_now_add=True) -
Django: How to search through django.template.context.RequestContext
I'm working over tests in Django and faced <class 'django.template.context.RequestContext'>, which I'm trying to iterate through and find <class 'ecom.models.Product'> object inside. test.py def test_ProductDetail_object_in_context(self): response = self.client.get(reverse('product_detail', args=[1])) # assertEqual - test passes self.assertEqual(response.context[0]['object'], Product.objects.get(id=1)) # assertIn - test fails self.assertIn(Product.objects.get(id=1), response.context[0]) views.py class ProductDetailView(DetailView): model = Product def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) data = cartData(self.request) cartItems = data['cartItems'] context['cartItems'] = cartItems return context What's inside response.context: [ [ {'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x7fd80>>, 'request': <WSGIRequest: GET '/1/'>, 'user': <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7fd820>>, ' perms': <django.contrib.auth.context_processors.PermWrapper object at 0x7fd80>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7fd8290>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40} }, {}, {'object': <Product: Pen>, 'product': <Product: Pen>, 'view': <ecom.views.ProductDetailView object at 0x7fd8210>, 'cartItems': 0} ], [ {'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x7fd8240>>, 'request': <WSGIRequest: GET '/1/'>, 'user': <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7fd8250>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x7fd8250>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7fd8290>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40} }, {}, {'object': <Product: Pen>, 'product': <Product: Pen>, 'view': <ecom.views.ProductDetailView object at 0x7fd8210>, 'cartItems': 0} ] ] Type of response.context: <class 'django.template.context.RequestContext'> What's inside Product.objects.get(id=1) … -
Notifications system for User into ManytoMany field
I got an issue I was wondering is there is a way to send a notification from Many to Many to each new user who are integrated to Reservation (notification has to be sent only to new users who belongs to friends). At the Reservation creation, friends == Null and then admin can add some user. Does anyone has an idea about how I can manage to do it? Assume user == reservation admin and friends are user who can only have access to the reservation. class Reservation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) friends = models.ManyToManyField(User,blank=True,related_name='friends_reservation') def notifs_reservation(sender, instance, *args, **kwargs): reservation = instance sender = reservation.user n_seller = reservation.friends notify = Notification(reservation=reservation, sender=sender, user=n_seller, notification_type=7) notify.save() send_mail( subject = "Lorem", message = render_to_string('notifs_reservation.html', { 'sender': reservation.user, 'n_userb': n_seller, 'channel': reservation.slug, }), from_email="example@example.co", recipient_list=[n_seller.email] ) post_save.connect(notifs_reservation, sender=Reservation) -
get_context_data method doesn't work in django
I have a class based view that inherits from CreateView and I have some fields that I want to be sent in the page through context dictionary and the get_context_data doesn't work because non of the context fields doesn't appear in the page. the class: class IncomeCreateListView(CreateView): template_name = 'users/incomes_&_spendings.html' form_class = IncomeCreateForm def get_context_date(self, **kwargs): context = super().get_context_data(self, **kwargs) incomes = Incomes.objects.filter( user=self.request.user, created_date__year=datetime.now().year, created_date__month=datetime.now().month) if datetime.now().month == 1: incomes_last_month = Incomes.objects.filter( user=self.request.user, created_date__year=datetime.now().year - 1, created_date__month=datetime.now().month + 11) else: incomes_last_month = Incomes.objects.filter( user=self.request.user, created_date__year=datetime.now().year, created_date__month=datetime.now().month - 1) total_incomes = round(assembly(incomes), 2) total_incomes_last_month = round( assembly(incomes_last_month), 2) context['title'] = 'Incomes' context['object_name'] = 'Incomes' context['primary_color'] = 'primary' context['objects'] = incomes context['total_sum'] = total_incomes context['total_sum_last_month'] = total_incomes_last_month context['year'] = datetime.now().year, context['month'] = datetime.now().month, return context def form_valid(self, form): return super().form_valid(form) -
Download zip file with Django from API request
Currently, I am making a call to an API that sends back a zip file. When using request: res = requests.get('http://url/to/api, headers={auth: 'token', Accept: 'application/octet-stream'} I am able to get the binary response content using res.content: Example: b'PK\x05\x06\... Then I return the binary response from my view to my template: return render(request, 'example.html', {'zipfile': res.content} At my example.html, I tried to create a button to download the zip file using: <a href="data:application/zip, {{ zipfile }}" download>Download</a> However, I got back a corrupted zip file. I'm quite new to Django, any help here is appreciated, thanks! -
"Send to messenger" Plugin not showing
I stuck at the "send to messenger" plugin, my configs as follow: 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> I added my webhook to the whitelist The Django server 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 allowed the cookies I tried everything in production (using Heroku and ngrok) There is something I missed? -
Django Admin - Create Custom List
I want to create a custom admin view. It should list specific objects from a model and add attributes to it. More precisely, I have the tables Student and Lecture. Lecture has an attribute enrolled_students, which is a Many-to-Many relationship (Student can be enrolled in multiple lectures; a lecture can have many enrolled Students). Students can gain points in a lecture, which determines their grade. Therefore, I would like to provide an admin view, in which all students of a specific lecture are listed, along with their reached points and grade. The grade is computed lazily, as points are changing frequently. How can I implement this? Is this possible using the build-in methods? Thanks a lot!