Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I pass two queryset in same function using Django Rest Framework
def getProducts(request): products = Product.objects.all() p = Product.objects.all().filter(category = 1) serializer = ProductSerializer((products,p), many=True) return Response(serializer.data)** I want to pass p and products value in the serializer object. Can I do this here? -
ImportError: cannot import name 'Translatable' from 'translations.models'
When I wrote this:python manage.py makemigrations I get this error:ImportError: cannot import name 'Translatable' from 'translations.models' How can i solve this problem? enter image description here -
Prevent django send_mail timimg attack
I have different REST-API views where I either send a mail (if an account exists) or do not send a mail. For example, the user can input the email in the forgot-password form and a mail is sent if the account exists. I am using from django.core.mail import send_mail to send the mail. The problem is, that this takes some time, and so requests for valid emails are generally longer than requests for non-exiting emails. This allows an attacker to compare the request times to find out if an account exists or not. Is there any way that I can call send_mail() without sending the mail? Or what would be the fix to make request times equally long for both cases? Note: I could check how long send_mail() needs on average and wait this time if I do not send the mail. As the app runs on different servers with different configs, this can not be generally done in my case. I would rather not store the average execution time per server in a database to solve this. -
can't show error message into error function in ajax - django
i'm trying to show error message from server to client site using ajax , but it wont work when i make a function for error messages , #other codes for saving the post,there is not error success_meesage = f'success' return JsonResponse({'success':'success','success_msg':success_meesage}) else: error_message=f'there is an error into your two dates please make sure check in smaller than check out' return JsonResponse({'success':False,'error_taken':True,'error_message':error_message}) my ajax code const form = document.getElementById('post-form') form.addEventListener("submit",submitHanler); function submitHanler(e){ e.preventDefault(); $.ajax({ type:'POST', url:"my-url", data:$("#post-form").serialize(), dataType:'json', success:successFunction, error:errorFunction, }) } function successFunction(data){ // console.log(data) if(data.success='success' && data.success_msg){ form.reset(); alertify.success(data.success_msg) } } function errorFunction(request, status, error){ console.log(request.responseText) if(error.error_taken == true){ alertify.alert('warning !','message') alertify.alert(error.error_message,function(){ }); } } } i also tried this : function errorFunction(jqXHR, exception) it shows nothing as well , i tried many ways but none of them worked ! thank you in advance .. -
How to add in instance field which not in model but created in Django form?Django
I have a model Book: class Book(core.BaseModel): name = models.ForeignKey( FishingGear, verbose_name="Name", on_delete=models.PROTECT, related_name='name', ) library = models.ForeignKey( Library, models.PROTECT, related_name='library_places', verbose_name='Library', ) tag_number = models.PositiveIntegerField('Tag Number', validators=[ MinValueValidator(1), MaxValueValidator(MAX_TAG_NUMBER), ]) In forms.py I created new field : class BookChangeStatusForm(core.ModelForm): start_tag_number = forms.IntegerField(label='Start number', min_value=1) In the same forms.py I have method which takes old data and create new book!But I want that without tag_number it will create field 'start_tag_number': def save(self, commit=True): # instance = super().save(commit=False) instance = Book.objects.create( name=self.instance.name, library=self.instance.library, tag_number=self.instance.**start_tag_number**, ) return instance class Meta: model = Book fields = () But I got Error: Book object has no attribute 'start_tag_number' My views.py class BookTagView(core.UpdateView): form_class = BookChangeStatusForm template_name = 'book/book_tag.html' success_url = reverse_lazy('book:book-list') I want to take in forms.py OLD instance in UpdateView and create new instance with old data but without 'tag_number' insert 'start_tag_number'!Please help me to undestand where is mistake! -
Django change hasher algorithm for user password
I need to transfer SHA512 passwords from another db to Dango. example password - b792e3c67205a800d16fceb2dacf5b70fada6f31e905352750e093bedc95ab970c0121f7c3f2a3bfcab32f3cb8a2c0d2273ada96b082dd0fbd012dbae379dcb1 and i need use auth with this password I try this. but it doesn't work hasher.py import hashlib from django.contrib.auth.hashers import BasePasswordHasher, mask_hash from django.utils.crypto import constant_time_compare from django.utils.translation import gettext_noop as _ class CustomPasswordHasher(BasePasswordHasher): algorithm = 'sha512' def salt(self): return '' def encode(self, password, salt): hash = hashlib.sha512(password.encode()) return hash def verify(self, password, encoded): encoded_2 = self.encode(password, '') return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): return { _('algorithm'): self.algorithm, _('hash'): mask_hash(encoded, show=3), } settings.py PASSWORD_HASHERS = [ 'restorating.hasher.CustomPasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', ] -
Achor tag begining with `?`: Django pagination: next/previous links take one to index
Following the docs on Paginating a ListView. It works great however I see the next and previous link's href starts with ?page= For my site that navigates to www.example.com/?page=2, i.e. the index, instead of staying on the same url, e.g. www.example.com/foos/?page=2. Other example's on the web have it working like the tutorial. In the template I could force it by manually inserting the {{ request.path }}, e.g.: <a href="{{ request.path }}/?page={{ page_obj.previous_page_number }}">previous</a> But I am curious why there is something broken with my setup. I tried to find the spec of how href works if it begins with a ? (is it relative to the root or the current page), but did not find it on MDN or when going down a W3C rabbit hole. -
How to remove white space within an html page
It automatically generates this "empty space" for me and I can't figure out how to remove it. This is the code I wrote in my file: HTML CODE: <div class="btn my-btnmenu btn-danger"> <i class="bi bi-bag"></i> </div> CSS CODE: .my-btnmenu { padding: .325rem .60rem; border-radius: 1.5rem; } .btn-danger { color: #fff; background-color: #dc3545; border-color: #dc3545; } and this is the image of the element inspection generated by my browser: -
why do we need get_absolute_url() in Django?
Can Anyone explain me in simple terms why do we need get_absolute_url() method in django? what is the purpose of defining get_absolute_url() in our django models? -
Pulling data from an existing database ( DJANGO // PYTHON )
I am trying to create a Web App that handles account data and prints said data to account statements and age analysis' The data will need to be fetched from an existing Sage Evolution database and printed to a web page through Django I have had a look at the Django documentation, however, the inspectdb function it gives does not give too much information on how to fetch data through a database IP address. Does anyone have a code example/tutorial on how to fetch this data through an IP address, almost with the same procedure as the below .BAT code import pymssql user = '[User ]' password = '[Password]' server = '[IP]' #username: [Username]_dev_ro #password: [Password] #database name: DB_Name databaseName = 'DB_Name' conn = pymssql.connect(server, user, password, databaseName) cursor = conn.cursor(as_dict=True) cursor.execute('SELECT top 10 * FROM [DB_Name].[dbo].[_etblGLAccountTypes]') for row in cursor: print(row) conn.close() -
drf filter by multiple ManyToManyField ids
Here is my models class Mediums(models.Model): medium_name = models.CharField(max_length=255) class Artwork(models.Model): title = models.CharField(max_length=255, blank=True, null=True) mediums = models.ManyToManyField(Mediums, blank=True, related_name="artwork") class Meta: db_table = 'artwork' I am using django-reft-framework . How can i fetch artwork by filtering multiple medium_id. I checked drf doc could not find option to filter ManyToManyField Pse take a look -
Handle permission cache in django user model
I stumbled upon a weird behaviour: I add a permission to a user object but the permission check fails. permission = Permission.objects.get_by_natural_key(app_label='myapp', codename='my_codename', model='mymodel') user.user_permissions.add(permission) user.has_permission('myapp.my_codename') # this is False! I found some posts about user permission caching here and here and the solution seems to be to completely reload the object from the database. # Request new instance of User user = get_object_or_404(pk=user_id) # Now note how the permissions have been updated user.has_perms('myapp.my_codename') # now it's True This seems really overkill for me and very un-django-like. Is there really no way to either clear the permission cache oder reload the foreign keys like you can do for an object with refresh_from_db()? Thanks in advance! Ronny -
Django - Return a list of primary keys with another attribute of the entity it's referencing
I have this FollowUser and User model below and there's a URL that gets a list of people the user is following (followees). I'd like to return a list of the followees (A User model) that has their UUID and the followees username. How can I do this in a fast and efficient way? models.py class User(AbstractBaseModel): username = models.CharField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(max_length=255, unique=True, primary_key=True) class FollowUser(AbstractSimpleModel): follower_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower_following") followee_id = models.OneToOneField(User, on_delete=models.CASCADE, related_name="followee_followed_by") views.py def get_followees(request, follower_id): try: followees = FollowUser.objects.filter(follower_id=follower_id).values_list('followee_id', flat=True) data = dict(followee_ids=list(followees)) return JsonResponse(data, status=status.HTTP_200_OK) except FollowUser.DoesNotExist: return Response(dict(error=f'follower id: {follower_id} does not exist'), status=status.HTTP_400_BAD_REQUEST) -
How to get cookies (basically I need jwt token) in Ember.js which was set in Django?
Django Rest Framework class LoginView(APIView): password = request.data['password'] user = User.objects.filter(email=request.data['email']).first() if user is None: return Response({ 'success': False, 'message': 'Username or password is invalid', 'errors': 'Username or password is invalid', }, status=status.HTTP_401_UNAUTHORIZED) if not user.check_password(password): return Response({ 'success': False, 'message': 'Username or password is invalid', 'errors': {'username-or-password': ['Username or password is invalid']}, }, status=status.HTTP_401_UNAUTHORIZED) payload = { 'id': user.id, 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='token', value=token, httponly=True) response.data = { 'success': True, 'data': { 'token': token } } return response Here I send token in response data and also set token in cookies. How can I get/receive/retrieve token from cookies in Ember.js? -
Django admin - add extra fields using ModelForm of another model
Is it possible to add extra fields in Django Admin using a ModelForm of another model? Here my models: class ModelOne(Model): field_1_1 = models.SmallIntegerField() field_1_2 = models.ForeignKey(AnotherMyModel) field_1_3 = models.BooleanField(default=True) field_1_4 = models.ManyToManyField(to="TestModel", through="ModelTwo") class ModelTwo(Model): field_2_1 = models.ForeignKey(MyModel, on_delete=models.CASCADE) field_2_2 = models.ForeignKey(ModelOne, on_delete=models.CASCADE) field_2_3 = models.BooleanField(default=True) And the admin looks like: class ModelOneAdmin(admin.TabularInline): model = ModelOne form = forms.ModelTwoForm fields = ('field_1_1', 'field_1_2', 'field_1_3', 'field_2_1', 'field_2_3') Here the form instead: class ModelTwoForm(ModelForm): class Meta: model = ModelTwo fields = "__all__" This code raises the following error: FieldError: Unknown field(s) (field_2_1) specified for ModelOneAdmin I know that this is the case of the inline pattern, but i cannot use it becasue ModelOneAdmin is already inside a inline model (and i don't want to include extra python package to achieve this). Is there a way to fix this problem and achieve this goal? (Working with Python2.7 and Django 1.11) -
Django to allow to upload multiple files for a single record
I am having a requirement in my django application, where user will fill a form with few fields, which also includes the attachments field, my requirement is that attachments should accept multiple files , but these files should be tagged to single record, but now it's creating multiple rows in table based on number of attachments, please help. Thanks in advance -
Deploying with docker
I am new to deploying with docker. Actually, I am running my django app in my computer inside docker container, and it is running successfully on port localhost:8080. Then I pulled the code to remote server and started docker-compose up, and app is running successfully there as well. What I want to ask is that, how can I see the app with the help of ip adress of the server? For example, if the ip adress is 123.45.67.89 I think the app should be running in 123.45.67.89:8080 but it does not run there. How can I access to the app running in container in remote server? P.S. I have not used nginx, should I use it? -
IntegrityError at /create_invoice NOT NULL constraint failed: invoiceAPI_invoice.buyer_id
I am trying to create a invoice which has two foreign keys seller, and buyer and one many to many to field for items. I have create serializer for seller, buyer, and items and nested serialzer for invoice and when I am creating the invoice I am getting the error IntegrityError at /create_invoice NOT NULL constraint failed: invoiceAPI_invoice.buyer_id. data which I have passed don't have the id in that. Because I don't want to pass id through JSON, could it is possible that Django create the primary key for all the models. This is my serializers.py file class SellerSerializer(serializers.ModelSerializer): class Meta: model = Seller fields = ('__all__') class BuyerSerializer(serializers.ModelSerializer): class Meta: model = Buyer fields = ('__all__') class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('name', 'price', 'quantity', 'tax') class InvoiceSerializer(serializers.ModelSerializer): seller = SellerSerializer(many=False, read_only=True) buyer = BuyerSerializer(many=False, read_only=True) items = ItemSerializer(many=True, read_only=True) class Meta: model = Invoice fields = ('seller', 'buyer', 'items', 'date') def create(self, validated_data): seller_data = validated_data.pop('seller') buyer_data = validated_data.pop('buyer') items_data = validated_data.pop('items') seller = Seller.objects.create(**seller_data) buyer = Buyer.objects.create(**buyer_data) items = [] for item_data in items_data: items.append(Item.objects.create(**item_data)) invoice = Invoice.objects.create(seller=seller, buyer = buyer, item=items) return invoice``` This is the models.py file. **models.py** ``` class Seller(models.Model): id … -
Why is my django core.serializers so slow
I have my a serializer from core.serializers in my django view. It does work, but it sometimes takes over 1 minute to show my results table. Any ideas how to get it faster? # views.py from django.core import serializers def search_institution(request): form = SearchInstitutionsForm() qs = Institution.objects.all() if request.method == "POST": form = SearchInstitutionsForm(request.POST) if form.is_valid(): cd = form.cleaned_data if cd['name']: qs = Institution.objects.filter(name__contains=cd['name']) print(f"Before requesting from db: {datetime.now()}") print(f"After requesting from db, before serializing: {datetime.now()}") context = { "result_data": SafeString(serializers.serialize("json", qs)), 'form': form } print(f"After serializing, before rendering: {datetime.now()}") return render(request, "landing/result_table.html", context) else: context = { "form": SearchInstitutionsForm } return render(request, "stakeholders/institution_form.html", context) -
Unable to implement Azure Adfs authentication in Django
I have been trying to use the authentication system of azure and for that I have followed the below link https://django-auth-adfs.readthedocs.io/en/latest/azure_ad_config_guide.html#step-1-register-a-backend-application but Im kinda of stuck and don't know where the problem lies . I keep getting the below error message. For any more information please ask in comment I will try to provide it. Any help or guidance will be a great help -
Need to Fetch specific foreign key object product from database in Django
Hi everyone I am new at Django and working on e-commerce site. I create a model name category and pass it to model shop by using foreign key. In Category model I have category Sale and i want to fetch all products that have category sale in my landing page and rest of us in shop page. Any one please help me how I do it? My model.py code is: class category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class shop(models.Model): s_id = models.AutoField(primary_key=True) s_name = models.CharField(max_length=50) s_category = models.ForeignKey(category, on_delete= models.CASCADE) s_artical_no = models.IntegerField(default=0) View.py: def index(request): prod = shop.objects.get(s_category = 4) params = {'prod': prod} return render(request, "main/index.html", params ) -
How Can I get related instance in formfield_for_dbfield method of TabularInline class of django admin?
Is it possible to get inline instance in formfield_for_dbfield method of TabularInline class in django admin? -
Can't use minutes from DateTimeField in django templates
M or m is month. How can i use |date so it gives me minutes. {{ client.time_of_receipt|date:"M, d h" }} -
Unable to get images in list in Django views.py context, Throws List AttributeError
I am using below code to get a list of all image and then display it: def index(request): data = cos.list_objects(Bucket='pixmedia') di = data['Contents'] endpoint="https://s3.us.cloud-object-storage.XXXXX.cloud/XXX/" #print(di) image_list=[] for key in di: print("Key is--->",key['Key']) res=key['Key'] res=endpoint + res print("Res is ---->",res) #context = { # 'image': res, #} image_list=image_list.append(res) print("Image List is",image_list) context = { {'image_list': image_list,} } return render(request, "index.html", context) But, i am getting below error on launching 127.0.0.1:8000: image_list=image_list.append(res) AttributeError: 'NoneType' object has no attribute 'append'. Please Help. -
How should I pass a raw query response to a Serializer class?
I am trying to fetch data using raw sql query but I am facing issues when I am trying to pass the raw sql response to the Serializer class. Serializer class User_Serializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' View class UserView(APIView): def get(self, request, emailId, format=None): with connection.cursor() as cursor: cursor.execute("SELECT * FROM users") resRow = cursor.fetchone() serializerResponse = User_Serializer(resRow) return Response(serializerResponse.data) I realise that the Serializer class cannot work with the ModelSerialzier class in this scenerio. How should I build my Serializer considering the fact that I need to post and save data to the concerned model using this Serializer class.