Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-money. When display in template it's showing wrong format of currenncy
I have a problem with displaying currency by django-money module. In template I used 2 options: {{ object.balance }} and {% money_localize object.balance %}. I expected to see on website $100.00, but I got US$100.00. Any ideas, why it's display this way? My model class has field: balance = MoneyField(_('Balance'), max_digits=25, decimal_places=2, default=Money(0, "USD")) -
Django annotate first occurrence of x in sorted queryset
I have a queryset where the owner's objects are displayed first then objects not owned by them are followed. MyModel.objects.annotate( sort=Case( When(owner=self.request.user, then=0), default=1, output_field=IntegerField() ) ).order_by('sort', 'name') Now if that produced the following, how can I annotate the first occurrence that the owner is not the request user so that obj_list[2]['first_occurrence'] = True? obj_list = [ {'owner': 1, 'name': 'B', 'sort': 0}, {'owner': 1, 'name': 'D', 'sort': 0}, {'owner': 6, 'name': 'A', 'sort': 1}, ... ] Alternatively is there a way to get the first occurrence (without regrouping) where request.user != obj.owner so that I can insert an extra table row? {% for obj in obj_list %} {% if obj.first_occurrence %} ... {% endif %} ... {% endfor %} -
Unabe to make migrations to herokuapp: No module named 'django-heroku'
After finally deploying my app to heroku I wanted to make migrations to my postgres database. I ran into a curious error: (movie_app) ejan@linux-nr9m:~/github/Moviebase-web-app> heroku run python manage.p makemigrations Running python manage.py makemigrations on ⬢ rate-star-movies... up, run.2515 (Free) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/checks/model_checks.py", line 15, in check_all_models models = apps.get_models() File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/registry.py", line 178, in get_models self.check_models_ready() File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/registry.py", line 140, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 336, in run_from_argv connections.close_all() File "/app/.heroku/python/lib/python3.7/site-packages/django/db/utils.py", line 219, in close_all for alias in self: File "/app/.heroku/python/lib/python3.7/site-packages/django/db/utils.py", line 213, in __iter__ return iter(self.databases) File "/app/.heroku/python/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in … -
Django Elasticsearch results highlighting problem
I'm making a site, almost finished and I have implemented the basic search into my site using Elasticsearch (5.6) and Haystack. I followed the tutorial, built the indexes connected everything and the search is working. Now I would like to highlight the search results with the query word. ( so if the word is Batman, I would like all instances of the word Batman to be highlighted on the page ). I read through elasticsearch documentation ( https://www.elastic.co/guide/en/elasticsearch/reference/6.4/search-request-highlighting.html ), and there I found examples like: GET /_search { "query" : { "match": { "content": "kimchy" } }, "highlight" : { "fields" : { "content" : {} } } } I'm still not sure how is this supposed to work, I have been searching since yesterday. I downloaded postman and tried getting this to work using that, but honestly I got no idea what I'm doing. Anyone kind enough to point me to some docs or help me out with that one, I really can't seem to work out how is that supposed to work :( Next, after failing with that, I tried this : https://django-haystack.readthedocs.io/en/v2.4.1/highlighting.html The problem here is that I get an <form class="search" method="get"> <i class="fa fa-search search-icon"></i> … -
Unable to run Python Django Oscar sandbox website on Windows
I wanted to learn how to use Django and Oscar to create an e-commerce website. I was initially trying to follow some tutorials but almost all of them use some old version. Finally, I tried to follow the official documentation. The only problem is that the instructions on the website seem to be for Linux. (https://django-oscar.readthedocs.io/en/2.0.2/internals/sandbox.html). Here are my commands I wrote in the terminal: git clone https://github.com/django-oscar/django-oscar.git cd django-oscar virtualenv oscar oscar\Scripts\Activate These commands seem to have created all the folders. However, make sandbox sandbox/manage.py runserver throws an error about the make not being recognized. I installed MinGW on my Windows but this did not seem to make any difference. If I try to run the manage.py runserver command directly. cd sandbox manage.py runserver I get the following error: ModuleNotFoundError: No module named 'django' How can I get the sample Django Oscar project to run? Thanks. -
Strange Bug : List.append in Python erasing precedent input and cloning the new one instead each
Ok I have been working many times with list in python and it s the first time I encounter this problem : Near the strange place I've got this ( simplified ) list = [] dict = {} things = {'1':'Am', '2':'I', '3':'Dumb?'} [...] for key,value in things.items(): if value: dict[key]=value print(dict) list.append(dict) print(list) And get the this result : {'1':'Am'} [{'1':'Am'}] {'2':'I'} [{'2':'I'},{'2':'I'}] {'3':'Dumb?'} [{'3':'Dumb?'},{'3':'Dumb?'},{'3':'Dumb?'}] hinhin, someone have ever get this ? I, m stuck, thank iou :) -
Saleor comes with react by default. Can we have a 'basic' Saleor without frontend frameworks?
I wanted to use Saleor for a "single-type-product" e-commerce website. I installed Saleor yesterday but it has a huge requirements file, including react.js and many other frontend stuff. I don't want them. Is it possible to install Saleor without anything else? Or at least, with the least other requirements? -
Creating own ordering class
I need to order all stories by popularity(rating field), lass added(created_at field) and by genres(genre field(Foreign key)). Now it only works for last added, how can I add two more order in my CustomOrdering class? class CustomOrdering(OrderingFilter): allowed_filters = ['top', 'new', 'genres'] def get_ordering(self, request, queryset, view): params = request.query_params.get(self.ordering_param) if params: fields = [params.strip() for param in params.split(',')] ordering = [f for f in fields if f in self.allowed_filters] if ordering: return ordering return self.get_default_ordering(view) def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering: ordering = ['-created_at'] if ordering: return queryset.order_by(*ordering) return queryset class StoryView(viewsets.ModelViewSet): queryset = Story.objects.all() serializer_class = StorySerializer filter_backends = (CustomOrdering, ) -
django template issue with django admin
from .models import Info from django.forms import ModelForm class NewInfo(ModelForm): class Meta: model = Info #fields = ('first_name', 'last_name', 'address') exclude = () -
Django HTML form input to db.sqlite3
I'm making a simple web server to take html input data and insert it to data base table . I've tried with POST request got into more CSRF troubles , Turned to GET request to go over CSRF (not necessary in my case ) , still not able to make it . myapp/models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=300, unique=True) content = models.TextField() myapp/templates/createpost.html <head> <title>Create a Post </title> </head> <body> <h1>Create a Post </h1> <form action="" method="GET"> {%csrf_token%} Title: <input type="text" name="title"/><br/> Content: <br/> <textarea cols="35" rows="8" name="content"> </textarea><br/> <input type="submit" value="Post"/> </form> </body> </html> myapp/views.py from django.shortcuts import render from .models import Post def createpost(request): if request.method == 'GET': if request.GET.get('title', None) and request.GET.get('content', None): post = Post() post.title = request.GET.get('title', None) post.content = request.GET.get('content', None) post.save() return render(request, 'createpost.html') else: return render(request, 'createpost.html') am using Django 2.2.6 with PyCharm community 2019.2.3 I've been searching for almost 2 days , checked django doc , and stackoverflow answers , none was helpful , I had to ask to make sure its not a version related issue and forgive me if i miss understand a simple point am just a beginner. -
How to validate username in django forms?
Here I am trying to validate username and email in my forms but validating username is not working. But validating email is working fine. How can I validate username here? forms.py class RegisterUserForm(UserCreationForm): def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email__iexact=email).exists(): raise ValidationError('Sorry this email address already exists.') return email def check_username(self): username = self.cleaned_data['username'] if len(username) < 6: raise ValidationError('Username must be 6 characters long.') return username class Meta: model = User fields = ['username', 'password1', 'password2','email'] -
How to avoid integrity errors occuring because of concurrent creations/updates?
So let's say there's a model A which looks like this: class A(model): name = char(unique=True) When a user tries to create a new A, a view will check whether the name is already taken. Like that: name_taken = A.objects.get(name=name_passed_by_user) if name_taken: return "Name exists!" # Creating A here It used to work well, but as the system grew there started to appear concurrent attempts at creating A's with the same name. And sometimes multiple requests pass the "name exists check" in the same few milliseconds, resulting in integrity errors, since the name field has to be UNIQUE, and multiple requests to create a certain name pass the check. The current solution is a lot of "try: except IntegrityError:" wraps around creation parts, despite the prior check. Is there a way to avoid that? Because there are a lot of models with UNIQUE constraints like that, thus a lot of ugly "try: except IntegrityError:" wraps. Is it possible to lock as to not prevent from SELECTing, but lock as to prevent from SELECTing FOR UPDATE? Or maybe there's a more proper solution? I'm certain it's a common problem with usernames and other fields/columns like them, and there must be a … -
How to Log Out from Keycloak from Django Code
Can not log out from keycloak IDP from inside of Django app code. All stackoverflow answers did not work fo me (most are for older version of the components involved), the same goes for the keycloak documentation. Recently another programmer implemented keycloak-based athentication for our Django-based website. Works fine for auth. The app is build by docker, three containers: the website on port 8000, keycloak db (postgres image), keycloak (jboss/keycloak image) on port 8080. Now I have to add "Logout" functionality to it, meaning singing out of keycloak from my Django code, and redirect the user back to the keycloak login screen. Django 2.2 Python 3.5 keycloak 7 social-auth-app-django 3.1.0 social-auth-core 3.2.0 settings.py SOCIAL_AUTH_KEYCLOAK_KEY = '<some keycloak key>' SOCIAL_AUTH_KEYCLOAK_SECRET = 'some keycloak secret' SOCIAL_AUTH_KEYCLOAK_PUBLIC_KEY = 'some public key' SOCIAL_AUTH_KEYCLOAK_AUTHORIZATION_URL = 'http://<some ip>:8080/auth/realms/<some realm>/protocol/openid-connect/auth' SOCIAL_AUTH_KEYCLOAK_ACCESS_TOKEN_URL = 'http://<some ip>:8080/auth/realms/<some realm>/protocol/openid-connect/token' SOCIAL_AUTH_STRATEGY = 'social_django.strategy.DjangoStrategy' SOCIAL_AUTH_STORAGE = 'social_django.models.DjangoStorage' SOCIAL_AUTH_KEYCLOAK_ID_KEY = 'email' SOCIAL_AUTH_POSTGRES_JSONFIELD = True SOCIAL_AUTH_URL_NAMESPACE = 'social' LOGIN_REDIRECT_URL = 'http://<website ip>:8000/' LOGOUT_REDIRECT_URL = 'http://<website ip>:8000/' SOCIAL_AUTH_POSTGRES_JSONFIELD = True SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.mail.mail_validation', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.debug.debug', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'social_core.pipeline.debug.debug', ) docker-compose.yml version: '3' services: web: restart: unless-stopped container_name: web-container build: context: . dockerfile: Dockerfile.dev ports: - "8000:8000" environment: PRODUCTION: 'false' … -
Django Admin Area "TextField" replacement. Issue with greek characters
I have replaced the standard Django "TextField" field with TinyMCE, CKEditor and Froala. When I type a greek word inside the editors (all of them) in the Admin Area, the result in the frontend app is HTML codes. For example, I type my name Αδριανός and I see <p>&Alpha;&delta;&rho;&iota;&alpha;&nu;ό&sigmaf;</p> I use Postgres with encoding=UTF8, Collate=English_United States.1253, CType=English_United States.1253 -
django opened file type to python opened file type
I have a django app that asks the user to upload an image. I get the image from html django. This image I pass to the python script as a parameter. I did a lot of stuff with this image (like using the PIL libraries), the class of the parameter is: 'django.core.files.uploadedfile.InMemoryUploadedFile' But the problem comes when I try to use one function that ask for the predeterminate type of .open() of python, that is: '_io.BufferedReader' Concretely, the function I'm using is: block_blob_service.create_blob_from_stream() (a Microsoft Azure function) So my question is, can I convert from django opened file type to python opened file type? It may be without saving the file and opening again. And, if by any chance, somebody has worked with this library, I've also tried block_blob_service.create_blob_from_bytes() and it's not working (to convert from django to bytes I've just done img = django_input.read() (I get a Bytes type) and block_blob_service.create_blob_from_path(), is not an option, because I can't get the path of the file, nor I don't want to save the image and get a new path. -
How to pass blank=false behavior to model form validation in django?
I have this model: Class MyModel(Model): other_field = CharField(max_length=200, null=True) my_field = BooleanField(null=True) and have this modelform class MyModelForm(ModelForm) class Meta: model = MyModel fields = ('my_field', ) my view: def my_view(request): template_name = 'my_template.html' context = {} if request.POST: my_model_form = MyModelForm(request.POST) if my_model_form.is_valid(): my_model_form.save() return redirect('other_url') else: my_model_form = MyModelForm() return render(request, template_name, context) in template I have: <form method="post" novalidate> <div> {% csrf_token %} {% form.as_p %} </div> <button>Save changes</button> </form> What I expect is that because in my_field I do not have blank=True`` and as a result it isblank=False, and I havenovalidate, I should not be able to save the form. But I see no validation error even if I leave my_field blank. However,other_field``` can not be left blank. -
how to use collapse in dynamic content when retrieving from database?
i have a bootstrap card that contains data retrieved from the database where this card has a card header that includes a link that is used to collapse extra data (hide/show) inside each card. what in my opinion is a logic is to get the id of each card and make the link open the selected card and not as a static card. the problem is that when i click the link nothing happen and there is now error. urls.py path("displaydata/<int:id>/",displaydata,name = "displaydata") views.py def displaydata(request,id): c = cursor.execute('SELECT ID,Nickname_,Date_of_Birth FROM Person_ WHERE ID = id ') print("c ===>",c) while True: result = c.fetchone() if result == Nonedjan: break print("result ===>", result) return redirect("search") return render(request,"displaydata.html",{"c":c}) pictureCard.html <div class="container"> <div class="row justify-content-center"> {% for obj in object_list %} <div class="col-xs-12 col-sm-6 col-md-6 col-lg-4 col-xl-3 mb-5"> <div class="p-2 my-flex-item"> <div class="card innercardzoom"> <div class="inner"> <img src="{% static '/img/card/1.png'%}" class="card-img-top" alt="..."> </div> <h5 class="card-header"> <a class="collapsed d-block" data-toggle="collapse" href="{% url 'displaydata' obj.0 %}" aria-expanded="true" data-target = "#table-collapsed" caller-id ="" aria-controls="collapse-collapsed" id="heading-collapsed"> <i class="fa fa-chevron-down pull-right"></i> details <script type="text/javascript"> $(document).on('click','.collapsed d-block',function(){ $('#heading-collapsed').attr('caller-id',$(this).attr('id')); }); </script> </a> displaydata.html {% for row in c %} <div id="table-collapsed" class="collapse" aria-labelledby="heading-collapsed"> <table class="card-body table-sm table table-hover text-right"> <tbody> … -
Highlight only the row of the specific player
I am developing a game using python and django templates. In the first step, each player enters his/her name(they are playing on different laptops). In the second step, a value. After that, they get the whole input displayed as a dataframe, sorted by their values. Since they should not know about the names of the others, I was thinking of dropping the name collumn using df1 = df.drop(['Position'], axis=1) However, the players should still know which value they inserted, which is why I want to highlight their specific row. Means Player A sees only his row in green, Player B sees only his row in green etc. The highlight would be based on df.style.apply(lambda x: ['background: lightgreen' if x.name == ????? else '' for i in x], axis=1) with x is the amount of players. However, I am not able to connect the specific entered name to the highlight functions I create a form field using django template and python code class Welcome(Page): form_model = 'player' form_fields = ['name'] The entered Name is then saved in the variable self.player.name. -
django - how to download uploaded files through a link
I am uploading a file and saving it on a folder outside the media folder. I want to add a download link in a template to be able to download the file directly. i am not sure what to add in the url,if i shoud add something i tried this in the template it says url not found <a href="{{data.tar_gif.url}}"> Download File</a> views.py def uploaddata(request): if request.user.is_authenticated: if request.method == 'POST': form = uploadform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('file_list') else: form = uploadmetaform() return render(request, 'uploaddata.html', { 'form': form }) else: return render(request, 'home.html') html page <tbody> {% for data in dataset %} <tr> <td>{{data.path_id}}</td> <td>{{ data.tar_gif }}</td> <td> <a href="{{data.document.url}}"> Download File</a> </td> </tr> {% endfor %} </tbody> -
How to change the AJAX - Views workflow in terms of url mapping
I have a working AJAX function and a working views function (to make API calls). But I don't get them work together. I guess that something is wrong with my web applications workflow / sequence of actions. So now the problem is as follows: When i visit http://127.0.0.1:8000/ everything shows up as intended and the team_id gets assigned correctly to the javascript variable when i click any team in the sidebar. When i visit http://127.0.0.1:8000/dashboard/ I get a TypeError, because the views function doesn't know about the required team_id for the API call (because so far nobody selected a team). Thus, the API return is a empty dic which ends up in a TypeError and the page doesn't render. The goal is that a user lands on http://127.0.0.1:8000/dashboard/ and clicks different teams in the sidebar without a page_refresh to update the dashboard accordingly to the fetched data. But to be able to select a team at all, he needs a rendered frontend.. Currently I have the following url mapping structure: from dasocc_app import views from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^$', views.render_landing_page, name='landing_page'), url(r'admin/', admin.site.urls), url(r'about/', views.render_about), url(r'dashboard/', views.team_update, name='team'), url(r'dasocc_app/', include('dasocc_app.urls')) ] This … -
Why migration is not working after pulling from git?
I'm working collaboratively with some members on a Django project. They're working on Windows whereas I'm working on Ubuntu. My problem is, every time I pulled from git and apply python manage.py migrate, and suggest me to enter python manage.py makemigrations --merge. Followed by the suggestion,entered python manage.py migrate, But it showed the following errors: django.db.utils.ProgrammingError: column "first_name" of relation "account_appuser" does not exist django.db.utils.ProgrammingError: column "login_id_id" of relation "account_appuser" does not exist For 1st error, from the migrations file, I delete those addfield operations and for 2nd error,from the migrations file, I delete removefield operations Now, I have to check every migrations file where this kind of problem occurred. On the other hand, other team member didn't face such kind of problem, they only apply python manage.py makemigrations --merge and python manage.py migrate. Is this happening because of different Operating systems? and any alternative solution for this problem. I am new on this site, So please help me by suggestion.Thanks -
Docker Image `httpd` with libapache2-mod-wsgi-py3
I'm currently creating a Dockerfile with a base image httpd:2 And I manually installed libapache2-mod-wsgi-py3 is there a way I can use mod-wsgi for my Django Application on another container? -
creating custom middleware not working in django?
Here I am trying to update user's last time visit by using the custom middleware. But this is not working.It is not updating the last_visit time in the database. What am i doing wrong here ? models.py class Staff(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff') name = models.CharField(max_length=255, blank=True, null=True) last_visit = models.DateTimeField(default=now(), blank=True) views.py class CheckUserLastVisitMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: Staff.objects.filter(pk=request.user.pk).update(last_visit=now()) response = self.get_response(request) return response settings.py MIDDLEWARE = [ 'organization.views.CheckUserLastVisitMiddleware', -
Isn't the html of the form Django displays on the screen?
Django shows you forms when you do basic coding, right? Where is the html of the automatically generated form in windows? So instead of looking for a template folder, once the developer writes the url or views code, he finds the location of the skeleton-only html that Django shows. In my opinion, it looks like it's built somewhere like an "anaconda/envs" contains a separate virtual environment, but I can't find it. Please help. Thank you for reading. work hard. End. nothing. unneccessary. it's maybe path? -
Manipulate Django ManyToManyField() according to category selected in the same model
I have these two models, first having category and second having size related to particular category class MasterCategory(models.Model): category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class MasterSizes(models.Model): category_name = models.ForeignKey(MasterCategory,on_delete=models.CASCADE) category_size = models.CharField(max_length=2) def __str__(self): return self.category_size This is product model where I want to fetch sizes related to selcted category AND let user select multiple sizes at a time. class Product(models.Model): category_name = models.ForeignKey(MasterCategory,on_delete=models.CASCADE) # subcategory_name = models. product_brand = models.CharField(max_length=50) product_title = models.CharField(max_length=50) product_summary = models.CharField(max_length=200) product_description = models.TextField() original_price = models.FloatField() # discount_rate =models.IntegerField(null=True, blank=True) related_size = MasterSizes.objects.filter(category_name=category_name) available_sizes = models.ManyToManyField(related_size,related_name='category_sizes') discount_price = models.FloatField() product_image = models.ImageField() product_size = models.ForeignKey(MasterSizes, on_delete=models.CASCADE) favourite = models.BooleanField(default=False) def __str__(self): return self.product_title How do I filter the ManyToManyField() with the selected category related sizes only ** Right Now** It shows all the sizes in available_sizes But I want to get sizes only related to category selected.