Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to decide where to put a function in django fat model implemantation
I want to know where to put a function on models that related to multiple models. I have four models: 1- custom user 2- office 3- company 4- vehicle every vehicle, user and office has a foreign key to company. I want to have all vehicles from a company I have tried to put a staticmethod on vehicles to get appropriate vehicles but I am not sure this is the right way of doing things because I have to pass request to models. @staticmethod def get_current_company_vehicles(request): Vehicle.objects.filter( located_office__in=CompanyOffice.objects.filter(company=request.user.company).values_list('pk') ) Where would you guys put the function and how to decide where a functions should go? -
Spring password encoder for the default Django password format (pbkdf2_sha256)
I am working on a Spring Boot application using Spring Security connected to a database originally generated by Django, in which all of the user passwords are stored in Django's pbkdf2_sha256 format. <algorithm>$<iterations>$<salt>$<hash> Looking at Spring Security's Pbkdf2PasswordEncoder, I was able to mostly figure it out and create an encoder that is able to encode and match Django's format. After successfully unit testing it, I tried it on a sample value generated by Django... and it failed. Why is this encoder not matching Django-generated values? Is Django performing some ~magic~ under the hood? I have also tried multiple replacements for Java's SecurityFactory implementation. This line in Django's source code caught my attention as well, but writing the equivalent Kotlin did not fix the issue. class DjangoPbkdf2PasswordEncoder : PasswordEncoder { companion object { private const val PREFIX = "pbkdf2_sha256" private const val SEPARATOR = "\$" private const val ITERATIONS = 180000 private const val HASH_WIDTH = 256 private const val ALGORITHM = "PBKDF2WithHmacSHA256" } private val saltGenerator: BytesKeyGenerator = KeyGenerators.secureRandom() private fun base64Decode(string: String): ByteArray { return Base64.getDecoder().decode(string) } private fun base64Encode(bytes: ByteArray): String { return Base64.getEncoder().encodeToString(bytes) } override fun encode(rawPassword: CharSequence): String { val salt = saltGenerator.generateKey() val hash = … -
To add values to a django model while I add value to another model
Let's say I have a model 'Books' and another model 'Products'. When I add a Book from django admin, I want the Book name and Book Code to be added to the Model 'Products'. -
"instance = my_model(user=user)" throws "my_model.user" must be a "User" instance when using AbstractBaseUser
I have created an AbstractBaseUser by the following #users/managers.py from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('Du skal indtaste en email')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) #users/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext_lazy as _ from django.utils import timezone from .managers import CustomUserManager from django.conf import settings class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('E-mail'), unique=True) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) wants_email = models.BooleanField(_("Send mig emails"),default=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email my creation-form #users/forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(error_messages={"unique":"This … -
'User' object has no attribute 'is_staff'
I have created my own user model by using AbstractBaseUser . I create the super user through terminal , which is created successfully . But when I go to the admin side and wrote the password and email there, This throw me the error that 'User' object has no attribute 'is_staff'. My models.py file is: class UserManager(BaseUserManager): def create_user(self, email, full_name=None, password=None, is_staff=False, is_admin=False): if not email: raise ValueError("User must have an email") if not password: raise ValueError("User must have a password") user_obj = self.model(email=self.normalize_email(email), full_name=full_name) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,full_name=None,password=None): user = self.create_user(email, full_name=full_name,password=password) return user def create_superuser(self,email, full_name=None,password=None): user = self.create_user(email, full_name=full_name, password=password) return user class User(AbstractBaseUser): full_name = models.CharField(max_length=255, blank=True, null=True) sur_name = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(max_length=255 ,unique=True) choose_subject = models.CharField(choices=SUBJECT_CHOICES , max_length=100) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) time_stamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] object = UserManager() def __str__(self): return self.full_name -
T Format date inside json
I am getting json from backend like this : { "datas":[ { "id":4, "create_date":"2021-03-18T21:11:57.239Z" }, { "id":5, "create_date":"2021-03-19T19:37:05.829Z" } ] } and looping through json like below : $(data.datas).each(function(index,value){ html += `<tr><th scope="row">${index+1}</th> <td>${value.id}</td> <td>${value.create_date}</td> <td><a href="#" class="btn btn-outline-dark">View Car</a></td> </tr>` }) But, here create_date is just printing in td column like this 2021-03-18T21:11:57.239Z . So, how can i make this display like this 2021-03-18 & 21:11 am/pm in each tds ? My attempt : var created_date = value.create_date; console.log(created_date.split("T")[0]);//2021-03-18 console.log(created_date.split("T")[1])//21:11:57.239Z (how can i remove 57.239Z..) I am open for both solution i.e : backend as well as frontend . For my backend i am using django let me know if you need to see any code from backend . -
Django Reloading specific part of a page using AJAX
I am attaching another stackoverflow answer here. I have no idea on Javascript or Ajax. So can someone please let me know how to reload a div using Ajax to get the data from the included html into the original HTML , Thanks. The motive is to reload a div alone without refreshing the whole page. Other Stackoverflow answer : To treat the same view in a different way if you receive an ajax request. I would suggest splitting your result-page.html into two templates, one that contains only the div that you want, and one that contains everything else and includes the other template (see django's include tag). In your view then you can do something like the following: views.py : def sort(request): objs = any_models.objects.all() context = { 'objs' : objs , } if request.is_ajax(): template = 'partial-results.html' else: template = 'result-page.html' return render_to_response(template, context ,context_instance=RequestContext(request)) results-page.html: <html> <div> blah blah</div> <div id="results"> {% include "partial-results.html" %} #I want to reload only this div by sending ajax req to views and getting the partial html uploaded and thus this section which includes the partial gets updated without reloading the entire page... </div> <div> some more stuff </div> </html> partial-results.html: … -
django -View screen on django admin page
if I click ID 1 on the current screen, I want to decorate it with a non-modifiable and read-only screen. However, currently, clicking on the ID 1 value will access the screen that can be modified. What are the options? There is a separate modification button, and I want to be read-only before I modify it. -
Django - Postgres creates a row in table after some time even if API returns success instantly
There is a POST API, which takes 2 seconds to return the response. Its does two simple insertions into two different tables, one is dependent on other. Some times, the insert query is created after more than a minute, even when the API is completed in 3 - 5 seconds. Every step is synchronous and there are no asynchronous tasks in this API. Is this a problem because of Postgres or any other problem Table 1 has 13k rows and table 2 has 242k rows. It works seamlessly sometimes, but most of the times , i am seeing the same pattern, where the row insertion is done after a minute or 2. -
(1062, "Duplicate entry '81CLZECZRW' for key 'orders_orderitem.orders_orderitem_orderItem_ID_7d6cd69b_uniq'") on Django Rest Framework
I am trying to generate a uniq OrderItem_ID during the order create api. But, it generates the above error as django.db.utils.IntegrityError: The first api is always successful from the postman, but in the second call I tried changing different products for creating the order, but I am getting this unique id order. I have to remove the order_items from db , to create a new order_item object otherwise I get this unique error. I am sending data like this. My model: import random import string # Create your models here. def id_generator(size=10, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) total_price = models.CharField(max_length=50,blank=True,null=True) def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): orderItem_ID = models.CharField(max_length=12,unique=True, editable=False, default=id_generator()) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) total_item_price = models.PositiveIntegerField(blank=True,null=True,) My serializers: class OrderSerializer(serializers.ModelSerializer): billing_details = BillingDetailsSerializer() order_items = OrderItemSerializer(many=True) user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Order fields = ['id','user','ordered_date','order_status', 'ordered', 'order_items', 'total_price','billing_details'] # depth = 1 def … -
Using Django models how would I organize URL, Hostname, IP Address information with trickling-up ValidationError exceptions? Inheritance or?
I have three models (URL, Hostname, IPAddress). If I create a URL the overridden save() method of that class finds the hostname and does get_or_create() for Hostname. The save() method for Hostname does a similar thing for IPAddress etc. Am I doing this the hard way? Should I be doing some kind of inheritance stuff with this instead? I don't know if inheritance is the way to go because a URL can have one hostname but also have many IP addresses. Inheritance doesn't seem suited for that kind of situation. I have to admit I haven't tried using inheritances yet but if it's a possible solution to this I'm willing to rewrite the entire thing. I cannot seem to get the ValidationError that validate_ip() throws to trickle all the way up to when I attempt to add a URL that has an IP address that doesn't pass the validator. It throws the exception in django admin but not in the nice way of putting the error above the URL entry field. Instead of it gives a 500 error page. ...snip... def validate_ip(ip_addr): """Check ip_addr: - belongs to an ASN we manage - not whitelisted """ asn, _, _ = lookup_asn_info(ip_addr) … -
Autocomplete light not showing options after reload
I have a django-autocomplete-light on my form which is working great. However when the form is non valid, the form is reloaded with all the fields filled, but only the autocomplete field is now empty. Any ideas? models.py genre = models.ManyToManyField(Genre) views.py if form.is_valid(): genre = form.cleaned_data.pop('genre') instance = Artist(**form.cleaned_data) instance.save() for g in genre: instance.genre.add(g) return HttpResponseRedirect('/thanks/') return render(request, 'application/form.html', {'form': form}) forms.py class Meta: model = Artist widgets = { 'genre': autocomplete.ModelSelect2Multiple( url='genre-autocomplete', attrs={ # Set some placeholder 'data-placeholder': 'Autocomplete ...', # Only trigger autocompletion after 3 characters have been typed 'data-minimum-input-length': 3, }, ) } form.html {% crispy form %} Thank you in advance! -
Django: How to edit model without PK in URL?
I'm writing a multiuser app, the problem is if I Edit a Product I have the URL: re_path(r'backend/produkter/edit/(?P<artikel_id>[0-9]+)/$', backend_views.edit_artikel_view), Which results: http://127.0.0.1:8000/backend/produkter/edit/36/ Now another User can use this URL because he is authenticated, and it looks not clean to me. Is it possible to go from view / url: http://127.0.0.1:8000/backend/produkter/ to http://127.0.0.1:8000/backend/produkter/edit/ and give the ID on another way to the editView? -
Django Rest Framework Return List of all parents and their children
I have been going crazy searching for an answer. I have two tables (models) as follows: class DisplayPosts(models.Model): post_id = models.CharField(unique=True, max_length=300, blank=True, null=True) post_url = models.CharField(max_length=300, blank=True, null=True) class Observations(models.Model): post = models.ForeignKey(DisplayPosts, to_field="post_id", on_delete=models.DO_NOTHING, related_name='observations') created = models.DateTimeField(blank=True, null=True) I have created the following seriailzers: class ObservationsSerializer(serializers.ModelSerializer): class Meta: model = Observations fields = '__all__' class DisplayPlostsSerializer(serializers.ModelSerializer): observation = ObservationsSerializer(many=True, source='observations') class Meta: model = DisplayPosts fields = '__all__' I am trying to create a search API to retrieve a list of posts urls and their respective created dates (the relationship between DisplayPosts to Observations is one-to-many). When I retrieve a single post I get all the child observations, but when I try to pull a list based on search terms, the child list is empty. These are my views for single post v.s. list posts: @api_view(['GET', ]) @permission_classes((IsAuthenticated,)) def api_detail_posts(request, post_id): try: display_post = DisplayPosts.objects.get(post_id=post_id) except DisplayPosts.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = DisplayPlostsSerializer(display_post) return Response(serializer.data) class ApiPostListView(ListAPIView): queryset = DisplayPosts.objects.all() serializer_class = DisplayPlostsSerializer observaation_serializer_class = ObservationsSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) filter_backends = (SearchFilter, OrderingFilter) pagination_class = PageNumberPagination search_fields = ('post_id', 'post_url') I would appreciate any hints on how I can go about … -
How can I use Med7 and Negspacy simultaneously?
I'm trying to use med7 and negspacy from Spacy but they both need separate version of spacy. How can i use both in the same script? I'm using en_core_med7_lg from spacy to get disease, drug and other entities out of text import spacy import scispacy from spacy import displacy from spacy.matcher import PhraseMatcher from spacy.tokens import Span from negspacy.negation import Negex med7 = spacy.load("en_core_med7_lg") # create distinct colours for labels col_dict = {} seven_colours = ['#e6194B', '#3cb44b', '#ffe119', '#ffd8b1', '#f58231', '#f032e6', '#42d4f4'] for label, colour in zip(med7.pipe_labels['ner'], seven_colours): col_dict[label] = colour options = {'ents': med7.pipe_labels['ner'], 'colors':col_dict} negex = Negex(med7, ent_types=["DISEASE", "NEG_ENTITY"], name="negex", neg_termset={'pseudo_negations': ['no further', 'not able to be', 'not certain if', 'not certain whether', 'not necessarily', 'without any further', 'without difficulty', 'without further', 'might not', 'not only', 'no increase', 'no significant change', 'no change', 'no definite change', 'not extend', 'not cause', 'neither', 'nor'], 'preceding_negations': ['absence of', 'declined', 'denied', 'denies', 'denying', 'no sign of', 'no signs of', 'not', 'not demonstrate', 'symptoms atypical', 'doubt', 'negative for', 'no', 'versus', 'without', "doesn't", 'doesnt', "don't", 'dont', "didn't", 'didnt', "wasn't", 'wasnt', "weren't", 'werent', "isn't", 'isnt', "aren't", 'arent', 'cannot', "can't", 'cant', "couldn't", 'couldnt', 'never', 'neither', 'nor'], 'following_negations': ['declined', 'unlikely', 'was not', 'were not', "wasn't", 'wasnt', "weren't", … -
How do I get user input from search bar to display in a page? Django
Django is very challenging and I still need to get used to the code and currently, I just want the search bar to display every time a user input a text and it will display like a title I really don't how to interpret the code to tell that every time the user inputs in the search bar, It is supposed to display the user input on a page like a title. Example: user input in the search bar: cat and it displays cat title Display on the current page: Result search: "Cat" HTML Code <!-- Search Bar --> <form action="{% url 'enc:search' %}" method="GET"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search"> </form> In my views.py I only write this code and I don't know what to write it. views.py def search (request): title = request.GET.get("q", "") urls.py urlpatterns = [ path("", views.index, name="index"), path("search/", views.search, name="search"), Right now just a simple display from the search bar input later I will code it in a data search where there is some file to integrate the search but right now I really need some help my brain is cracking. It's kinda sad I mean I know it be a simple … -
Google Autocomplete with Modal Dialog HTML5
Been working with google's autocomplete for a project to use it to find establishments. However whenever I call for it, the pac container div is appended to the body of the html rather than the dialog tag of modal dialog. I have tried a lot of stuff, using promises, messing with focusing. However whenever the page is loaded or whenever you focus into the input box, the first iteration of loading the autocomplete sets the container to the body rather than the input box itself. I've tried also taking it out of the ready and placing it else where, doing a callback into the google url itself. However a simple timeout function does get rid of the pac container, but I would rather like to solve this issue without the use of one. Image of pac container when the dialog screen is loaded up Here is a sample of what my code looks like for the dialog. <dialog id="myDialog> <div class="modal-body"> <input id="searchbox" name="searchbox"/> </div> </dialog> <script> $(document).ready(function () { initAutocomplete(); }); </script> autocomplete.js function initAutocomplete() { const input = document.getElementById("searchbox"); const autocomplete = new google.maps.places.Autocomplete(input); autocomplete.addListener("place_changed", () => { var place = autocopmlete.getPlace(); /* Rest of the code*/ } … -
How to maintain authentication data
I am doing a Vue 3 practice together with Django Rest Framework, what I am trying to do is a token authentication validation, a user logs in, a token is going to be generated, but I run into a problem and it is that when at moment of logging in is done correctly and I am able to obtain the generated token, the problem is that when reloading the page the token is no longer in the vue application, a possible solution that I decided is to make the token save in local storage, but i think it is not the correct solution. This is my Login.vue: <template> <h2>login</h2> <form method="POST" @submit.prevent="sendData" autocomplete="off"> <input type="text" placeholder="Nombre de Usuario" v-model.trim="username" /> <input type="password" placeholder="Contraseña de Usuario" v-model.trim="password" /> <button type="submit">enviar</button> </form> </template> <script> import { ref } from '@vue/reactivity'; import { watchEffect } from '@vue/runtime-core'; export default { setup() { const username = ref(''); const password = ref(''); const token = ref(''); const sendData = () => { fetch(`http://localhost:8000/auth-token/`, { method: 'POST', body: JSON.stringify({ username: username.value, password: password.value, }), headers: { 'Content-Type': 'application/json', }, }) .then((res) => res.json()) .catch((error) => console.error('Error:', error)) .then((response) => { token.value = response.token; }); }; watchEffect(() … -
How to prevent Django caching querysets in memory in a ./manage.py command
I have a ./manage.py command that is made to run as a service in the background. However the memory usage goes up steadily and the script gets killed eventually. By using memory_profiler I found that the memory usage goes up after each query, especially after bulk_create(). I tried putting the results in a variable and setting it to None, also tried django.db.connection.close() after each iteration of the endless loop. Is there a way to tell Django not to cache those queries? -
Make Django Admin Commands run automatically in deployment (apache2)
I am creating an eCommerce site and want to delete rows of the order table after 20 days has passed. And I was successfully able to do that! My code... delete_old_orders.py from django.core.management.base import BaseCommand, CommandError from store.models import Order from datetime import datetime, timedelta class Command(BaseCommand): help = 'Delete objects older than 20 days' def handle(self, *args, **options): Order.objects.filter(order_date__lte=datetime.now()-timedelta(days=20)).delete() self.stdout.write('Deleted objects older than 10 days') In which, just for your information my file location goes as... store/ models.py management/ __init__.py commands/ __init__.py delete_old_orders.py tests.py views.py Every time in order to run it, I need to run the code python manage.py delete_old_orders in the terminal. However, this is in my local machine, when I want this to run every day at 2am in my server, which runs apache2 in Ubuntu. How should I deal with this? Should I alter my config file in the server? Any help would be much appreciated! Thanks! -
Translation from data in database
I implemented a logs system in my Django app, this system, for every action of any user will save informations in the database. Here is the model: class Log(models.Model): user = models.ForeignKey(to=User, on_delete=models.PROTECT) log = models.CharField(max_length=255) type = models.CharField(max_length=50) date = models.DateTimeField(auto_now_add=True) company = models.ForeignKey(to=Company, on_delete=models.PROTECT) My point is on the translation of the log field. For exemple my language is english, it will save in the database "did create a new customer", But if I change the language in french I will obviously get this in english again. Same if a french create a log I will have some logs in french others in english. My problem is there is hundreds of different possibilities for this log field. Is it a way with Django to translate data coming from the database in the templates like with a {% translate %} tag? I was thinking something like having these hundreds possibilities in the translation files and Django translate it directly in the templates? I do have the same problem with the permissions name. Users can give permissions to other users but these permission names are in english. Thanks for your help -
Django served on specific URL - relative urls corrupted
I've deployed my Django (DRF API) project on DigitalOcean apps. The path "/" is used by my static site that uses this API so I set route for this component to "/api" which works correctly. The problem: I go to /api/admin/ and it redirects me to /admin/login but the django is served on /api url so this URL is invalid. Do you know how to make this work? Is there a way to tell django to use absolute URL everywhere? -
Is possible to make unique a field in the database for a foreign key?
Lets suppose that I have two models named Company and Airplane: class Company(models.Model): name= models.CharField(max_length=250) location=models.Charfield(max_length=250) class Airplane(models.Model): company = models.ForeignKey(Company, on_delete=models.RESTRICT) number = models.IntegerField(unique=True) I want the number in Airplane model to be unique but just in the same company, an airplane from another company can have the same number. Is it that possible? -
Error 500 in djangoAPP deployed on microsoft AZUR
so i've tested my djangoApp locally and everything went fine, then i used microsoft Azur to deploy my App, many users were able to register but most of them got the error 500,i want to know what's could be the problem and how can i fix it? -
Stop python function call on page reload
I have a python function which is called by an onclick HTML event - <button name="get_key_btn" class="waves-effect waves-light btn" onclick="location.href='{% url 'getkey' %}'" method="GET">My Keys</button> Python function below - @login_required def get_key(request): """A view to return landing page keygen""" args = {} customer_name = request.user.username return render(request, 'landing.html', {'customer_name': customer_name}) The above get_key function is called each time the browser is refreshed, which is causing some difficulty.