Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Populate list in Django using view
I have the following function to read news headlines into a Python list: import requests def us_news_articles(): url = 'https://newsapi.org/v2/top-headlines?country=us&apiKey=### source = requests.get(url) data = source.json() us_news_articles_list = [] for article in data['articles']: us_news_articles_list.append(article) return us_news_articles_list This function works, and I've verified it. Now I want to be able to use this to populate HTML li items I have the following views built: def viz(request): return render(request, 'resume/viz.html') class USNewsArticles(TemplateView): template_name = 'viz' def get_context_data(self, *args, **kwargs): context = { 'articles': us_news_articles(), } return context My URL looks like this path('viz/', views.viz, name='viz') And in my HTML file, I have the following: <ul> {% for article in articles %} <li>{{ article.title }}</li> <ul> <li>{{ article.description }}</li> </ul> {% endfor %} </ul> However, when I deploy the website, I get no list. I believe it's an issue with the view, but I am not well-versed enough in understand views and functions to understand why it will not populate the li items -
serve multiple base64 images to download
My django application has a model with base64 encoded images. I would like to add the option to my ListView to download all the displayed images to the location of the user's choice. Should I create an AJAX view, or can jQuery take care of it? I googled around and I saw some examples of serving a single file to download. But how do I serve all the images at the same time? -
Why does django-dynamic-formset 'add another' button duplicate foreign key field?
I went through the instructions to set up django-dynamic-formset to my project and my specific inline formsets. All of the formsets seem to work except one that includes a foreign key. When I 'add another' it duplicates that field right under it. Before pressing 'add another': After pressing 'add another': The formset: <h3>Services</h3> <div class="row"> {{ services_formset.management_form }} {% for formserve in services_formset %} {{ formserve.non_field_errors }} <div class="container" id="services_formset"> <div class="row" name="service_form"> {% for hidden in formserve.hidden_fields %} {{ hidden }} {% endfor %} {% for field in formserve %} {% if field.name != 'index' and field.name != 'invoice'%} <div class="col-sm"> {{ field.errors }} {{ field|as_crispy_field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endif %} {% endfor %} </div> </div> The javascript: <script type="text/javascript"> $(function() { $('#services_formset').formset({ prefix: '{{ formserve.prefix }}' }); }) </script> -
Django Many to Many Field add() got an unexpected keyword argument 'id'
I want to add items from Available classic to Chosen classic how can i do that as in image below i can get Chosen classic by Profile.objects.get(user=request.user).classic.add(id=2) but i can't add iems from Available classic to Chosen classic any one can help this problem fast please Thanks for all Models.py from django.db import models # Create your models here. from django.utils import timezone from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Language(models.Model): language = models.CharField( max_length=2, choices=[ ('AR', 'Arabic'), ('EN', 'English'), ], default='AR' ) def __str__(self): return self.language class Classic(models.Model): name = models.CharField(max_length=50, blank=False, null=False) music = models.FileField(upload_to='', max_length=100, blank=True, null=True) lang = models.ForeignKey(Language, on_delete=models.CASCADE) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) classic = models.ManyToManyField(Classic, blank=True, null=True) workOut = models.ManyToManyField(WorkOut, blank=True, null=True) chillOut = models.ManyToManyField(ChillOut, blank=True, null=True) romantic = models.ManyToManyField(Romantic, blank=True, null=True) happy = models.ManyToManyField(Happy, blank=True, null=True) sad = models.ManyToManyField(Sad, blank=True, null=True) lang = models.ManyToManyField(Language, blank=True, null=True) def __str__(self): return str(self.user) def update_user_profile(sender, **kwargs): if kwargs['created']: user = Profile.objects.create(user=kwargs['instance']) post_save.connect(update_user_profile,sender=User) Admin.py from django.contrib import admin # Register your models here. from . import models class ClassicAdmin(admin.TabularInline): model = models.Classic class PlayLists(admin.ModelAdmin): inlines = [ClassicAdmin] class Favo(admin.ModelAdmin): filter_horizontal = ['classic'] admin.site.register(models.Language, PlayLists) admin.site.register(models.Profile, … -
Django server shows wrong time
I have a problem with my django server time, it is 2 hours late. I tried to find a solution but whatever i found (as How to change my django server time, or Django documentation) is not what i think I need. Right now my computer's time is 23:14:37 When i write in bash date +%H:%M:%S I will get: (python_env) bash-3.2$ date +%H:%M:%S 23:17:03 So I don't think this is my console problem. But when I am running my server here is what i get: (python_env) bash-3.2$ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. April 04, 2020 - 21:18:47 Django version 2.2.4, using settings 'myVote365.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. The time is now 2 hours late. I have red that it could be because of wrong timezone, but I have my code similar to How to change my django server time LANGUAGE_CODE = 'pl' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True … -
Populate ModelChoiceField via queryset of 3 tables in Django Form
I have this model definition: class Header(models.Model): no = models.CharField(max_length=20, primary_key=True) # Header ID status = models.CharField(max_length=9) class Item(models.Model): header = models.ForeignKey(Header, on_delete=models.CASCADE) # link Header item_no = models.CharField(max_length=20) class Meta: unique_together = (("header", "item_no"),) class Resource(models.Model): no = models.CharField(max_length=20, primary_key=True) name = models.CharField(max_length=50) class Assignment(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) # link Item resource = models.ForeignKey(Resource, on_delete=models.CASCADE) # link Resource class Meta: unique_together = (("item", "resource"),) With this Form: class ItemForm(forms.Form): header = forms. ModelChoiceField(queryset=Header.objects.filter( ??????? )) def __init__(self, resource, *args, **kwargs): super().__init__(*args, **kwargs) self.resource = resource And with this View: def form_function(request): resource = get_resource(request). # gets resource from user and other logics if request.method == 'POST': form = ItemForm(data=request.POST, resource=resource) if form.is_valid(): pass # do something with the form else: form = ItemForm(resource=resource) return render(request, 'template1.html', {'form': form }) So basically the Assignment table links a Resource (let's say the user) to a particular Item In a Form I need to propose a ModelChoiceField (html select) the list of all Headers assigned to current Resource (the Resource is passed in the view to the Form) Translated in SQL "pseudo code" it would become something similar to the following statement: select * from HEADER where NO in ( select … -
Django- How do I get the content of a model thats related to another?
So i'm creating a to-do app. How do I view the tasks linked to the board? Like I understand that the board needs to be the foreign key to task. Here is my code so far: Models.py class Board(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Board") name = models.CharField(max_length=200) class Task(models.Model): board = models.ForeignKey(Board, on_delete=models.CASCADE) admin = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField(default=False) assigned_to = models.CharField(max_length=30) views.py def board_post_detail(request, board_id): obj = get_object_or_404(Board, id=board_id) context = {"object": obj} return render(request, 'boards/board_post_detail.html', context) board_post_detail.html {% block content %} <h1>{{ object.name}}</h1> <p>Created by {{object.admin.username }}</p> {% endblock %} -
how do i resolve this django.core.exceptions.ImproperlyConfigured error
please how do I resolve this. I'm trying to add data on the admin site but I keep getting this error urls.py for btre from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('pages.urls')), path('listings/', include('listings.urls')), path('admin/', admin.site.urls), ] + static(setting.MEDIA_URL, document_root=settings.MEDIA_ROOT) this is what the terminal shows File "C:\Users\David\Envs\btre-project\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'btre.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Problems with real time chat in django project
I have django project with rooms, and i want to create real time chat for rooms with channels library, this chat works with data from url kinda example.com/room_name/person_name, but i have rooms that have static url(example below),how to adjust that for my project. I want to show request.user.username instead of person_name in url, and i want to use room_detail url instead of room_name that i should type every time views.py class RoomDetail(DetailView): model = Room template_name = 'rooms/room_detail.html' context_object_name = 'room_detail' slug_field = 'invite_url' slug_url_kwarg = 'url' consumers.py class Consumer(WebsocketConsumer): def connect(self): self.room_name=self.scope['url_route']['kwargs']['room_name'] self.room_group_name='chat_%s' % self.room_name self.person_name=self.scope['url_route']['kwargs']['person_name'] async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.person_name+" Joined Chat" } ) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.person_name+" Left Chat" } ) async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data=None, bytes_data=None): text_data_json=json.loads(text_data) message=text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type':'chat_message', 'message':self.user+" : "+message } ) def chat_message(self,event): message=event['message'] self.send(text_data=json.dumps({ 'message':message })) urls.py path('rooms/<url>/', RoomDetail.as_view(), name='room_detail'), -
Django - Trying to call a model function from list_display in modeladmin
I'm following along with Mozilla's Django tutorial, currently on this page: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Admin_site I am trying to get the ModelAdmin for the Book model to call a function of the Book model in the list_display of the ModelAdmin. This is to provide a list of genres in the list display. I have the following code in the admin.py file: class BookAdmin(admin.ModelAdmin): list_display('title', 'author', 'display_genre') And in the models.py file: class Book(models.Model): ... def display_genre(self): return ', '.join(genre.name for genre in self.genre.all()[:3]) display_genre.short_description = 'Genre' I believe this was exactly what the tutorial asked me to add to each of these files. Here's is what django tells me when I try to makemigrations: SystemCheckError: System check identified some issues: ERRORS: : (admin.E108) The value of 'list_display[2]' refers to 'display_genre', which is not a callable, an attribute of 'BookAdmin', or an attribute or method on 'catalog.Book'. I'm not sure what I've done wrong Running python 3.6.9 on Ubuntu 18.04.4 -
django | importing two models' stored data in a single html page
I have two views in my views.py as following: def table1(request): template_name = 'tables.html' queryset = one.objects.all() context = { "table1_list": queryset } return render(request, template_name, context) def table2(request): template_name = 'tables.html' queryset = two.objects.all() context = { "table2_list": queryset } return render(request, template_name, context) and the following models in models.py: class one(models.Model): title = models.CharField(max_length=100) explanation = models.CharField(max_length=1000, blank=True, null=True) class two(models.Model): title = models.CharField(max_length=100) explanation = models.CharField(max_length=1000, blank=True, null=True) In my tables.html I want to show the contents from both of these models. I have: <p>Table one content</p> <ul> {% for obj in table1_list %} {{ obj.title }}, {{ obj.explanation }} {% endfor %} </ul> <p>Table two content</p> <ul> {% for obj in table1_list %} {{ obj.title }}, {{ obj.explanation }} {% endfor %} </ul> But since I can just return one view from views.py in urls.py, I cannot return both of the tables. In urls.py I have to write either of the following: urlpatterns = [ url(r'^$', home), url(r'^tables/$', table1), ] or urlpatterns = [ url(r'^$', home), url(r'^tables/$', table2), ] I tried adding both of the tables from the query in views.py as: def table1(request): template_name = 'tables.html' queryset_one = one.objects.all() queryset_two = two.objects.all() context = { … -
How to filter the class to which the model is related in a ManyToManyField relation in Django?
I would like to filter the class Location to which the model House is related. The idea is to limit the choices of Location based on the value of the field country in the admin pannel. Is it something possible and if so, how can I do that? class House(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='country' ) city = models.ManyToManyField( Location, related_name='city' ) Basically I would like someting like that but Django throw an error saying django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. city = models.ManyToManyField( Location.objects.filter(country=country, related_name='city' ) -
JQuery Ajax call refused by Django server in google compute engine. net::ERR_CONNECTION_REFUSED
I have a Django web server with REST API. Front end Ajax is implemented with JQuery. All works in local Mac and Ubuntu. When deployed in google computer engine, web page showed up and subsequence Ajax call failed with error: net::ERR_CONNECTION_REFUSED This application does not have cross domain API calls. It's simply web page ajax call to the same web server. I have firewall rule allow TCP:8000 Ingress http-server IP ranges: 0.0.0.0/0 tcp:8000 Allow 1000 default I also confirmed that Ajax call never reached the server side. It's like refused by google compute engine. What GCP configuration is missing? -
Django : SystemCheckError: System check identified some issues
I have created Django projects before. However this time,I do django-admin startproject myproject and run server python3 manage.py runserver. First I see include() error in urls.py, I removed the include() from admin urlpattern. It then looks like : path(r'^admin/', include(admin.site.urls)). Second, I see another security check problems. Exact message is this : django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. I followed another Stack question with similar problem like me but different Django/Python versions : Django E.408, E.409 and E.410 errors on runserver From reading these, I understood the problem has risen because of incompatible versions of Django/Python. However I still have questions like : I ran the runserver on default settings (settings generated by startproject). Why Django cannot recognize it's own settings ? . In the Stack question above, I tried changing MIDDLEWARE_CLASSES to MIDDLEWARE then it solves this issue and raises another issue of django.core.exceptions.ImproperlyConfigured: WSGI application 'portfolio.wsgi.application' could not be loaded; Error importing module. I … -
Is there a way to renew an existing csrf_token in Django?
Currently I have the following registration form in my django app and I am having problems when I try to reload the registration page, that is, whenever the user types an invalid username, email or password then he/she receives a message about the error but then if he/she types a valid username, email and password, I encounter a 403 Forbidden CSRF verification failed. Request aborted. I believe this happens because a pre-session token is created when the user incorrectly types invalid registration credentials and when new credentials are typed in then there's a mismatch between the new data and what's inside of the csrf_token, so I am thinking I need to destroy the previous created csrf_token and create a new one (please, correct me if I am wrong since most of this stuff is relatively new to me). views.py from django.shortcuts import render, redirect, render_to_response from .forms import UserRegisterForm from django.contrib import messages def register(request): form = UserRegisterForm(request.POST) if request.method == 'POST': if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account {username} has been successfully created!') return redirect('login') else: # display the errors when trying to submit your request return render_to_response('accounts/register.html', {'form':form}) elif request.method == 'GET': form = UserRegisterForm() return … -
How to let user select currency in Django using Django-money?
I am currently working on an online store. I want a user to be able to change their currency option in the header and convert the whole site to the currency choice. I have found app called django-money, which seams to have that functionality, but I cannot find any implementation examples. I want it to work like localize work in django. Having a form that will redirect to URL and saving choice in session and in cookie. This is the example of the language selection code. /template.html <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language" onchange="this.form.submit()"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.code|upper}} </option> {% endfor %} </select> </form> And then whenever I need something to be translated I will use this inside html: {% trans "Some text to translate" %} So is there something similar for currency? What would be the action for the form? Please can somebody help if you have ready solution! I will really appreciate. -
Bootstrap-4: Grid in dropdown
I have a project with django. For the HTML I use Bootstrap 4 and I have the following code: <div class="dropdown-menu dropdown-menu-right scrollable-menu" aria-labelledby="navbarDropdown"> {% for notification in user.notification_set.all %} <a class="dropdown-item px-2" href="{{ notification.url_to_redirect }}"> <div class="row"> <div class="col m-0 p-0"><img src={% static 'open-iconic/svg/badge.svg' %} alt="thumb-up" title=Badge style="width: 16px; height: 16px;"></div> <div class="col m-0 p-0"> {{ notification.text }} {{ notification.created_at }} </div> </div> </a> {% endfor %} </div> This code give me the expected result: But sometimes the sentence of {{ notification.text }} is too long and I obtain this: I would like the following result: I tried to use float or table but I didn't get there. Someone could help me ? -
display '0' in html if QuerySet = []
I am building a view a Django to render how many rows in a field have values greater than 0. So, the view that I am making needs to count the values greater than 0. Django Query to find number of rows with a certain value greater than zero, grouped by user has been extremely helpful, however I am stuck with the result. I can't find a way to tell my view to display '0' on my html page when the querySet = [], and the count when the QuerySet has something in it. class HomeView(View): def get(self, request, *args, **kwargs): count_orders = Item.objects.filter(en_cours_de_reception__gt=0).values('en_cours_de_reception').annotate(count_orders=Count('en_cours_de_reception')) if count_orders == 0: count_orders = '0' return render(request, 'dashboard/index.html', {'count_orders' : count_orders How can I get that done in a Django view? }) -
Django Field 'id' expected but got queryset
I'm facing a problem with a django query. My models: class Mandant(models.Model): Mandant_id = models.AutoField('ID', primary_key= True) Mandant_accn= models.CharField('Kundennummer', max_length=10) Mandant_name = models.CharField('Bezeichnung', max_length=200) def __str__(self): return str(self.Mandant_id) class Meta: app_label ="meas" class Meas_User(AbstractUser): Mandant = models.ForeignKey(Mandant, on_delete=models.CASCADE, null = True) def __str__(self): return self.username I want to select the Mandant object of a specific user. I've tried this: user = Meas_User.objects.get(username=user_name) mandant = Mandant.objects.get(pk=user.Mandant) The second statement leads to this TypeError: TypeError: Field 'Mandant_id' expected a number but got <Mandant: 1>. Why do I get a queryset by using a get method? And how do I select my mandant object? -
dropdown box empty in django when trying to populate values from database
I am new to Django and I was unable to find a fix for this. I am trying to populate a dropdown box with the database values. Here are my files models.py file from django.db import models # Create your models here. class Page(models.Model): title = models.CharField(max_length=60) permalink = models.CharField(max_length=12, unique=True) update_date = models.DateTimeField('Last Updated') bodytext = models.TextField('Page Content', blank=True) def __str__(self): return self.title class Item(models.Model): itemId = models.AutoField(primary_key=True) itemName = models.CharField(max_length = 100, unique=True) itemPrice = models.IntegerField() def __str__(self): return self.itemName forms.py file from django import forms from .models import Item class OrderListForm(forms.Form): itemNames = forms.queryset = Item.objects.all().order_by('itemName') urls.py file from django.urls import path from . import views urlpatterns =[ path('',views.OrderListView.as_view(),name ='hello'), ] views.py file from django.views.generic.edit import FormView from .forms import OrderListForm # Create your views here. class OrderListView(FormView): template_name = "myapp/orderlist.html" form_class = OrderListForm context_object_name = 'itemNames' orderlist.html file <form action="" method = "post"> {% csrf_token %} <label for="Items">Choose an Item:</label> <select id = items > {% for item in itemNames %} <option value = "">{{item.itemName}}</option> {% endfor %} </form> -
Adding a user object to a manytomany field
I'm writing a simple game using Django. My Game model has a many-ti-many field players: class Game(models.Model): ... players = models.ManyToManyField(User, related_name='playing_games', blank=True, null=True, default=None) My current code to add a player to a game: def add_player(self, player) if not player in self.players.all(): self.players.add(player) causes the following ValueError: Cannot add "<User: xyz>": instance is on database "None", value is on database "default" What am I doing wrong? -
Why does objects.create() fail silently?
When I create an object via [model].objects.create() and I set one of the field variables incorrectly, the create will fail. However it even with debug=True it does not produce an exception. E.g. the following fails silently: Email(models.Model): email = models.EmailField() details = {'email': '1234'} # Fails because it is not a valid EmailField Email.objects.create(**details) Why is this, and when I have a large model with lots of fields how can I debug which field is failing? -
Django signals default data working for one child but not for many
I have a signals file that I would like to be run every time a child is created. For some reason, it has created the default information for one child but if another one is added, it does not create the default information. Does not work for other users either, it has for some reason only worked for my account. signals.py file: from django.db.models.signals import post_save from django.dispatch import receiver from children.models import Children from .models import Timeline @receiver(post_save, sender=Children) def init_new_child(instance, created, raw, **kwargs): # raw is set when model is created from loaddata. if created and not raw: Timeline.objects.create(header = "Financial Support", age = "0-4",children=instance) Timeline.objects.create(header = "Financial Support", age = "4-11",children=instance) Timeline.objects.create(header = "Financial Support", age = "11-18",children=instance) Timeline.objects.create(header = "Financial Support", age = "18-25",children=instance) Timeline.objects.create(header = "Educational Support", age = "0-4",children=instance) Timeline.objects.create(header = "Educational Support", age = "4-11",children=instance) Timeline.objects.create(header = "Educational Support", age = "11-18",children=instance) Timeline.objects.create(header = "Educational Support", age = "18-25",children=instance) Timeline.objects.create(header = "Governmental Support", age = "0-4",children=instance) Timeline.objects.create(header = "Governmental Support", age = "4-11",children=instance) Timeline.objects.create(header = "Governmental Support", age = "11-18",children=instance) Timeline.objects.create(header = "Governmental Support", age = "18-25",children=instance) Timeline.objects.create(header = "Charity Support Groups", age = "0-4",children=instance) Timeline.objects.create(header = "Charity Support Groups", age = "4-11",children=instance) … -
Should I need separate virtual environments for every separate Django project
Does every Django project needs a separate virtual environment? Can't I use one of my exciting virtual env ? If I can't, then what's the problem? -
How to store compressed complex data and be able to decompress in Django?
I need to store nested data that consists of dicts, lists and numpy arrays, but it would be really good if after the decompression I could still have the numpy arrays, as opposed to what happens when I use json as a serializer. Is that possible at all? Thanks in advance!