Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django can not set AppConfig atrribute during ready()
i'm currently trying to set a custom attribute for the AppConfig of one of my project's apps. The point of doing so is, that the code producing the value needs to be run after App initialization. That's when i came accross the ready() method of AppConfig. So suppose i got an app called content my apporach is : from importlib import import_module from django.apps import AppConfig from django.conf import settings class ContentConfig(AppConfig): name = "content" sone_val = None def ready(self): value = ... # some code if value: self.some_val = value The ready() method gets called and at that point the value is correct. However when i try to access this attribute later in views.py via from django.apps import apps as django_apps django_apps.get_app_config("content").some_val the result is None instead. What am I overseeing/missunderstanding here? -
TemplateDoesNotExist Exception - Django is not loading template from namespaced template
I am using Django 2.2.10 I have an app called myapp, and this is my folder structure: /path/to/project ... myapp ... templates myapp index.html When I place index.html in /path/to/project/myapp/templates/index.html I am able to view the template, however, when I place index.html in the correct subfolder (as shown above) and recommended in the Django documentation (as a way of "namespacing"the templates per application). I get the eror TemplateNotFound. This is the relevant portion of my settings.py settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates"), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', ], }, }, ] Why is Django not able to find the template, and how do I fix this? -
API with Signed endpoint security in Django REST framework
I'm looking up on how to develop an API with an API key (for the project) and Auth Token (for the users). I'm interested in this kind of authentification for the API key Binance API but I can't find any information on how to do it. Looking at other exchanges APIs looks like is a standard way to do it. Is there any documentation or tutorial on how to accomplish this kind of API key security? So far I found this https://pypi.org/project/djangorestframework-api-key/ but I think it is not what I'm looking for. -
control image size in bootstrap
I am using Django I am trying to make image slider using bootstrap, this is my code so far {% extends "blog/modelsbase.html"%} {% block content%} <body> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src= "/media/models/dd08-43fc-ae2b-c6bc75ade6f6.jpg" alt="First slide"> </div> {% for image in images %} <div class="carousel-item"> <img class="d-block w-100" src= "{{image}}" alt="Second slide"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </body> {% endblock content%} </html> this is my views.py from django.shortcuts import render import os images = os.listdir('/media/models/model1') def test_model_bt(request): return render(request,'blog/model1.html',{'title':'TEST_MODEL','images':images}) The images are showing correctly,I would like to place the images inside some sort of container to give them max size [800x800] (if they are larger than it reduce size else pass), how can I do it ? Note:for now my code is "mobile friendly" I would like to keep that I got my slider from Carousel · Bootstrap -
How do I insert a pop up with data entery in python?
I'm working on a web app where people can keep a list of all their friends; I'd like to have an image in the center of the dashboard after they login that says "Add a friend" than then triggers a pop up where they can upload their photo, their social media, and contact informations such as email or phone numbers. After clicking done at the bottom of the pop-up form it then exits the pop-up and show the person added at the top hand corner of the dashboard, layed out with their photo, and clickable social media icons. I have no idea what to do or where to start to be honest, as there's no such guide on the internet for such a thing. I reckon that the go-to language for that type of functionality is php, but given that I've already started out with Django, and learned how to create apps, projects, user accounts, logout functionality, and also given the fact that I would like to work with technologies such as machine learning, and deep learning latter down the road I prefer to do everything on python. ALSO, how does one go about creating a fully customizable web app, … -
Django: Can server-generated files be cached by the browser?
In production I have my CSS and JS files minified by a node script when the server loads and then the minified "files" (strings) are held in memory and accessed by a URL such as /min/front.css. The problem I'm finding is that Chrome does not cache these files, probably because it recognises that they are not actually files. I have set the content type / mime type but they are still not getting cached. Is there some way to make them cacheable? This is my url.py and views.py that are serving the minified files: urls.py urlpatterns = [ ... path('min/<file>', views.min), ] views.py command = 'node .node/min.js' output = subprocess.run(command, stdout=subprocess.PIPE, shell=True) minified = eval(output.stdout.decode('utf-8')) def min(request, file): global minified split = file.split('.') ext = split.pop() mime = { 'css': 'text/css', 'js': 'application/javascript', 'html': 'text/html', }[ext] return HttpResponse(minified[file], mime) -
is there a way to scape special character on path, re_path method when redirect occur in Django 2?
I'm wondering if there is a possibility to escape special character as '#' on path and re_path method when dealing with urlpatterns and redirect method on views. My objective here is to redirect to my index template on a specific element that has an id and allows the user to not scroll it down whenever the user wants to follow a specific section on the page. Here is my example: I am trying by using path and re_path but on the browser, I just see that the character is converted as : 127.0.0.1:8000/%23mail-id This is what I want: 127.0.0.1:8000/#mail-id urls.py from django.urls import path, re_path, include from project_app import views # namespace app_name = 'project_app' urlpatterns = [ path('', views.index_view, name='index'), re_path(r'^\#mail-id$', views.index_view, name='index2'), path('email', views.sendMail_view, name='email'), ... ] view.py from django.shortcuts import render, redirect def sendMail_view(request): if request.method == 'POST': ... return redirect('project_app:index2') index.html ... <div class="mail__form" id="mail-id"> <form action="{% url 'my_project:email' %}" method="post" class="form"> ... </form> </div> ... -
Why does the console respond that: Article encountered an unexpected pub_date parameter?
enter image description here I study django and while creating my blog I ran into such a problem enter image description here -
Should I start with Learning Django or Python [closed]
I have chosen to learn web programming and I selected the Django framework as my development choice. However I know that Django is Python based so my question is. Should I start to learn Python first then move to Django or should I learn Django first then commence with Python? -
ModelChoiceField options not taken into account in the HTML rendering
I am currently working on an application and I have a problem with my ModelForm. I feel like the options that I put in my ModelChoiceField is not being taken into account. This is my forms.py: class PlayerModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return '{} from {} at {} '.format(obj.name, obj.team, obj.price) class Form(forms.ModelForm): def __init__(self, contest_id, *args, **kwargs): super(Form, self).__init__(*args, **kwargs) contest = ContestLOL.objects.filter(id=contest_id)[0] teams = contest.teams.all() players = Player.objects.filter(team__in=teams).order_by('-price') self.fields['top'].queryset = players.filter(role='Top') self.fields['jungle'].queryset = players.filter(role='Jungle') self.fields['mid'].queryset = players.filter(role='Mid') self.fields['adc'].queryset = players.filter(role='ADC') self.fields['support'].queryset = players.filter(role='Support') self.fields['top'].initial = players.filter(role='Top')[0] self.fields['jungle'].initial = players.filter(role='Jungle')[0] self.fields['mid'].initial = players.filter(role='Mid')[0] self.fields['adc'].initial = players.filter(role='ADC')[0] self.fields['support'].initial = players.filter(role='Support')[0] class Meta: model = Model fields = {'top': PlayerModelChoiceField( queryset=Player.objects.filter(role='Top'), widget=forms.RadioSelect(), empty_label=None, to_field_name="top"), 'jungle': PlayerModelChoiceField( queryset=Player.objects.filter(role='Jungle'), widget=forms.RadioSelect(), empty_label=None, to_field_name="jungle"), 'mid': PlayerModelChoiceField( queryset=Player.objects.filter(role='Mid'), widget=forms.RadioSelect(), empty_label=None, to_field_name="mid"), 'adc': PlayerModelChoiceField( queryset=Player.objects.filter(role='ADC'), widget=forms.RadioSelect(), empty_label=None, to_field_name="adc"), 'support': PlayerModelChoiceField( queryset=Player.objects.filter(role='Support'), widget=forms.RadioSelect(), empty_label=None, to_field_name="supp") } fields = {'top', 'jungle', 'mid', 'adc', 'support'} This is is my view.py: def contest(request, slug=None): contest = get_object_or_404(ContestLOL, slug=slug) matches= Match.objects.filter(contest=contest.id) form = Form(contest.id, request.POST or None) if form.is_valid(): bet = form.save(commit=False) bet.user = request.user bet.contest = contest bet.save() messages.success(request, 'Bet was saved') form = Form(contest.id) output = { "contest": contest, "form": form, "matches": matches } return render(request, "questions/contest.html", output) And this is … -
What does migrate mean in django?
I'm currently learning Django using python. I'm using the Django website as my reference and there is one line of code that I am supposed to enter " python manage.py migrate'. I'm wondering what does migrate means and what does it do? Thank You! -
Django force_str for table choices returns original value
I have the following model: SERVICE_STATE_RECEIVED = 'RECEIVED' SERVICE_STATE_WAITING_FOR_ASSESSMENT = 'WAITING_FOR_ASSESSMENT' SERVICE_STATE_WARRANTY = 'WARRANTY' SERVICE_STATE_QUOTED = 'QUOTED' SERVICE_STATE_SCHEDULED = 'SCHEDULED' SERVICE_STATE_REPAIRING = 'REPAIRING' SERVICE_STATE_DOWN = 'DOWN' SERVICE_STATE_FINISHED = 'FINISHED' SERVICE_STATE_DELIVERED = 'DELIVERED' SERVICE_STATE_CHOICES = ( (SERVICE_STATE_RECEIVED, _("Recibido")), (SERVICE_STATE_WAITING_FOR_ASSESSMENT, _("Esperando valoración")), (SERVICE_STATE_WARRANTY, _("En Garantía")), (SERVICE_STATE_QUOTED, _("Cotizado")), (SERVICE_STATE_SCHEDULED, _("Programado")), (SERVICE_STATE_REPAIRING, _("En Reparación")), (SERVICE_STATE_DOWN, _("Baja")), (SERVICE_STATE_FINISHED, _("Servicio Concluido")), (SERVICE_STATE_DELIVERED, _("Entregado")), ) class ServiceStatus(CustomModel): service = models.ForeignKey(Service, on_delete=models.PROTECT, related_name='status', verbose_name=_("Servicio")) status = models.CharField(max_length=25, choices=SERVICE_STATE_CHOICES, verbose_name=_("Estatus")) timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y Hora")) comment = models.TextField(null=True, blank=True, verbose_name=_("Comentarios")) update = False class Meta: verbose_name = _("Estado del Servicio") verbose_name_plural = _("Estados de los Servicios") def __str__(self): return "[{}] {}/{}/{}".format(self.id, self.service.id, self.status, self.timestamp) And the following serializer: class ServiceForListSerializer(CustomModelSerializer): product = serializers.SerializerMethodField() serial_number = serializers.SerializerMethodField() reception_date = serializers.SerializerMethodField() status = serializers.SerializerMethodField() class Meta: model = models.Service fields = ('id', 'product', 'serial_number', 'client_name', 'client_phone', 'comment', 'reception_date', 'status') def get_product(self, instance): product = instance.item.product.name return product def get_serial_number(self, instance): serial_number = instance.item.serial_number return serial_number def get_reception_date(self, instance): reception_date = instance.status.all().order_by('timestamp').first().timestamp reception_date_to_return = reception_date.strftime("%d/%m/%Y") return reception_date_to_return def get_status(self, instance): status = instance.status.all().order_by('timestamp').last().status status_to_return = force_str(status) return status_to_return I want the field status to bring the verbose content of choices tupple, but I get the string value in the database: I … -
getting an image from static/img into a template in Django
I have a Django project with a static/img folder I want to get this image loaded but since it's in a variable and static points to my static folder, not static/img I'm not sure how to get it in. I tried f'img/{project.image}' project.image is set to equal "01.jpg" <img class="card-img-top" src="{% static project.image %}"> -
Django Query For Max Value For Column Which Includes Foreign Key Table Also In Result
I have two related models - class Auction(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False) # other properties and class MaxBid(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False) value = models.DecimalField( decimal_places=2, max_digits=10, validators=[MinValueValidator(MINIMUM_TRANSACTION_VALUE)] ) created = models.DateTimeField(default=timezone.now) auction = models.ForeignKey( 'Auction', on_delete=models.CASCADE, related_name='bids' ) user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name="bids" ) I want to get the maximum bid a user has made in an auction and the auction columns in a SINGLE django SQL query. This SO question - SQL select only rows with max value on a column - has helped me to see a way of doing it in raw sql - SELECT * FROM "products_maxbid" as m JOIN "products_auction" as a on m.auction_id = a.uuid WHERE m.uuid in ( SELECT m.uuid FROM "products_maxbid" as m INNER JOIN ( SELECT auction_id, Max(value) as value FROM "products_maxbid" WHERE user_id = '2' GROUP BY auction_id ) n on m.auction_id = n.auction_id and m.value = n.value and m.user_id = '2' ) ORDER BY a.square_id # can apply any orders now to the auction table like normal I don't know where to begin to achieve this in Django - well, the docs obviously, but nothing stands out in there. All I've worked out is the … -
GeoDjango Point fields widget does not show coords properly
in a Django application I use PointField point = models.PointField(_('Point'), null=False, blank=False) I use normal long lat system, so [50, 15] should be a point in Europe, in the Czech Republic I think. But then in the administration there is a nice interactive widget with a map which shows the point somewhere in the Red sea. When I check the value in the code of the widget It says the coords are completely different (some numbers in millions), but when I want to output the coords to the console, it says normaly [50, 15] print(Datapoint.objects.get(pk=pk).point) # Output: SRID: 4326; Point(50, 15) Does anyone have an idea what could go wrong here? I know there are more SRIDs, but even when I change every possible SRID attribute (Model, AdminSite, Form, Widget), still does not work... Thanks, RA -
Can I manipulate my django dataset utilizing the view?
I'm developing with django an application for the management of the company budget. All you need to have to work a lot with the db. I noticed that with django to be able to modify the data contained in my db I always have to go through a required view. But, once I have installed the data through a form, I would like to make changes to the dataset? it's possible? I'll give you an example: through my form I collect the data of the monthly collections per business unit: | ____ Jan ____ | ___ Fab _____ | Business unit_1 | ____ 100 ___ | _____ 100 ____ | Business unit_2 | ____ 100 ____ | ____ 100 ____ | If I wanted to have a second db that brings me back the total per month: | ____ Jan ____ | ___ Fab _____ | total | ____ 200 ____ | ____ 200 ____ | And I want that, if I delete a row in business unit, automatically the total is udpdated. Do you think I can do it directly in the view and so utilziing only django?? if yes how? or do you recommend another way ?? -
How to serialize object to json with custom fields in python
I have a class class Person(object): def __init__(self,age,name): self.person_age = age self.person_name = name And i want to serialize object to json. I can do so: person = Person(20,'Piter') person.__dict__ But such an approach will return it: {'person_age':20,person_name:'Piter'} I want serialize my object to json with my own fields. Instead of 'person_age' - 'age'. Instead of 'person_name' - 'name': {'age':20,name:'Piter'} How can this be done if the class has many fields? -
django template rendering using for loop
i am rendering the 4 items in a row through a for loop , the problem is that in the first line it renders 4 items but the rest of the items that come in the loop are rendered in separate line. code <div class="card-group"> {% for item in wt %} <div class="card my-3 text-white bg-dark mb-3" style="width: 18rem;"> <img src="/media/{{item.thumbnail}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{item.product_name}}</h5> <p class="card-text">{{item.thumbnail_desc}}</p> <a href="blog_detail/{{item.post_id}}" class="btn btn-primary">View Product</a> </div> </div> {% if forloop.counter|divisibleby:4 %} </div> {% endif %} {% endfor %} here i am using bootstrap and django framework... i also used "row" class but it also doesnt work very well -
Django| Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user/(?P<username>[^/]+)$']
I am following django tutorial by @CoreyMSchafer. I got error while practicing i can't find solution to it. According to my understanding its problem with reversing of url. but can't find out what is wrong This is what I'm getting as an error Error: NoReverseMatch at / Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user/(?P[^/]+)$'] For some reason error is in head of base.html where I'm linking bootstrap. I also tried removing that link then its giving same error but at line 0 of base.html views.py: class UserPostListView(ListView): model = Post context_object_name = 'posts' template_name = 'blog/user_posts.html' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.all().filter(author= user).order_by('-date_posted') urls.py file: from django.urls import path, include from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeletelView, UserPostListView from . import views urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeletelView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), ] user_posts.html: {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num … -
How do I make changes on a live Django website?
I have a live Django website I need to make changes on and I want to know what's the best / most correct way of updating the code of the website, I have access to the remote server and access to the git. Thanks in advance!!! -
trying to build an app with graphql & Django
I am an inter and they assigned me a new project. I've never used Django before so I'm kinda lost. for this project, I have to use an existing database (SQL server), and so I had to recreate my User class by extending "AbstractBaseUser" and "PermissionsMixin". and as I said it should use graphQL (my first time also) so I am using graphene. I managed to do queries, but when it comes to authentication (using "graphql_jwt"), I can query to get a Token, but when I use the token to authenticate I always get the user not authenticated. (I am using a decorator @ Login_required form graphql_jwt) I think I am failing to understand how the authentication works in Django. can anyone explain it further to me? -
My Django app won't detect settings.py, and won't detect SECRET_KEY
I have a problem with my Django app. For some reason it won't detect settings.py nor SECRET_KEY. First, here is my structure of the project dir C:. │ manage.py │ ├───Accounts │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ __init__.py │ │ │ ├───templates │ │ login.html │ │ signup.html │ │ │ └───__pycache__ │ omitted │ ├───Blog │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ __init__.py │ │ │ └───templates ├───Learning │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ __init__.py │ │ │ └───templates ├───static │ │ compiled_sass.css │ │ compiled_sass.css.map │ │ │ └───sass-styles │ │ styles.sass │ │ │ ├───src │ │ omitted │ │ │ └───static │ omitted │ └───tf │ local_settings.py │ settings.py │ TODO.md │ urls.py │ wsgi.py │ __init__.py │ ├───templates └───__pycache__ omitted Now, when running I get django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. That's how my settings.py look like … -
How do I view and delete an admin migration
I tried running my Django project and I got a warning on unapplied migrations. The problem is, I didn't make any changes that would arouse any migration so I set out to look for the migration files but I couldn't find any. I ran python manage.py showmigrations to see the migrations that were pending I then discovered there were two admin migrations that were pending [ ] 0004_auto_20200124_1105 [ ] 0005_auto_20200124_1107 I've been trying all day to trace these files or to even see the changes to no avail. Please help -
Django how to display choosen file name on custom input file?
Hae all, My problem is quite simple to understand. I have made a form where user will input his/her personal information. That personal information also requires to upload a file. I want that whenever user opens his profile then he/she must be able to see already attached file name in custom input field or atleast if he/she doesn't choose any new picture, input file field value must be set to previously attached picture url. This is what I tried to do but didn't worked when setting value of custom input field. Kindly suggest some way around of it. <div class="col-md-6 mb-3"> {% if details.picture.url != '' %} <label for="front">Picture <span class="text-muted"> <a href='{{details.picture.url}}'>{{details.picture}}</a></span></label> {% else %} <label for="front">ID Card (front) <span class="text-muted">Take a snap and upload</span></label> {% endif %} <input type="file" class="form-control" id="front" name="front" value="{{details.picture.url}}" > </div> -
Django: Is it faster to use Ajax or built in Methods?
I've got a question regarding Posting Data from a Template to the server using Ajax or built in Django Methods. Consider the following example: What i mean by Django Methods: views.py: def block_user(request, lobby): target_id = util.get_other_user(Chat.objects.get(lobby=lobby), request.user).id request.user.profile.block(User.objects.get(id=target_id)) return HttpResponseRedirect(reverse('chat-explicit', kwargs={'lobby': lobby})) template: <button type="button" class="btn btn-danger" id="block-user-btn" onclick="location.href='{% url 'user-block' chatroom.lobby %}';">Block</button> What i mean by using Ajax: views.py: def block_user(request): lobby = request.POST.get("lobby", None) target_id = util.get_other_user(Chat.objects.get(lobby=lobby), request.user).id request.user.profile.block(User.objects.get(id=target_id)) return HttpResponse('') template: <button type="button" class="btn btn-danger" id="block-user-btn">Block</button> <script> $("#block-user-btn").click(function() { $.ajax({ headers: { "X-CSRFToken": getCookie("csrftoken") }, url: "{% url 'block-user' %}", data: { 'lobby': '{{ lobby }}' }, type: 'post', dataType: 'json', async: false, success: function(data) { location.reload(); }, failure: function(data) { console.log("error"); } }); }); </script> Both methods work, but which one is faster? or which one is better practice? 1) In this case the response from the server just tells javascript to reload the page. Considering other cases: 2) What, if i wanted to load another page as response? What would be better practice then? 3) And what would be better, if i neither wanted to redirect the user nor reload the page, but just Post data to the server and run server side code?