Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Empty Django Inline saying fields are required
In django admin I'm trying to create a new entry, but fields in the inline forms are throwing errors saying they are required even if I don't want to create a new inline. models: class Attribute(models.Model): name = models.CharField(choices=ATTRIBUTE_CHOICES, max_length=max_choice_len(ATTRIBUTE_CHOICES)) amount = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() def __str__(self): return f'{self.name} {str(self.amount)}' class Item(models.Model): ... attributes = GenericRelation(Attribute) admin: class AttributeInline(GenericTabularInline): model = Attribute extra = 0 class ItemAdmin(admin.ModelAdmin): inlines = [AttributeInline] class Meta: model = Item admin.site.register(Item, ItemAdmin) -
Django's python manage.py createsuperuser gives error OperationalError: 'no such table'
I am working on my Final Year Project. I wanted to extend the default User model that Django provide in order to add some more attributes. I added following code in my models.py class User(AbstractUser): contact = models.CharField(max_length=100) Also in settings.py I added: AUTH_USER_MODEL = 'esacp.User' where as esacp is the name of my app. After doing all of this, I ran python manage.py makemigrations esacp, then I ran python manage.py migrate in my CMD. Both of these commands worked prfectly. Now, I went to create an admin role for my Django Web App, in order to manage the things as a superuser, when I ran the command python manage.py createsuperuser, it asked me for the username, after I entered username and pressed 'Enter', it gave me the error: django.db.utils.OperationalError: no such table: esacp_user The screenshot of the whole error is attached below enter image description here Kindly tell me where did I make mistake or miss anything? Thanks in advanced! -
Why does the Django message tags boxs is not working?
I have a problems with the message tags. So I have a little apps that send a sms. When I press the submit button and my webpage, if the sms is send correctly a message.success is printed on the screen.(The success messages work fine. the text and green color appear correclty) But if the message is not sent, an message.error is printed, but only the text is printed, the red color box is not printed(Which is not fine, I also want the Red box to be printed). I searched online to find a answer, but I didn't find anything.THanks for help views.py try: sms = Client.messages.create( from_="+14509001443", body=mess, to=number ) send = sms.sid print("DOne") form.instance.author = request.user form.save() messages.success(request, f'Votre message a bien été envoyé!') return redirect("sms-home") except: print("error") messages.error(request, f'Votre message na pas été envoyé!') return redirect("sms-home") home.html {% extends "sms/base.html" %} {% load crispy_forms_tags %} {% block content %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} <div> <form method="POST"> {% … -
Django Exists() / ~Exists() return if there is no matching data?
I have the DetailView below with a query/subquery that checks whether supplier_code exists within instances of a second model set up to represent purchase orders received into a live stock database. The intention is for this to function as a checklist/ticksheet that will return whether or not the order has been received for each supplier expected to send one. Getting it to return that there is a match seems to be working fine, and if there is a value it does not recognize (I have purposefully created an invalid order that won't match against the list) it will return that there is no match. However I need this to also tell me that there is simply no data, yet I don't seem to be able to achieve this. For example the below shows the template output; G001 is the 'fake' code I have set up and G002 is a valid one that exists in the suppliers list. However if there is not an order present for G002 it will not return anything. Order not received: G001 Order received: G002 I have tried writing a second query for the context that is a mirror of context['db_orders'] but using the ~Exists() and … -
Simplifying Javascript which adds an "active" class according to URL (DRY)
I usually write in Python on the back-end and am not seasoned on JS. This code looks pretty nasty to me as it repeats itself a lot. If I were writing in Python I think I would make a list of objects then loop over the list of objects to add the active class if one of the objects matches the URL. Can I do that with JS? Or what is a good way to optimize this from someone who writes on the front-end normally? var url = window.location.pathname; var overview = document.getElementById("overview"); var cats = document.getElementById("categories"); var videos = document.getElementById("videos"); var tests = document.getElementById("tests"); var memos = document.getElementById("memos"); var overviewBtm = document.getElementById("overview-btm"); var videosBtm = document.getElementById("videos-btm"); var testsBtm = document.getElementById("tests-btm"); var memosBtm = document.getElementById("memos-btm"); var profileBtm = document.getElementById("profile-btm"); var superUsersBtm = document.getElementById("super-users-btm"); var superResultsBtm = document.getElementById("super-results-btm"); var superNewBtm = document.getElementById("super-new-btm"); var superInviteBtm = document.getElementById("super-invite-btm"); var superProfileBtm = document.getElementById("super-profile-btm"); if (url == '/overview/'){ console.log(url); if (overview){ overview.classList.add('nav-active'); } else if (overviewBtm){ overviewBtm.classList.add('nav-active'); } } else if (url == '/categories/'){ console.log(url); if (cats){ cats.classList.add('nav-active'); } } else if (url == '/videos/'){ console.log(url); if (videos){ videos.classList.add('nav-active'); } else if (videosBtm){ videosBtm.classList.add('nav-active'); } } else if (url == '/tests/'){ console.log(url); if (tests){ tests.classList.add('nav-active'); … -
JavaScript doesn't work with elements from forms.py
I have a JavaScript function witch takes form's input and display an autocomplete box. The script recognizes the input but it does nothing (I've test the function with other file in witch I manually created the form, it works properly using only html and js). I can't find out the problem when I create the form using forms.py form.py ... class SearchForm(forms.ModelForm): class Meta: model = city fields =[ 'city_name', ] widgets = { 'city_name': forms.TextInput(attrs={'class': 'from_input', 'id':'ct_input'}),} template.html <form ...> <div> {{ form.city_name }} </div> </form> script.js cities = ["city1","city2"] function autocomplete(inp, arr) { var currentFocus; inp.addEventListener("input", function(e) { var a, b, i, val = this.value; closeAllLists(); if (!val) { return false;} currentFocus = -1; a = document.createElement("DIV"); a.setAttribute("id", this.id + "choices-list"); a.setAttribute("class", "choices_form"); this.parentNode.appendChild(a); for (i = 0; i < arr.length; i++) { if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) { b = document.createElement("DIV"); b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>"; b.innerHTML += arr[i].substr(val.length); b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>"; b.addEventListener("click", function(e) { inp.value = this.getElementsByTagName("input")[0].value; closeAllLists(); }); a.appendChild(b); } } }); inp.addEventListener("keydown", function(e) { var x = document.getElementById(this.id + "choices-list"); if (x) x = x.getElementsByTagName("div"); if (e.keyCode == 40) { currentFocus++; addActive(x); } else if … -
¿Puedo hacer que carguen mis static files en DEBUG = False, en mi proyecto django sin tener que hacerlo servidor web? ¿y de que forma?
Quiero que carguen los static files de mi proyecto en django pero no quiero pasarlo a un servidor web aún, ¿hay manera de cargar los static en DEBUG = False? -
Keeping data in the form after the search
I have got a form to filter the items on my site, but when I enter the data to filter and press search, then I got the results, but the data that I put in my form disappear. Is there a way to save the data and display it in the form after the search? views.py that handles the filtering of the data def HomeView(request): item_list = Item.objects.all() item_list = item_list.annotate( current_price=Coalesce('discount_price', 'price')) category_list = Category.objects.all() query = request.GET.get('q') if query: item_list = item_list.filter(title__icontains=query) cat = request.GET.get('cat') if cat: item_list = item_list.filter(category__pk=cat) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') if price_from: item_list = item_list.filter(current_price__gte=price_from) if price_to: item_list = item_list.filter(current_price__lte=price_to) paginator = Paginator(item_list, 10) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context = { 'items': items, 'category': category_list } return render(request, "home.html", context) form in the html template: <form method="GET" action="."> <div class="form-group col-md-4"> <label for="category">Category</label> <select id="cat" class="form-control" name="cat"> <option value="" selected>Choose...</option> <option value="" href="/home">All</option> {% for cat in category %} <option value="{{ cat.pk }}">{{ cat }}</option> {% endfor %} </select> </div> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="q" placeholder="Brand.."> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> … -
get_or_create fails for unique_together for decimals
I have the following model: class LocationPoint(models.Model): latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) class Meta: unique_together = ( ('latitude', 'longitude',), ) Interactor: class GetOrCreateLocationPoint(object): def exec(self, latitude: Decimal, longitude: Decimal) -> LocationPoint: point, _ = LocationPoint.objects.get_or_create( latitude=latitude, longitude=longitude, defaults={ 'latitude': latitude, 'longitude': longitude, }, ) return point And test: class GetOrCreateLocationPointTest(TestCase): # from django.test import TestCase __get_or_create_location_point: GetOrCreateLocationPoint def setUp(self) -> None: self.__get_or_create_location_point = GetOrCreateLocationPoint() def test_create_duplicate(self): point1 = self.__get_or_create_location_point.exec(Decimal(10.5), Decimal(5.01)) self.__get_or_create_location_point.exec(Decimal(13.4), Decimal(1.5343)) point3 = self.__get_or_create_location_point.exec(Decimal(10.5), Decimal(5.01)) self.assertEqual(point1.pk, point3.pk) I get an error while executing point3 = self.__get_or_create_location_point.exec(Decimal(10.5), Decimal(5.01)): django.db.utils.IntegrityError: duplicate key value violates unique constraint "geo_locationpoint_latitude_longitude_08fb2a82_uniq" DETAIL: Key (latitude, longitude)=(10.500000, 5.010000) already exists. However, if in debugger I see that self.model.DoesNotExist is thrown in get_or_create. What's wrong? Django 3.0.3, PostgreSQL 12. -
Django {{ form.as_p }} not rendering
I'm trying to utilize Django forms.ModelForm function. However, I can not get it to render in the browser (Firefox and Chrome tested). In both browser inspection of code, the table\form does not show and there is no error coming from Django at all. The only thing that shows from the html file is the "Save button" Is there something I am missing here? In Models.py from django.db import models class Product_sell_create(models.Model): product_product_sell = models.CharField(max_length=120) product_price_sell = models.DecimalField(decimal_places=2, max_digits=500) product_volume_sell = models.DecimalField(decimal_places=2, max_digits=500) product_location_sell = models.CharField(max_length=120) product_description_sell = models.TextField(blank=False, null=False) Forms.py from django import forms from .models import Product_sell_create class ProductName(forms.ModelForm): class Meta: model = Product_sell_create fields = [ 'product_product_sell', 'product_volume_sell', 'product_price_sell', 'product_location_sell', 'product_description_sell' ] Views.py from django.shortcuts import render from .forms import ProductName def products_create_view(request): form = ProductName(request.POST or None) if form.is_valid(): form.save() form = ProductName() context = { 'form': form } return render(request, "sell.html", context) sell.html {% include 'navbar.html' %} <h1> Upper test</h1> <form> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> <h1> TEST </h1> {% block content %} {% endblock %} -
I'm unable to access Django Admin site
I'm unable to login to the Django Admin site. Below are the excerpts from the error for your kind reference: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 3.0.3 Python Version: 3.8.0 Installed Applications: [. . . 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', . . . ] Exception Type: DoesNotExist at /admin/login/ Exception Value: Site matching query does not exist. I did try the steps listed below: $> python manage.py shell >>> from django.contrib.sites.models import Site >>> site = Site() >>> site.domain = 'example.com' >>> site.name = 'example.com' >>> site.save() It didn't help, got the following error: . . sqlite3.IntegrityError: UNIQUE constraint failed: django_site.domain . . django.db.utils.IntegrityError: UNIQUE constraint failed: django_site.domain . . I would be really thankful if anyone could please help me fix this issue. -
How many users can Sqlite can handle , Django
I have a Django application, which I have hosted on pythonanywhere. For the database, I have used SQLite(default). So I want to know how many users my applications can handle? And what if two user register form or make post at same time, will my application will crash? -
How can I, using django, successfully send json data to a postgres database after receiving this data from an API call?
I am fairly new to django, I have recently built an app that makes API calls. home -> this view asks user for the url. User gives url and clicks submit, on submit sends this url to new view and handles call in "request" request -> receives url, process' call and brings back json data and prints data on screen. As of now this data just gets printed but is not saved in any way. During the printing of the data I need it to send the data to a postgres db so I can refer to it later. The table is built and is connected to django framework and can accept data. What functions or commands, using python and django's framework can make this successful? I know this is a very broad statement I am new to using stackoverflow and do not know what is required of me. Thanks in advance -
CSRF Token Fails When Attempting To Serve Django App On A Subdomain
I am successfully configured two Django apps on these domains respectively: http://omerselcuk.engineer http://visions.omerselcuk.engineer They both work well on GET requests, but while the first (main domain) works with POST requests, the second (subdomain) does not. I can verify I have included {% csrf_token %} correctly, because I cannot even log in to admin panel. (Admin panel is accessible but not loginable.) They both accessible publicly and second Django app's DEBUG is on for you to test yourself if you want. To clarify, when I serve second one on the main domain but in a different port, it works just as expected. -
Why is my djang-carrot queue always closing?
I use django-carrot with rabbitmq and have a task I schedule to run once every day. However, every so often, it just stops working, does not execute the task and I need to restart the daemon and then suddenly it works again. The error log is simply: default-consumer-5 2020-01-30 16:45:17,104 INFO:: Channel opened default-consumer-5 2020-01-30 16:45:17,104 INFO:: Exchange declared default-consumer-5 2020-01-30 16:45:17,104 INFO:: Queue bound default-consumer-5 2020-01-30 16:45:17,104 INFO:: Starting consumer default-consumer-5 MainThread 2020-01-30 16:47:44,548 INFO:: Stopping MainThread 2020-01-30 16:47:44,548 WARNING:: Shutdown received. Cancelling the channel MainThread 2020-01-30 16:47:44,553 INFO:: Closing the channel Has anyone else had this problem? If so, what is happening and how can I solve it? -
How to create user base on data from form?
forms.py ''' class AddUserForm(forms.Form): username = forms.CharField(label='Login', min_length=1) password = forms.CharField(label='Password', widget=forms.PasswordInput) repeat_password = forms.CharField(label='Repeat password', widget=forms.PasswordInput) name = forms.CharField(label="First name", min_length=1, validators=[check_first_upper_letter_validator]) surname = forms.CharField(label="Last name",validators=[check_first_upper_letter_validator]) email = forms.CharField(validators=[EmailValidator()]) ''' views.py ''' class AddUserView(View): def get(self, request): form = AddUserForm() return render(request, 'exercises/form.html', {'form': form}) def post(self, request): form = AddUserForm(request.POST) if form.is_valid(): user = User.objects.create_user(username=...., email=....., password=....) user.save() return HttpResponse("OK") else: return render(request, 'exercises/form.html', {'form': form}) ''' How to get data from form for username, email etc.? -
Django user-specific variable not updating in backend
I have a set a pre-existing teams that the user can join [team1, team2, team3] at /jointeam, and that will show up on /home. My issue is that the variable 'user_team' from Profile stays 'None', even after the user successfully joins a team. In other words, if I enter 'team1' on /jointeam , I'd like it to assign it to user.profile.user_group Thanks in advance, appreciate your input! Here is my code: Models.py #used to create a team class TeamCreation(models.Model): team_name = models.CharField(max_length=100, default=None, unique=True) [...] def __str__(self): return self.team_name #user-specific class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_team = models.CharField(max_length=30, null=True) [...] def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) #model to join a team class Join(models.Model): team_name = models.CharField(max_length=100, default=None, unique=False) def __str__(self): return self.team_name Forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username','email'] class TeamCreationForm(forms.ModelForm): class Meta: model = TeamCreation fields=['team_name'] class JoinForm(forms.ModelForm): class Meta: model = Join fields=['team_name'] views.py - users [...] @login_required def join_team(request): form_class = JoinForm form_join = form_class(request.POST or None) user = request.user if request.method=='POST': if form_join.is_valid(): newJoin = form_join.save(commit=False) if not TeamCreation.objects.filter(team_name=newJoin.team_name).exists(): print("nope") return redirect('dashboard') messages.error("Team doesn't exist or incorrect key") else: print("exist") group_name=newJoin.team_name user.profile.user_team=group_name … -
How to access request.user from Form in Django
I want to create a select box form. I'm planning to take the user values of ManyToManyField and make it a select box. But I don't know how to access the value of request.user in the form. How can I access request.user? class AddForm(forms.Form): cp_list = MyModel.objects.filter(cp_list__in=str(request.user.id)) # for c in cp_list: # c.code code = forms.CharField( # widget=forms.Select ... ) -
Difference between using slug_url_kwargs and pk_url_kwargs for get_object()
Difference between using slug_url_kwargs and pk_url_kwargs for get_object() When would i use one over the other? from django.urls import path from books.views import AuthorDetailView urlpatterns = [ #... path('authors/<int:param>/', AuthorDetailView.as_view(), name='author-detail'), ] For the above example, would pk_url_kwargs = 'param' be sufficient? When would i use the slug? -
Python DRF, DETAIL: Key (" ")=(1) is duplicated Error
I'm trying to run this code in django shell: >>> from TwoLocationsTrian.models import PostGDT1AndUAV >>> from TwoLocationsTrian.serializers import PostGDT1AndUAVSerializer >>> serializer = PostGDT1AndUAVSerializer() >>> print(repr(serializer)) which gave me this error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 537, in __repr__ return representation.serializer_repr(self, indent=1) File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/rest_framework/utils/representation.py", line 77, in serializer_repr fields = serializer.fields File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 363, in fields for key, value in self.get_fields().items(): File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 1063, in get_fields source, info, model, depth File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 1208, in build_field return self.build_unknown_field(field_name, model_class) File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 1325, in build_unknown_field (field_name, model_class.__name__) django.core.exceptions.ImproperlyConfigured: Field name `latitude_gdt` is not valid for model `PostGDT1AndUAV`. So, I tried to change the fields in the model: # The updated model. from django.db import models class PostGDT1AndUAV(models.Model): """ POST user's GDT1 and UAV locations. """ latitude_gdt = models.FloatField(verbose_name='LatitudeGDT1', unique=False, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=0) longitude_gdt = models.FloatField(verbose_name='LongitudeOfGDT1', unique=False, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google " "Maps.", default=0) latitude_uav = models.FloatField(verbose_name='LatitudeOfUAV', unique=False, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google " "Maps.", default=0) longitude_uav … -
Error when searching for title and price at the same time
I have got a filter form, where I can filter the content by category, title and the price. I am able to search the items by the category and price or category and title at the same time, but I am getting an error when I am trying to filter by using price and the title. Here's the error, that I am getting after filtering by price and the title: FieldError at / Cannot resolve keyword 'current_price' into field. Choices are: category, description, discount_price, id, image, label, orderitem, price, slug, title views.py def HomeView(request): item_list = Item.objects.all() item_list = item_list.annotate(current_price=Coalesce('discount_price', 'price')) category_list = Category.objects.all() query = request.GET.get('q') if query: item_list = Item.objects.filter(title__icontains=query) cat = request.GET.get('cat') if cat: item_list = item_list.filter(category__pk=cat) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') if price_from: item_list = item_list.filter(current_price__gte=price_from) if price_to: item_list = item_list.filter(current_price__lte=price_to) paginator = Paginator(item_list, 10) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context = { 'items': items, 'category': category_list } return render(request, "home.html", context) html: <form method="GET" action="."> <div class="form-group col-md-4"> <label for="category">Category</label> <select id="cat" class="form-control" name="cat"> <option value="" selected>Choose...</option> <option value="" href="/home">All</option> {% for cat in category %} <option value="{{ cat.pk }}">{{ cat }}</option> … -
Como usar/gerenciar vários bancos de dados com o Django Rest
Estou usando um banco de dados local do MongoDB Compass, mas pode ser qualquer banco de dados, minhas settings.py contem essas informações para configurar o banco de dados: DATABASE_ROUTERS = ['manager.router.DatabaseAppsRouter'] DATABASE_APPS_MAPPING = {'banco1': 'DB1', 'banco2':'DB2', 'banco2':'DB3' } DATABASES = { 'default': {}, 'DB1': { 'NAME': 'DB1', 'ENGINE': 'djongo', }, 'DB2': { 'NAME': 'DB1', 'ENGINE': 'djongo', }, 'DB3': { 'NAME': 'DB1', 'ENGINE': 'djongo', }, } Meu models.py está assim: nome1 = models.CharField('TAG', max_length=100,blank=True) texto1 = models.TextField('Ordem de Manutenção', blank=True) data1 = models.DateField('Data de teste', default=datetime.date.today, blank=True) class Meta: app_label = 'banco1' def __unicode__(self): return self.nome1 class Exemplo2(models.Model): nome2 = models.CharField('TAG', max_length=100,blank=True) texto2 = models.TextField('Ordem de Manutenção', blank=True) data2 = models.DateField('Data de teste', default=datetime.date.today, blank=True) class Meta: app_label = 'banco2' def __unicode__(self): return self.nome2 class Exemplo3(models.Model): nome3 = models.CharField('TAG', max_length=100,blank=True) texto3 = models.TextField('Ordem de Manutenção', blank=True) data3 = models.DateField('Data de teste', default=datetime.date.today, blank=True) class Meta: app_label = 'banco3' def __unicode__(self): return self.nome3 Gostaria de utilizar essas diferentes informações destes diferentes banco de dados, em um unico endpoint. Não sei como eu poderia configurar minha views.py, mas imagino que deve ser algo do tipo: from rest_framework.response import Response from .models import * from .serializers import * class Varios_exemplosview(generics.ListAPIView): serializer_class = Exemplo1Serializer queryset … -
Calculate some value based on one of the django model and update 700k objects at once
In my django app I have a model: class Entry(BaseModel): event_name = models.CharField(_('Event name'), max_length=256, null=True, blank=True) slug = models.SlugField(null=True, blank=True, max_length=512) def save(self, *args, **kwargs): if not self.slug: self.slug = self.get_slug() super().save(*args, **kwargs) def get_slug(self): add = 1 slug = None if not self.slug and self.event_name: init_slug = slugify.slugify(self.event_name) slug_available = Entry.objects.filter(slug=init_slug).count() == 0 if slug_available: slug = init_slug else: while not slug_available: check_slug = '{}-{}'.format(init_slug, add) slug_available = Entry.objects.filter(slug=check_slug).count() == 0 if slug_available: slug = check_slug else: add += 1 return slug def make_slug(self): if not self.slug: slug = self.get_slug() self.slug = slug self.save() slug field is empty by default, and now I want to update 700k+ rows with empty slug with new value. I was doing it by querying the database: qs = Entry.objects.filter(slug__isnull=True) and then I was updating items in loop one by one: for entry in qs: entry.make_slug() but I am looking for more efficient way to do it. Do you know any simple solution? -
Angular and Django: SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported
I am working with Angular and Django. In angular I am generating reports with jspdf and html2canvas, for this I am loading images stored in Django and at the moment of wanting to generate the pdf I generate the error mentioned in the title. In Django I have added corsheaders and given the permissions to be able to access from Angular: enter image description here The Angular function to generate the pdf: enter image description here Reviewing pages suggested adding the crossOrigin = "anonymous" but this has not worked for me -
Django user logs for tracking user actions on a website
I am currently working on a django web app and there are around 4 sub web pages with different functionalities on each page. Every user who uses the application has to login via Gmail. so, all the users data is present. Now, how can i actually track all the actions of user actions, for example - When a user visits a sub webpage and click on a link (or) widget (or) button click (or) filtering etc..?