Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i use django comment_set.all
My problem Make comment model, and form for Django Use {% for i in post.comment_set.all %} no change html Information saved in the comment form does not appear how can i fix it? MY top_detail.html <form method="POST" action="{% url 'create_comment' post.id %}"> {% csrf_token %} {{ comment_form }} <input type="submit"> {% for i in post.comment_set.all %} <p>comment: {{ i.subject }}</p> <p>time: {{ i.created_at }}</p> <hr> {% endfor %} </form> MY models.py from django.db import models class Top(models.Model): product_name = models.CharField(blank=True, null=True, max_length=30) product_price = models.CharField(blank=True, null=True, max_length=30) product_image = models.ImageField(blank=True, null=True, upload_to="images") product_explain = models.TextField(blank=True, null=True, ) class Question(models.Model): post = models.ForeignKey(Top, null=True, on_delete=models.CASCADE) subject = models.CharField(null=True, max_length=150) created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject MY urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views from .views import PostList urlpatterns = [ path('home/', views.home, name='home'), path('home/top', PostList.as_view(), name='top'), path('home/top/<int:pk>/', views.top_detail, name='top_detail'), path('search/', views.search, name='search'), path('signup/', views.signup, name='signup'), path('login/', auth_views.LoginView.as_view(template_name='main/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('create_comment/<int:post_id>', views.create_comment, name='create_comment'), ] My views.py def top_detail(request,pk): post = get_object_or_404(Top, pk=pk) post_list = Top.objects.get(pk=pk) comment_form = CommentForm() return render(request, 'main/top_detail.html', {'post':post, 'post_list':post_list,'comment_form':comment_form}) def create_comment(request, post_id): filled_form = CommentForm(request.POST) if filled_form.is_valid(): form = filled_form.save(commit=False) form.post = Top.objects.get(id=post_id) form.save() return redirect('top_detail',post_id) MY … -
'>' not supported between instances of 'NoneType' and 'NoneType' Overlapping Check
Hi I am getting this error in my validation check def sefl(clean): start_number=self.cleaned_data.get("start_number",None) end_number=self.cleaned_data.get("end_number",None) latest_start=max(start_number, end_number) earliest_end = min(start_number, end_bbch) delta = (earliest_end - latest_start) + 1 if delta is None: raise ValidationError("overlap not allowed") -
PylancereportMissingModuleSource on VS Code
I have the following code from a tutorial which I am following: from django.http import HttpResponse import random from django.template.loader import render_to_string from articles.models import Article The issue is that I am getting this error in VS Code: Import "django.http" could not be resolved from sourcePylancereportMissingModuleSource Import "django.template.loader" could not be resolved from sourcePylancereportMissingModuleSource It is odd because on the terminal in vs code if I type the import commands, it is not producing any error. So since the webpage is producing DoNotExist error, i am not sure if this is because of these packages or because of some other factor. I did try to find out if i was using a different interpreter than the django virtual environment import sys print(sys.executable) Produces the location of the virtual environment for this project so it is the right interpreter. -
Django update table on page every 5 sec
So i have a template which gets a list of lists with information for table. I render data like that way Here is my template html {% for each in info %} <tr class="bg-dark-2"> <th data-label="Seller" scope="row"><span class="fw-bold">{{ each.2 }}</span></th> <th data-label="U give"> <div class="d-flex align-items-center"> <span class="icon d-flex align-items-center justify-content-center me-3"></span><span>{{ each.4}}</span><span class="fw-normal ms-3">{{ each.0 }}</span> </div> </th> <th data-label="U get"><span>{{ each.1 }} {{ each.5 }}</span></th> <th data-label="Limit"><span>from {{ each.8 }} to {{ each.9 }}</span></th> <th data-label="Reserve"><span>{{ each.6 }}</span></th> <th data-label=""> <a class="btn btn-success btn-block" href="{{ each.3 }}">Buy</a> </th> </tr> {% endfor %} So the task is, how can i update data on my django webpage, without refreshing it? (every 5-10 seconds) Or how can i use ajax for delete table and download new data to it? -
how to save file location to database sqlite3 - django
i want to save file location to database sqlite3, but the file just save it to local storage. i tried to make it but there's error : here's my models : from django.db import models from django.core.files.storage import FileSystemStorage fs = FileSystemStorage(location='/media/mp3') class Audio_store(models.Model): record=models.FileField(storage=fs) forms.py : from django import forms from .models import Audio_store class AudioForm(forms.ModelForm): class Meta: model = Audio_store fields= ['record'] views.py : def homepage(request): form = AudioForm() audio = Audio_store.objects.all() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("homepage") context={'form':form, 'audio':audio} return render(request, "homepage.html", context=context) please help me to fix it -
Django: To get all child and grandchild objects recursively
There is a model called Comment with the following recursive relationship. class Comment(models.Model): video = models.ForeignKey(ProductVideo, on_delete=models.CASCADE) text = models.TextField(max_length=1000) commented_at = models.DateTimeField(default=timezone.now) parent = models.ForeignKey( "self", blank=True, null=True, on_delete=models.CASCADE, related_name="replies", ) def __str__(self): return f"{self.user}, {self.text[:10]}" And the children of the parent comment A are B, C, D... and there are multiple layers of recursive relations. . └── A ├── B │ └── C ├── D │ └── E │ └── F ├── G └── H └── I └── J └── K How can I get all these children from an object called A efficiently and with a flat result? // Comment.objects.get(pk="A") [ {"id": "A"}, {"id": "B"}, {"id": "C"}, {"id": "D"}, {"id": "E"}, {"id": "F"}, {"id": "G"}, {"id": "H"}, {"id": "I"}, {"id": "J"}, {"id": "K"}, ] There are various django-mptt, django-cte, etc. What should we use? -
Error when listing out a user's followers
I am trying to add a notifications feature to my social media platform. Part of this involves adding a notifications logo to my navbar at the top of my website which will display the number of unseen notifications a logged-in user has. When I run my server, I receive a NameError: NameError Here is part of my navbar.html: {% load custom_tags %} (...) {% if user.is_authenticated %} <div class="nav-item dropdown"> <a class="nav-link dropdown-toggle text-dark" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false"><i class="fas fa-user"></i></a> <ul class="dropdown-menu dropdown-menu-end"> <li><a class="dropdown-item" href="{% url 'profile' request.user.profile.pk %}">Profile</a></li> <li><a class="dropdown-item" href="{% url 'account_logout' %}">Sign Out</a></li> </ul> </div> <div class="nav-item"> {% show_notifications %} {% endif %} </div> </div> </nav> Here is my show_notifications.html: <div class="dropdown"> <span class="badge bg-primary notification-badge">{{ notifications.count }}</span> <div class="dropdown-content d-none" id="notification-container"> {% for notification in notifications %} {% if notification.post %} {% if notification.notification_type == 1 %} <div class="dropdown-item-parent"> <a href="#">@{{ notification.from_user }} liked your post</a> <span class="dropdown-item-close">&times;</span> </div> {% elif notification.notification_type == 2 %} <div class="dropdown-item-parent"> <a href="#">@{{ notification.from_user }} commented on your post</a> <span class="dropdown-item-close">&times;</span> </div> {% endif %} {% elif notification.comment %} {% if notification.notification_type == 1 %} <div class="dropdown-item-parent"> <a href="#">@{{ notification.from_user }} liked on your comment</a> <span class="dropdown-item-close">&times;</span> </div> {% … -
column contains null values
I added Person as a foreign key to the CareerHistory table. person = models.ForeignKey( Person, on_delete=models.PROTECT, default=None, related_name='careerist') I set default=None thinking this would avoid that error when running migrations about making a new field on an existing table without a default value. However, instead I got django.db.utils.IntegrityError: column "person_id" contains null values Now, there are only 114 Persons in that table, and all of them have ids, so I find this error very confusing. I looked at this answer: SQL Django Null Constraint Error - cannot resolve? and decided to try: person = models.ForeignKey( Person, on_delete=models.PROTECT, default='', related_name='careerist') However, this still came back with the same error. Then I went to: person = models.ForeignKey( Person, on_delete=models.PROTECT, default='', null=True, related_name='careerist') But I still get the same error. I don't understand what is happening here. Can someone please explain, and show me how to fix this? I don't want to just fix it, I want to understand what is happening here. Maybe I need to edit my migrations file(s)? Thanks. -
Duplicate the data OR saving Order Items data into JSONField
I have one to many Relationship with Order to OrderItem. OrderItems is saving the details of Item table. Item can be deleted by user, but I cannot delete the information of an item from OrderItem table ( Because it will used for Generating reports), so that is why I did not move the Item key to OrderItem and saving all the information of item table to OrderItem. Now you can see that, data is being duplicated from Item to OrderItem table. My question is or I want to ask for suggestions that, i am using postgresql and we have luxury of JSONField. So is it a good idea to save all the information of Item table into JSONField and remove all fields? Later on I have to generate reports from OrderItem, like how many Orders has been placed or calculate the profit using OrderItem table. class Item(models.Model): class Meta: db_table = 'items' SKU = models.PositiveIntegerField() name = models.CharField(max_length=255, blank=False, null=False) supplier = models.ForeignKey(Supplier,on_delete=models.CASCADE, blank=False, null=False) purchase_price = models.DecimalField(max_digits=10, decimal_places=2) trade_price = models.DecimalField(max_digits=10, decimal_places=2,blank=False, null=False , default = 0.00) retail_price = models.DecimalField(max_digits=10, decimal_places=2) class Order(models.Model): class Meta: db_table = 'orders' customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, related_name='orders') serial_no = models.CharField(max_length=30, null=False, unique=True) … -
Django Annotate resolve diferent value than bucle for in one Subquery
I have this Query with Annotate: whateverquery=Whatever.objects.filter(query,important_field__isnull=False).values('important_field','id').annotate( total=Count('id'), total_contract_by_user=Count( Subquery(OtherWhatever.objects.filter( whatever__important_field=OuterRef('important_field'), status="asignada", visibility=True, confirm=True).values('user').distinct(),output_field=IntegerField())) ).values('total','total_contract' ).annotate(tasa_conversion=Cast(F('total_contract_by_user')/F('total'),FloatField()) ).values('total','total_contract','tasa_conversion' ).order_by(order) It not resolve the same value in total_contract_by_user that: for w in whateverquery: total_contract_by_user = OtherWhatever.objects.filter(visibility=True,confirm=True,status="asignada",Whatever__important_field=w['important_field']).values('user').distinct() tasa_conversion = round((total_contract_by_user.count() / int(w['total']))*100,2) I do not know what I have wrong in Annotate in Query. -
Can I pass a Django object to an HTML class?
I want differents background colors for each column in the table, but I don't know how to do it, I tried this but no My model: class Alternative(TimeStampedModel): standard = models.ForeignKey('Standard', verbose_name=_('Standard'), on_delete=models.CASCADE) name = models.CharField(verbose_name=_('Name'), max_length=100) active = models.BooleanField(verbose_name=_('Active'), default=True) detail = models.TextField(verbose_name=_('Detail')) point = models.PositiveIntegerField(verbose_name=_('Point'), default=0) objects = managers.AlternativeManager() class Meta: verbose_name = _('Alternative') verbose_name_plural = _('Alternatives') def __str__(self): return self.name My template: {% for standard in standards %} <div class="table-responsive"> <table class="table table-bordered caption-top"> <caption class="tituloStandard">{{standard.name}}</caption> <thead class="thead"> <tr> {% for alternative in standard.alternative_set.visible %} <th class="point{{alternative.point}}">{{alternative.name}} {{alternative.point}}</th> {% endfor %} </tr> </thead> <tbody> <tr> {% for alternative in standard.alternative_set.visible %} <td>{{alternative.detail}}</td> {% endfor %} </tr> </tbody> <tfoot> <tr> <th colspan="4">{{standard.diagnosis_tools}}</th> </tr> </tfoot> </table> </div> {% endfor %} My CSS: .point5{ background-color: #2f8888; } .point10{ background-color: #71a2d3; } .point15{ background-color: #ff4bba; } .point20{ background-color: #83b4f4; } If u see I tried class="point{{alternative.point}}", but that didn't work, any advice? -
How to add a field of a through model to a Django form
For my Django project I am trying to create a singular form that allows me to add a row in my Pipeline model and link that row to the Process model through the PipelineProcess model. This is fairly straightforward by using ModelForms IF the PipelineProcess model did not have an extra field (phase). I need to be able to view and add/edit the PipelineProcess.phase field in the same form. Note that the PipelineProcess is a "through model" of the Pipeline and Process model. models.py class Pipeline(models.Model): name = models.CharField(max_length=100) sector = models.CharField(max_length=100, blank=True, null=True) process = models.ManyToManyField(Process, through='PipelineProcess') ### NOTE THE USAGE OF THE THROUGH MODEL HERE class Meta: managed = True db_table = 'pipeline' class Process(models.Model): name = models.CharField(max_length=100) class Meta: managed = True db_table = 'process' class PipelineProcess(models.Model): pipeline = models.ForeignKey(Pipeline, models.DO_NOTHING, blank=True, null=False) process = models.ForeignKey(Process, models.DO_NOTHING, blank=True, null=False) phase = models.CharField(max_length=100) ### THIS FIELD I AM UNABLE TO ACCESS THROUGH A FORM class Meta: managed = True db_table = 'pipeline_process' forms.py class PipelineForm(ModelForm): class Meta: model = Pipeline fields = ['name', 'sector', 'phase'] This form generates the following error which makes sense: django.core.exceptions.FieldError: Unknown field(s) (phase) specified for Pipeline I have tried looking up examples of … -
Import "django.template.loader" could not be resolved from sourcePylance
This question is regarding a tutorial which i am following to learn django. I was trying to import from django.template.loader import render_to_string, in views.py file. But when i try to import it, its producing this error on vs code: Import "django.template.loader" could not be resolved from sourcePylancereportMissingModuleSource Same with another import from django.http import HttpResponse Could you please advise why am I not able to import them? It is odd because on the terminal in vs code if I type the import commands, it is not producing any error. Any help would be very appreciated, thanks -
Change language in custom middleware
I would like to change language in my custom middleware. For some reason code below doesn't work. class LanguageMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print('set language to spanish...') translation.activate("es") request.LANGUAGE_CODE = "es" response = self.get_response(request) translation.deactivate() return response settings.py LANGUAGES = ( ("en", "English"), ("es", "Spanish"), ) LOCALE_PATHS = (os.path.join(BASE_DIR, "locale"),) USE_I18N = True USE_L10N = True LANGUAGE_CODE = "en" if I change LANGUAGE_CODE is settings to "es" I get spanish API responses but I would like to be able to change it programmatically in my middleware. -
Unable to subscribe to the Django Rest-frameworks channel
I am trying to write an API which would subscribe to all the instances of a Django's model. To accomplish this I have been referring to the documentation of package djangochannelrestframeowork. I did everything as told in the documentation. This is what my asgi.py file looks like - import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import yacht_away os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yacht_away.settings") django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": django_asgi_app, # Just HTTP for now. (We can add other protocols later.) "websocket": AuthMiddlewareStack( URLRouter(yacht_away.urls.websocket_urlpatterns) ), } ) In my setting.py file, I have declared - ASGI_APPLICATION = "yacht_away.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis", 6379)], }, }, } Also, in the installed apps - INSTALLED_APPS = [ "channels", ... ] In my project's urls.py - from messaging.urls import websocket_urlpatterns websocket_urlpatterns = [ path("api/messaging/", URLRouter(websocket_urlpatterns)), ] And in the apps.py - from django.urls import path from messaging.views import CustomerOwnerMessagesView websocket_urlpatterns = [ path( "customer/<int:customer>/owner/<int:owner>/", CustomerOwnerMessagesView.as_asgi(), ), ] After that, I wrote a view class which will create a record in the database and at the same time if subscribed to the method subscribe_to_customer_owner_messages_activity then it must return the newly created … -
How to upload a json.dump into a model filefiedl
I seem to not be able to work around this problem. I have a model with a Filefield. Now I'm trying to create a file json data. I've been working around this in different ways and I have come to the conclusion (right or wrong) that I shouldn't need to write a file, but be able to dump the data inte the file directly. All this is embedded in a custom_command. My model class Free_FileHistory(models.Model): free_file= models.FileField(upload_to=get_inv_file_filepath, null=True, blank=True, verbose_name='File',validators=[validate_file_size]) .... My code OBJ = Free_FileHistory.objects.get(free_transfer_id=ID) # ID is a unique identifier file = (ID) # CreateDictioneryJSON is a function that take two given arrays of keys and values and create one data directory data = CreateDictioneryJSON(HEADER,ROW) read=json.dumps(data, indent=4) print(read) OBJ.free_file.save(file,read) print(read) displays the data just as I want it. I get the error: 'str' object has no attribute 'closed' -
Is any other process to download packages without pip?
I am stuck to download pip install fiona package but still it is not downloaded on my windows 10 system. 1.Help to download fiona package 2.How to control cache packages on pip -
Decimal calculation different on my local machine vs Heroku server
I have a Django project that I deployed to Heroku. I noticed that the calculations are not working when I used smaller numbers for some reason. Everything works fine on my local Windows machine. For example this calculation newBalance = Decimal(str(userObj.user_coins)) - Decimal(str(betValue)) when the calculation would be 2000 - 12 I get an answer of 2.2E+3 instead of 1988. If the calculation would be 2000 - 120 I get an answer of 1900 or 1.9E+3 instead of 1880. On my local machine this was working correctly. I don't understand what might be going wrong here. -
Can someone explain me how to do a register/login with django and kivy application?
I want to create a application with kivy and django and with a register/login and I don't know where I have to begin, I already did the front-end but not the backend. Thanks for your answers ! -
django notification system for single user
Hi I would like to create a notification system I created the badge that signals me the notification on its page to see the various notifications and through ajax with the GET method I update the number of notifications. Not being attached to a single user, the count remains the number of notifications and I would like that user who clicks the 'read' button the notification is no longer seen and the conuter decreases. But how do I do it for the single user, I can do it but it would work for each user and not for the single one and that's it. model class Notification(models.Model): date = models.DateField(auto_now_add = True) title = models.CharField(max_length = 255) text = models.TextField() active = models.BooleanField(default = False) view notification + view ajax notification def notifiche(request): if request.is_ajax() and request.method == "POST": notifica = request.POST['id_notifica'] oggetto = get_object_or_404(Notification, id = notifica) if oggetto.active == True: oggetto.active = False messaggio = "Notifica disattivata" else: oggetto.active = True messaggio = "Notifica attiva sul sito" oggetto.save() return JsonResponse({'oggetto': oggetto.active, 'messaggio': messaggio}, status=200) else: notifiche = Notification.objects.all() context = {'notifiche':notifiche, 'popup':popup} return render(request, 'notifiche.html', context) def popup(request): popup = Notification.objects.filter(active = True).count() return JsonResponse({'popup': popup}, status=200) snippets/nav.html … -
Django update content of HTML element on same page based on selected item
The title is a bit vague as I couldn't think of a way to summarise this. I have 3 django models. Let's call them root, branch leaf to make it easy. A root can have multiple branches and each branch can have multiple leaves. In my template I am displaying buttons that are populated from the root objects. When a user clicks one of these buttons I would like to update the content of another element on the same page with all the branches that are children of that root. When a branch is clicked, i'd like to update another element with all the leaves. I'm assuming the process would be the same for the two updates. I am pretty new to Django but not to programming and I can't seem to find a good explanation of how to detect which 'root' has been clicked and pass that back to django in order to populate the branch elements. Can anyone offer some guidance? I probably don't need code, just more of an idea of what the workflow is. E.G use onclick to send the name of the clicked item to a javascript function, call out to a python function that … -
How to apply the same decorator chain to multiple functions
@extend_schema( methods=['GET'], responses={(200, STYLES_MIME_TYPE): OpenApiTypes.BINARY}) @extend_schema( methods=['PUT'], request={STYLES_MIME_TYPE: OpenApiTypes.BINARY}, responses={(204, 'application/json'): OpenApiResponse( response={'type': 'array', 'items': {'type': 'integer', 'format': 'int32'}}, examples=[OpenApiExample( 'Returned style IDs example', status_codes=['204'], value=[101, 102, 103])])}) @api_view(['GET', 'PUT']) @permission_classes([IsAuthenticated|ReadOnly]) @renderer_classes([StylesRenderer, StylesJSONRenderer]) @parser_classes([StylesParser]) def styles(request: Request, pid: int) -> Response: """ Get or save styles for a project. GET - protobuf binary response POST - returnd IDs for saved styles """ try: project = Project.objects.get(pk=pid) return _handle_styles(request, project) except Project.DoesNotExist: raise Http404() @extend_schema( methods=['GET'], responses={(200, STYLES_MIME_TYPE): OpenApiTypes.BINARY}) @extend_schema( methods=['PUT'], request={STYLES_MIME_TYPE: OpenApiTypes.BINARY}, responses={(204, 'application/json'): OpenApiResponse( response={'type': 'array', 'items': {'type': 'integer', 'format': 'int32'}}, examples=[OpenApiExample( 'Returned style IDs example', status_codes=['204'], value=[101, 102, 103])])}) @api_view(['GET', 'PUT']) @permission_classes([IsAuthenticated|ReadOnly]) @renderer_classes([StylesRenderer, StylesJSONRenderer]) @parser_classes([StylesParser]) def styles_xref(request: Request, xref: uuid.UUID) -> Response: """ Get or save styles for a project. GET - protobuf binary response POST - returnd IDs for saved styles """ try: project = Project.objects.get(xref=xref) return _handle_styles(request, project) except Project.DoesNotExist: raise Http404() This is Django, and obviously I want to use the same decorators for those 2 views. The only difference is that one looks up object by int ID, and the other by UUID xref field. How can I keep this DRY? -
import views vs from . import views
I am new to Python and Django, I have an app directory called calc and inside it there are two files: views.py urls.py In urls.py, if I type in import views the server generates an error, however if I type from . import views everything works fine. Could someone explain why? I thought since the two py files are in the same directly, the import statement should match the views.py -
I created folder called Tempelates and written some code in hello_world.html. But i can.t run, how can i set path for that
Base_Dir and tempelate foldeer result -
Why this SQL sentence gets stuck and never finishes
I'm using PostgreSQL and all queries have been working fine for all our users. Except now. Some hours ago, some of the sentences are not working for some users. For instance: select comments from appointments_appointmentlog where id=102501539; If I run this sentence in the psql tool, it runs just fine. But, I use a different id (one of the problematic ones), then it gets stuck: UPDATE appointments_appointmentlog SET comments='A' WHERE id=30042047; The select command works fine though: select comments from appointments_appointmentlog where id=30042047; Any idea what may be happenning? Do you need any additional information? Also, as a side note, I can update, create and delete other rows in the same appointments_appointmentlog table. Note: not sure if relevant, but we are using Django 1.1 (I know I know, too old). The problem can also be reproduced with raw sql though, without using django.