Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Read multiple records as one in Django
everyone, I am in the middle of a grouping of rows of a table Relationship with the same name as one. example- the table will look like Parent_name .... Childern_name A Mittal ........ Children 1 A Mittal ........ Children 2 A Mittal ........ Children 3 B Mittal .........children 1 B Mittal .........children 2 Now I created an HTML where I want to see only A Mittal B Mittal For which I have to define in views - parentnames= Relationship.objects.distinct(Parent_name) But it's not working kindly help. Is there any other way also to do it? -
Creating user profile on successful registration DJANGO
Imm trying to create a user profile for users on successful registration, but facing some issues, can't seem to figure out the problem. On successful registration it doesn't create any profile for user, but i was able to manual create profile admin page. Here's what i tried: Models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpeg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' Signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required() def profile(request): return render(request, 'users/profile.html', context) Apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals profile.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ … -
how to financial settlements with partners in django oscar?
I'm trying to develop an eCommerce website by Django-oscar. I have multi partners in my project and I don't know how to financial settlements (check out) with partners in Django oscar? can you help me? Do you know how oscar handle that? -
Downloading a file via Axios from Django
I'm trying to get filename from blob request using Axios and Django. Django's view: with open(full_file_path, 'rb') as f: response = HttpResponse(f, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') file_expr = "filename*=utf-8''{}".format(quote(file_name_with_ext)) response['Content-Disposition'] = 'attachment; {}'.format(file_expr) return response Frontend: axios .request({ url, method, responseType: 'blob', }) .then(({ data }) => { console.log(data); const downloadUrl = window.URL.createObjectURL(new Blob([data])); const link = document.createElement('a'); link.href = downloadUrl; link.setAttribute('download', 'file.xlsx'); document.body.appendChild(link); link.click(); link.remove(); }); But parameter 'data' doesn't contain headers to allow me to get filename. Is there any solution? -
Django Rest Framework: obtain user details and permissions with token login
My (Angular) frontend performs jwt login to the Django Rest Framework backend through the provided jwt_views.TokenObtainPairView class. However, this returns only access and refresh tokens, and I'd actually like to get more, such as username and the permissions the user has (so that the frontend can hide or disable any features the user can't use anyway). What would be the best solution to achieve this? Write my own token-generating view? Subclass the existing view and overwrite the serializer with one that fetches user information? Use a different method to transfer permissions or to log in? The level of 'magic' that happens in Django confuses me as to what parameters and values I can set and overwrite.