Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field 'id' expected a number but got 'xyz'
In Models.py class Post(models.Model): user = models.CharField(max_length=100) likes = models.IntegerField(default=0) content = models.TextField() date = models.DateTimeField(auto_now_add=True) class Profile(models.Model): following = models.ForeignKey('User',on_delete=models.CASCADE,related_name='following') user = models.ForeignKey('User',on_delete=models.CASCADE,related_name='user') def __str__(self): return self.user In views.py def viewProfile(request,username): posts = Post.objects.filter(user=username).order_by('id').reverse() profile = Profile.objects.filter(user=username) no_of_followers = profile.following.count() return render(request, "network/profile.html",{ "posts":posts, "username":username, "no_of_followers":no_of_followers }) In profile.html {% extends "network/layout.html" %} {% block body %} <h2 style="margin-left: 20px;">Posts of {{username}}</h2> <div class="col-sm-6"> <div class="card"> <div class="card-body"> <h5 class="card-title">Profile Details</h5> <p class="card-text">Followers:{{no_of_followers}}</p> <p class="card-text">Followings:0</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% for post in posts %} <div class="card" style="width:70%;margin-left: 10%;margin-right: 20%;"> <div class="card-body"> <a href="{% url 'viewprofile' post.user %}"><h5 class="card-title">{{post.user}}</h5></a> <div class="form-group"> <p>{{post.date}}<br>{{post.content}}</p> </div> <p>{{post.likes}}</p> </div> </div> {% endfor %} {% endblock %} Facing an error of Field 'id' expected a number but got 'xyz'. xyz is the username If I replace profile = Profile.objects.filter(user=username)with profile = Profile.objects.filter(user__user=username) then I am getting the error django.core.exceptions.FieldError: Related Field got invalid lookup: user -
summation two similar objects based on the name django
i try to make a system for a storage , sometimes it happen two similar objects are entry in two different time , i have summation the quantity of both and looks like one object instead of two different object for example i've entry this data one week ago name=mouse , qnt=20 , price=20 and today i add a new collection of mouse (the same mouse as before) name=mouse , qnt=10 , price=15 i have to whenever i face similar problem it automatically summation quantities =(30) and price = ((20+15)/2) instead of creating a new object to the second mouse object this is my model class Products(models.Model): name = models.CharField(max_length=20,unique=True) qnt = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3,null=True,blank=True) def __str__(self): return self.name class Collections(models.Model): name = models.ForeignKey(Products, on_delete=models.CASCADE) qnt = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3,null=True,blank=True) i dont need to create new object to the same product as exist in collection , i have to just summation the quantities ?! is it possible ?thanks -
insert django tag in react gatbsy helmet
I have to put a django tag inside the head, so the template will render the dynamic metatags server side. what I want to do is: {% block metatags %} <meta name="description" content="{{ metatags.description }}" /> <meta name="keywords" content="{{ metatags.keywords }}" /> <meta property="og:url" content="{{ metatags.og_url }}" /> <meta property="og:title" content="{{ metatags.og_title }}" /> <meta property="og:description" content="{{ metatags.og_description }}" /> <meta property="og:image" content="{{ metatags.og_image }}" /> <meta property="og:image:url" content="{{ metatags.og_image_url }}" /> <meta property="og:image:type" content="{{ metatags.og_image_type }}" /> {% endblock %} Now, no problems for the meta tags inside helmet, since it's a accepted element for helmet. The problem is for the {% block metatags %} and {% endblock %}. The compiled page won't have those two, probably because helmet ignores them. I tried also to put manually {% block metatags %} and {% endblock %} in the compilated page and it works. I think I cannot achieve this with just helmet, since it will ignore every tag I put inside which are not recognised (script,meta,noscript,..). How could I do that? The only solution maybe it's call a script after gatsby build and add those manually.. any better solutions? -
Getting the difference of quantity between 2 different django model fields?
I have here 2 django database table class Inventory(models.Model): product_name = models.CharField(max_length = 100) qty = models.PositiveIntegerField() class Order(models.Model): product = models.ForeignKey(Inventory, on_delete = models.CASCADE ) qty = models.PositiveIntegerField() I would like to have an inventory table page wherein I can see the total qty left in Inventory (for example: Inventory.qty - Order.qty) . how to do this in Django ? -
set default image to ImageField for existing objects in django
I have a model which has an ImageField. class A(model.Model): blah = CharField(max_length=10) profile = ImageField(upload_to='uploads/', null=True, blank=True) I want to set a default image for existing data, so I tried saving the file in shell like the following: >>> myapp.models import A >>> from django.core.files import File >>> for a in A.objects.all(): >>> a.profile.save('default.jpg', File(open('/Users/myusername/Pictures/default.jpg', 'rb'))) I was quite happy, until I found out that in myprojectroot/media/uploads/ there are as many defaultblablah.jpg files as the number of A objects. I'd like to know if there's any way to set the same image file with all objects as you do with update() method. Could someone can shed some light on it? Thank you in advance. -
Django how to efficiently export large Excel file
I have a really large database (billions of rows) that a user can query through a website build with django. I would like to offer the possibility for the user to download the results of their query in excel format. Currently the code is like: from excel_response import ExcelResponse qs = data.objects_in(db) qs_results = qs.filter([...]).order_by([...]]) json_data = [['col1, 'col2', 'col3']] for item in qs_results: json_data.append([ escape(item.col1), escape(item.col2), escape(item.col3), ]) return ExcelResponse(json_data, 'title') But this is really slow. The output can sometime have 100,000s of lines (and 20 columns) and take more than 10 minutes to be generated and often times out. How can I output an excel file with a high number of row efficiently? -
Django form : two users (A and B) - check if user B already exist, if yes add it to the channel - username is not defined
I'm facing an issue. My goal is to know if a user already exist in DB. If it's true add it to the channel and create it. There is only two fields in the form for consumer. title of channel name of seller (check if it's valid and if so add it) I don't really why that does not work. class CreateChannelView(CreateView): model = Channel form_class = CreateChannelForm template_name = 'channel_new.html' def form_valid(self, form): form.instance.consumer = self.request.user seller = self.request.POST.get("seller") current_seller = User.objects.filter(username=username(seller)) if current_seller.count()<1: raise forms.ValidationError('Username does not exist') else: existed_seller = User.objects.get(username=username(seller)) form.instance.seller.add(existed_seller) form.save() return super(CreateChannelView, self).form_valid(form) def get_success_url(self): return reverse_lazy('channel:channel_home') class Channel(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller") -
Best way to validate request parameters in django
I have following url in django: url( r"^supplier/(?P<supplier_receiver_pk>[0-9]+)/assign_license/(?P<supplier_sender_pk>[0-9]+)", AdminSupplierAssignLicenseView.as_view(), name="supplier-assign-license", ), I want to validate these parameters (supplier_receiver_pk, supplier_sender_pk) so in my serializer I tried this by doing this: class AdminSupplierLicenseSerializer(serializers.Serializer): license_sender_id = serializers.IntegerField() total_licenses = serializers.IntegerField() def get_license_sender_id(self): supplier_receiver_pk = self.context["supplier_receiver_pk"] license_sender_id = self.context["supplier_sender_pk"] #more code def validate_total_licenses(self, total_licenses): #more code But that doesn't work, as het gives an error that license_sensor_id is not given. How do you validate request parameters in django? -
Django | How to change nav class with change in URL?
I want to know the best approach to change the html class name according to the change in url. <nav class="navbar navbar-expand-lg fixed-top clean-navbar" > <div class="container"><a class="navbar-brand logo" data-bs-hover-animate="jello" href="#">BootstrapNation</a><button data-toggle="collapse" class="navbar-toggler" data-target="#navcol-1"><span class="sr-only">Toggle navigation</span><i style="color: white;" class="fas fa-bars"></i></button> <div class="collapse navbar-collapse" id="navcol-1"> <ul class="nav navbar-nav ml-auto mr-0"> <li class="nav-item"><a class="nav-link" href="{% url 'home' %}">HOME <i class="fas fa-home"></i></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'snippets' %}">SNIPPETS <i class="fab fa-css3" style="color: purple;"></i></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'premium' %}">PREMIUM THEMES <i class="fab fa-product-hunt" style="color: green;"></i></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'login' %}">LOGIN <i class="far fa-user"></i></a> </li> </ul> </div> </div> </nav> After every time use a nav-item, I want the class to include 'active', like if the url includes 'site.com/snippets' I want the class to say 'nav-item active' I think using request.get_full_path in if tag might be an approach, but that will make a mess. -
How to data submit and page redirect same position after the button click using javascript python Django?
index.html <div class="row"> <div class="col-md-12"> <div class="card shadow-lg"> <div class="card-body" id="div1"> <div class="row"> <div class="col-md-6"> <h5 class="card-title"><i class="fa fa-user-circle" aria-hidden="true"></i> <a href="{% url 'profile' datas.id %}">{{datas.user_id|capfirst}}</a></h5> </div> <div class=" col-md-6 text-right" > {% if request.user.id == datas.user_id_id %} <button class="btn btn-sm btn-outline-primary" onclick="load_post(this, '{{datas.id}}')" id="edit"> Edit</button> {% endif %} </div> </div> <div id="msg"> <hr> {{datas.post}} <hr> </div> <div id="one"> </div> <div class="row"> <div class="col-md-4"> <i class="fa fa-thumbs-up" value="0" onclick="count(this, '{{datas.id}}')" id="odd"></i><span id="add"></span> </div> <div class="col-md-4"></div> <div class="col-md-4 text-right">{{datas.post_date}}</div> </div> </div> </div> </div> inbox.js function load_post(id, data) { const one = id.closest(".card-body"); one.querySelector('#msg').style.display = 'none'; fetch(`/network/${data}`) .then(res => res.json()) .then(out => { const element = document.createElement("textarea"); element.classList.add("form-control"); element.rows = 2; element.id = "body"; element.innerHTML = out["post"]; one.querySelector('#one').appendChild(element); const li = document.createElement("br"); one.querySelector('#one').appendChild(li); const button = document.createElement("button"); button.className = "btn btn-sm btn-success" //button.classList.add("btn"," btn-primary"); button.id="sucees"; button.innerHTML = "SUBMIT"; button.addEventListener('click',() => edited(id, out["id"])); one.querySelector('#one').appendChild(button); }) } function edited(id, data) { var two = document.querySelector('#body').value; fetch(`/network/${data}`,{ method : 'POST', body : JSON.stringify({ post : two }) }) .then(res=>res.json()) .then(out=>console.log(out)) } views.py @csrf_exempt def edit_post(request, post_id): try: post = posts.objects.get(user_id=request.user, pk=post_id) except posts.DoesNotExist: return JsonResponse({"Out":"Data not found"}, status=404) if request.method == 'GET': return JsonResponse(post.serialize()) if request.method == 'POST': data = json.loads(request.body) upt = data.get("post","") post.post … -
Why my URL doesn't activate view in django?
Here is the thing i'm trying to do: There are few tv channels as image links and they will have some information inside channels. I managed to create tv channels as a list, they look like a link but they don't work like link. I've created slug area for each channel that takes from it's own name and generates slug auto. And with get_absolute_url i take it's url in the below code you'll see; This is my model : class Channels(models.Model): name = models.CharField(max_length=50, null=False, blank=False, verbose_name="Tv Kanalı") logo = models.ImageField(upload_to="channels/images/", verbose_name="Tv Logosu", blank=False) slug = models.SlugField(null=True, unique=True, editable=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Channels, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('channel-list:campaigns', kwargs={'page_slug': self.slug}) This is my main urls: urlpatterns = [ path('admin/', admin.site.urls), url(r'', include(('tvekstra.apps.core.urls', 'home'), namespace='home')), url(r'^user/', include(('tvekstra.apps.user.urls', 'login'), namespace='user')), url(r'^channels/', include(('tvekstra.apps.tvchannels.urls', 'main'), namespace="channel-list")), This is channels urls: urlpatterns = [ url(r'', views.channel_list, name='channels'), url(r'^(?P<page_slug>[-\w]+)/$', views.campaign_list, name='campaigns'), ] This is my views: def channel_list(request): channels = Channels.objects.all() return render(request, 'channel.list.html', {'channels': channels}) def campaign_list(request, page_slug): channel = get_object_or_404(Channels, slug=page_slug) return render(request, 'campaign.list.html', {'channel': channel}) And this is my template: {% for channel in channels %} <div class="col-3 text-center channels"> <a href="{{ channel.get_absolute_url }}"> <img src="{{ channel.get_image }}" … -
Converting Sql query with joins To django orm query
I am trying to convert an Sql query to Django orm query: SELECT * FROM table1 JOIN table2 ON table1.field1 = table2.field1 JOIN table3 ON table3.field = table2.field JOIN table4 ON table4.field2 = table3.field2 JOIN table5 ON table5.field = table2.field Any help apreciated! -
Django DB connection custom SQL parameters
I need to perform a batch update since the ORM seems to be a bit slow at this. Since I am updating strings that could contain single quotation marks, e.g. Mc'Donald, I cannot simply template a string variable with all of the attributes. The documentation recommends the following: cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz]) Question: How do I apply this correctly for the below use case? Technical Details: Django 3.0.2 I am generating a SQL string and then calling it as follows: from django.db import connection people = [{"name": "Person A", "age": 15, "height_m": 1.83, "id": 5}, {"name": "Person B", "age": 19, "height_m": 1.73, "id": 45}] sql = "" params = [] for p in people: sql += 'UPDATE people SET name = %s, age = %d, height_m = %d WHERE id = %d;' params.append(p['name']) params.append(p['age']) params.append(p['height_m']) params.append(p['id']) with connection.cursor() as cursor: cursor.execute(sql, params) cursor.connection.commit() This throws the following error: ValueError: unsupported format character 'd' (0x64) at index 104 -
How to have multiple AUTH_USER_MODEL in django
I have two different app that has separate models that inherits from AbstractionBaseUser like below # in doctor/models.py ... class Patient(AbstractBaseUser): email = models.EmailField(blank=True, unique=True) phone_number = models.IntegerField(blank=False, unique=True) USERNAME_FIELD = 'phone_number' REQUIRED_FIELD = ['phone_number', 'email'] ... # in Patient/models.py ... class Patient(AbstractBaseUser): email = models.EmailField(blank=True, unique=True) phone_number = models.IntegerField(blank=False, unique=True) USERNAME_FIELD = 'phone_number' REQUIRED_FIELD = ['phone_number', 'email'] ... Both models have different fields # in settings.py AUTH_USER_MODEL = [ 'doctor.Doctor', 'patient.Patient' ] I tried to do this but in making migration it tells me that it must be a single model AssertionError: ForeignKey(['doctor.Doctor', 'patient.Patient']) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' I read docs but I couldn't find any help How can I fix this and how can I have multiple AUTH_USER_MODEL -
Django - Mark a field as favorite
Thanks in advance to anyone who takes the time to respond to this! I have two models, one showing a list of reports and one containing whether or not a user has favorited a report from the list. In the HTML, I'm looping through one model to display all reports that haven't been favorited and the other model to show favorited, so separating them by category, essentially. I'd like to use a checkbox to indicate whether or not a report has been favorited. The functionality works when marking as favorite in the admin section, but how would I introduce this in the HTML itself? Here is my code: models.py from datetime import datetime from django.utils.text import slugify from hitcount.models import HitCountMixin, HitCount from django.contrib.contenttypes.fields import GenericRelation from django.contrib.auth.models import User class ReportDirectory(models.Model): report_name = models.CharField(max_length=300, unique=True, blank=False) report_desc = models.TextField() report_type = models.CharField(max_length=300) report_loc = models.TextField() slug = models.SlugField(unique=True, max_length=300) last_update = models.DateTimeField(null=True) main_tags = models.CharField(max_length=300) view_count = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') # Renames the item in the admin folder def __str__(self): return self.report_name # Creates and saves a slug based on the report_name if a slug does not already exist def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.report_name) … -
how to use background_process in django class based views.?
This is my view file. class MyView(View): def send_notification(): cls_obj_ = Process_Class_View() cls_obj_ .notifications(self.request.user.id) def get(self, request): if request.user.is_authenticated: result = self.send_notification() return HttpResponse('result') This class is in another file.Im import thin cls in view file. class Process_Class_View: def noti_to_user(self,id): print("notification send to user") @background(schedule=0) def notifications(self,id): noti_to_user(id): Still call is not going to notifications().How can we use background process in class based view in django.. -
Force setup X-Frame-Options Django
I tried different methods to setup X-Frame-Options to 'SAMEORIGIN' in the Django-server responses, but it wasn't help: I removed XFrame package from the middleware in settings.py. I putted X_FRAME_OPTIONS='SAMEORIGIN' to settings.py I added 'X-Frame-Options' to response object with the same value in my view in which I wanted to use the <iframe> I tried to add @xframe_options_sameorigin decorator to my view. I also changed /etc/apache2/apache2.conf, putted Header always set X-Frame-Options "SAMEORIGIN" into it. Then I tried to restart apache2 service after all my actions but the result always the same: X-Frame-Options setted as 'DENY'. My Django version is 2.2.4. -
Is it possible to serve more than one django project under same domain?
I have a site say, localdjangosite.com and I already have a django application running on that domain at url localdjangosite.com/site1/. For this I have a virtual host set up inside apache sites-available directory as follows, I used mod_wsgi also. WSGIScriptAlias /site1 /path/to/the/django/codebase/wsgi.py <Directory /path/to/the/django/codebase/> Require all granted </Directory> And with that, that site1 is working well. Now I want to have one more site under the same domain like localdjangosite.com/site2/. And when I tried to configure apache like below I face page not found error. WSGIScriptAlias /site2 /path/to/the/django/codebase/for/site2/wsgi.py <Directory /path/to/the/django/codebase/for/site2/> Require all granted </Directory> When I configured like that and visited the url localdjangosite.com/site2/, It shows Page not found error and it displays the url configurations of the site1 instead of site2. Here site1 and site2 are really two different django projects and they have different apps inside and server different purpose. So I really don't understand what is going on? what is wrong? Could someone please help me to understand it and host two or more django projects under same domain? -
How I can reduce logic of hande form in next Django view?
I'm studing a django course right now. Teacher showed how find short route with ascross points by graph algorithm. He writed many code in view, I think it's some dirty. I shorten piece of code by using session in RouteSession class. But there is still many code. Should do any thing in this case? Thanks. def find_routes(request): if request.method == "POST": form = RouteForm(request.POST or None) if form.is_valid(): data = form.cleaned_data from_city = data['from_city'] to_city = data['to_city'] across_cities_form = data['across_cities'] travel_time = data['travel_time'] graph = get_graph() all_ways = list(dfs_paths(graph, from_city.id, to_city.id)) if len(all_ways) == 0: messages.error(request, 'There is no routes') return render(request, 'routes/home.html', {'form': form}) if across_cities_form: across_cities = [city.id for city in across_cities_form] right_ways = [] for way in all_ways: if all(point in way for point in across_cities): right_ways.append(way) if not right_ways: messages.error(request, 'The route through these cities is impossible') return render(request, 'routes/home.html', {'form': form}) else: right_ways = all_ways trains = [] for route in right_ways: tmp = {'trains': []} total_time = 0 for i in range(len(route) - 1): qs = Train.objects.filter(from_city=route[i], to_city=route[i + 1]) qs = qs.order_by('travel_time').first() total_time += qs.travel_time tmp['trains'].append(qs) tmp['total_time'] = total_time if total_time <= int(travel_time): tmp['from_city'] = from_city tmp['to_city'] = to_city trains.append(tmp) if not trains: … -
Wagtail Template does not contain request.user
I have configured wagtail 2.9, Everything works preety fine. But I couldn't able to access request.user or request.site from the wagtail template(home_page.html). My model is configured as below. class HomePage(Page): template = "home/home_page.html" editors_note = models.CharField(max_length=100, blank=False, null=True) editors_text = RichTextField(blank=False, null=False, default='Enter Text here', features=['h1','h2', 'h3', 'bold', 'italic', 'link']) editors_name = models.CharField(max_length=100, blank=False, null=True) content_panels = Page.content_panels + [ MultiFieldPanel( [FieldPanel('editors_note'), FieldPanel('editors_text'), FieldPanel('editors_name')], heading='Editors Note' )] I tried creating one more normal django page using the below view function. def landing(request): request.session['uid'] = user_id user = LDAPBackend().populate_user(uid) request.user = user return render(request, 'home/landing.html') Here in the landing page, I can able to access request.user and request.session.sso_id. Do I need to configure something for the request to access in the template, I have tried redirecting from landing.html to home_page.html still its not available. -
bachground Scheduler of django-apscheduler does not run the jobs
I want to send data to the database using django-apscheduler in the background but when I use Background Scheduler , the Scheduler does not run my jobs. The job is here : def my_job(): time = timezone.now().strftime('%X') print("It's now %s" % time) The Scheduler for running the job is : class Command(BaseCommand): help = "Runs apscheduler." def handle(self, *args, **options): scheduler = BackgroundScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( my_job, trigger=CronTrigger(second="*/10"), # Every 10 seconds id="my_job", max_instances=1, replace_existing=True, ) logger.info("Added job 'my_job'.") try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!") (I've just used a simple job to test Scheduler.) When I run python manage.py tasks the job is added in django jobs but it does not appear in execution part of Django Admin.what is wrong? Any help would be appreciated. -
Django channels image saving, TextField or ImageField
Chat app using django channels I am using websockets to send base64 encoded string to the server, the base64 encoded string could be saved in TextField or saved in ImageField by decoding using base64 library, which method is preferred, why? -
Django annotate if field exists in second model ArrayField
I have the following 2 models. I'm trying to annotate the DeliveryRegionLog queryset with a boolean that indicates whether a DeliveryRegion exists with the postal code in the ArrayField postal_codes. class DeliveryRegion(models.Model): name = models.CharField(max_length=255) postal_codes = ArrayField( models.CharField(max_length=255, blank=True), blank=True, default=list, help_text='Comma separated list of postal codes.' ) class DeliveryRegionLog(models.Model): postal_code = models.CharField(max_length=64) checks = models.PositiveIntegerField( default=1, help_text='The number of times someone has checked if ' 'this postal code exists in a delivery region.' ) I've tried the following but it doesn't work and I can't figure out why. from django.db.models import Exists, OuterRef postal_code = 'A1A' DeliveryRegion.objects.create(postal_codes=[postal_code]) DeliveryRegionLog.objects.create(postal_code=postal_code) DeliveryRegionLog.objects.annotate( region_exists=Exists( DeliveryRegion.objects.filter(postal_codes__contains=[OuterRef('postal_code')]) ) )[0].region_exists # False DeliveryRegionLog.objects.annotate( region_exists=Exists( DeliveryRegion.objects.filter(postal_codes__contains=[postal_code]) ) )[0].region_exists # True -
Django Rest Framework: how to add total sum to ListAPIView?
I want to add total sum of field to the response. What is the best way to do it? -
Remove trailing slashes in Django URLs
Is there any way of stripping all trailing URLs in Django and redirecting them to the non slashed URL. i.e. If I go to /home/ I want to be redirected to /home. Currently I get a 404 as the page "does not exist". There was one piece of middleware I found which is outdated. Called Django-unslashed. Would this be a case of adding something to the urlconf, or writing custom middleware?