Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
docker container for Django hangs when updating mounting sources
As part of a course I am currently passing there is a situation when following combination is used: A docker container is created for very standard scenario: One for Django, second one for Postgresql database and then a compose file is managing all this stuff. And the sources are actually mounted using the docker-compose volumes. The entire application I created during the course is available in my github: https://github.com/arsenhakobyan/recipe-app-api The problem I faced is with running django test command each time when I update any source file. steps to reproduce the issue I have: build images with docker-compose build run the following command: docker-compose run --rm app sh -c "python manage.py test" The process should run as expected. Edit any file (e.g. app->user->tests->test_user_api.py) and save the changes run the command from step 2. the process hangs at this point in my case and I can not even force to remove the docker containers, even tried to deactivate some endpoints from the network that is connected with that containers (I think that could help when I read some of the error messages). The only way to continue work is to restart the docker exe on my machine. Let me know if β¦ -
How to connect two databases in django for local and remote servers?
guys. I have a database, which I deployed on Heroku. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'd7mj3h2mco40v9', 'USER': 'fwla1qyxgxrrqk', 'PASSWORD': get_secret('DB_PASSWORD'), 'HOST': 'ec2-54-174-73-136.compute-1.amazonaws.com', 'PORT': '5432', } } The problem is when I add comments objects on a local machine, they automatically downloaded to the remote database. It's not convenient. I want to create, for example, a local database which will save all migrations or changes of my models, but not downloaded into a remote server. And when I need to download the data, I will do something and the changes are to appear on a remote database. What do I need to do for this? How to make the right migrations and then work with them? I'm newbie, please don't advice complicated things I can't understand :) -
is there any way in django to list all devices a user logged in?
I am trying to list all the device and their locations on which a user account is logged in . similar to login activity of instagram, is there any way to do this? sorry for my bad english π -
django rest upload multiple images
I'm working on an e-commerce API with Django rest framework so I want when the user adds a new product he can upload multiple images how can I do that with rest framework? here are my models, views, serializer my models.py class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(null=True, blank=True) owner = models.ForeignKey(User, related_name='Products', on_delete=models.CASCADE,null=True) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images') images = models.FileField(upload_to='API/images',max_length=100,null=True) my serializer class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImages fields = '__all__' class Productserializer(serializers.ModelSerializer) : images= ProductImageSerializer(many=True) class Meta: model = Product fields = ('id','title','price','description','whatfor','categories','size','rooms','Location','Lat','Long','owner_id','images') extra_kwargs = {"user":{"read_only":True}} def validate(self, attrs): attrs['owner'] = self.context.get("request").user return attrs my views class ProductViewSet(ModelViewSet): queryset = Product.objects.all() serializer_class = Productserializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_class = ProductFilter search_fields = ['title', 'description'] ordering_fields = ['price', 'last_update'] def get_serializer_context(self): return {'request': self.request} -
csrf_exempt is not working in my django project
I am using django 3.2 I am trying to use a twilio webhook on my site but still getting the error 403 forbidden <p>CSRF verification failed. Request aborted.</p> <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for βsame-originβ requests.</p> my view @csrf_exempt @validate_twilio_request def webhook(request): return HttpResponse("something") what are my doing wrong? -
Why does a Django foreign key id __in query fail to match None?
When filtering a queryset on a nullable foreign key, I can filter by an ID value (foo_id=123) or by None (foo_id=None). However, if I attempt to filter by a list (foo_id__in=[123, None]) the None is ignored. Why is this happening, and what is the best workaround for filtering on a foreign key using a list which includes None? Example: from django.db import models class Foo(models.Model): name = models.CharField(max_length=100) class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.PROTECT, blank=True, null=True) foo = Foo.objects.create(name='myfoo') Bar.objects.create(foo=foo) Bar.objects.create(foo=None) Bar.objects.count() # 2 Bar.objects.filter(foo_id=foo.id).count() # 1 Bar.objects.filter(foo_id=None).count() # 1 Bar.objects.filter(foo_id__in=[foo.id, None]).count() # 1 - Expected 2! -
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 !