Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I define a django model's field default value to be another field value?
In my model I have these two fields: start_bid = models.IntegerField(default=0) max_bid = models.IntegerField(default="the start_bid value") The start_bid will be added by the user once through Django ModelForm. And the max_bid may change and may not. So I need the first value of 'max_bid' to be the start_bid value entered by the user, then if it changes it will be updated. In brief, I need the initial value of max_bid to be equal to the start_bid! Any suggestions? -
Displaying number of messages sent by each category of users
This is what message_user_id contains: message_user_id = Message.objects.all() This is my context dictionary in admin.py: 'msg' : message_user_id, This is my Message class in models.py: class Message(models.Model): message_text = fields.EncryptedTextField(blank=True, null=True) conversation_id = models.ForeignKey(Conversation, on_delete=models.CASCADE) origin_user = models.ForeignKey(UserInfo, on_delete=models.CASCADE, blank=False, default=None) timestamp = models.DateTimeField(default=datetime.now, blank=True) This is UserInfo class: class UserInfo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) is_buyer = models.BooleanField(default=False) is_seller = models.BooleanField(default=False) is_professional = models.BooleanField(default=False) There are different roles for users that they can choose from while sign up. That information stays in UserInfo table which I'm referencing to as a foreign key in origin_user field in Message class. origin_user in Message contains the same information as id in UserInfo. I want to display the number of messages sent by each category of users. How do I achieve this?. -
How to store all IP addresses that related to user in django? [closed]
I want to store all IP addresses of each user in the database, I want each time to keep the IP before the change and append the next one to the same field, for exemple I want a list that take all IP from the creationg of Profile. I collect IP adresses using this middelware from dashboard.models import Profile from django.utils.deprecation import MiddlewareMixin class SaveIpAddressMiddleware(MiddlewareMixin): def process_request(self, request): # sourcery skip: use-named-expression x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') if request.user.is_authenticated: profile = Profile.objects.get(user=request.user) profile.ip_address = ip profile.save() model.py from django.db import models from django.contrib.auth.models import User from .formatChecker import ContentTypeRestrictedFileField # Extending User Model Using a One-To-One Link class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True, max_length=150) ip_address = models.GenericIPAddressField(null=True, max_length=30) avatar = ContentTypeRestrictedFileField(max_upload_size=10485760, null=True, verbose_name="",default='default.jpg', blank= True, content_types=['image/png', 'image/jpeg']) def __str__(self): return self.user.username -
How to access array of files in request with Django Rest Framework
I'm sending a request from a React frontend to Python backend, in this request i'm sending a FormData() with an array of images, like this: const data = new FormData() images.forEach(image => { data.append('images', image.arquivo) }) data.append('product', JSON.stringify(product)) return recuperarInstanciaAxios(true).post(`${recuperarUrlBackend()}/products/`, data) But I'm not being able to access this array of pictures in Python. Through PyCharm evaluate, request.FILES shows me a dict with an array 'images' within. But when I do request.FILES['images'] it returns me a single file. This is the python code: def create(self, request): try: productData = json.loads(request.data['product']) serializer = ProductSerializer(data=productData ) if serializer.is_valid(): product = serializer.save() files = request.FILES['images'] for image in files: product_image= {'image': image, 'product': product.id} image_serializer = ProductImage(data=product_image) if image_serializer .is_valid(): image_serializer .save() else: raise IntegrityError('Error :' + serializer.errors.__str__()) return Response(serializer.data, status=status.HTTP_201_CREATED) else: raise IntegrityError('Error:' + serializer.errors.__str__()) except IntegrityError as exc: print(exc) return Response(exc.__str__(), status.HTTP_412_PRECONDITION_FAILED) It gives me an error because files is not iterable. Am I accessing the array in a wrong way? -
Django how to prevent brute force attack by showing captcha in login page after few failed attempt?
I know there have few package available like django-defender, django-axes etc for prevent brute force attack. I am thinking to prevent brute force attack using Django session or somethings like this without help of any package. I want to count failed login attempt in my views then it will show the captcha after number of failed login attempts. So it will be simple two step: step1) it will count the failed login attempts. step2) It will show the captcha after number of failed login attempts here is my views.py : def login_view(request): if request.method == 'POST': username = request.POST.get('username') password =request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.add_message(request, messages.INFO,'Login Sucessfull') else: messages.info(request, "wrong username or password") -
Google OAuth RefreshError even with Refresh Token present in the Django app
My app running on Django with Django allauth allows signup/login only via Google OAuth. Therefore when a user is registered, his social oauth details are saved to All-auth Social Accounts model and the token data saved in Social Application Tokens model. We want the users to be logged-in as long as possible, without granting/revoking access regularly. Question 1: The default expiry is set as 1 hour from the registration time. How can I extend this programmatically and for how long (can it be never-expire?) Currently, a user logged in at 5:00 and I get the following data from credentials.to_json(): { "token": "ya29.A0ARrdaM8YXPM35RXPv7UK-pXLZvWG49T-MgCZ5wMse2ADMXOZJOWFJKMaq1PkobADLptM5YX5mnrliS2yCCESqCk0NTaZJkfe6inK94j6WQMFZWIT_xRyBTOX4W3dUEiuLhHFpQcD5vS-x_Y22pUzxwgI23pp", "refresh_token": "1//0gYC8oucHhTBVCgYIARAAGBASNwF-L9IrCG7c5IJCBMVznUrytGEFsJbsObAFvmNBoQbHHGA1KESyBWgmudEVogbes8ski87q_5g", "client_id": "blablabla.apps.googleusercontent.com", "client_secret": "xyzsecret"} No other data is returned. At 6:05, the credentials.to_json() is exactly the SAME AS ABOVE. But to fetch any Google/Youtube API data, I get the following error in server logs: google.auth.exceptions.RefreshError: The credentials do not contain the necessary fields need to refresh the access token. Question 02: When there's a Refresh Token available already, why the error? As per the docs, it refreshes the token automatically few minutes before the expiry. What am I missing? I already had "access_type": "offline" in the providers settings. I also tried adding "prompt": "consent", but no … -
How do I connect to any network printer from server and give multiple print job?
I will try to describe my problem as story. I have one computer in my house and that is connected to internet. My uncle has one printer which is on my Uncle's house (100 miles away from our house). That is also connected to internet. I have one Django app which is hosted on AWS. I want to click on print button on hosted Django app. Which will print 100 pdfs on my uncle's printer automatically.(Assume uncle's printer is connected to internet) I have IP address of my uncle's printer. How can I print 100 pdfs from my uncle's printer from hosted django app? -
Djnago : AttributeError: module 'django.views.generic' has no attribute 'Detail'
where can I import the detail attribute from? views.py: from django.shortcuts import render from django.views import generic from . import models class Index(generic.TemplateView): template_name='catalog/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['num_books'] = models.Book.objects.all().count() context['num_instances'] = models.BookInstance.objects.all().count() context['num_instances_available'] = models.BookInstance.objects.filter(status__exact='a').count() context['num_authors'] = models.Author.objects.count() return context class BookListView(generic.ListView): model = models.Book template_name = 'catalog/book_list.html' class BookDetialView(generic.Detail.View): model= models.Book template_name = 'catalog/book_detail.html' urls.py from django.urls import include, path, re_path from . import views from django.views.generic import TemplateView app_name='catalog' urlpatterns = [ path(r'', views.Index.as_view(), name='index'), re_path(r'^$', views.Index.as_view(), name='index') ] urlpatterns = [ path(r'^$', views.index, name='index'), path(r'^books/$', views.BookListView.as_view(), name='books'), path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'), ] but the result: class BookDetialView(generic.Detail.View): AttributeError: module 'django.views.generic' has no attribute 'Detail' -
well-known redirects do not work for www only without
I am trying to add my SSL certificates to my Django website and I cannot solve the problem with domain validation. I have added the well-known information directly in Django. Therefore, my configuration is: in core/urls.py I have: urlpatterns = [ re_path(r'^\.well-known/', include('apps.app.urls')), ... ] in apps.app.urls I have: urlpatterns = [ path('acme-challenge/xxxxxxx', certs_no_www), path('acme-challenge/yyyyyyy', certs_www), .... ] in apps.app.views I have: def certs_no_www(request): return HttpResponse("xxxxxxx.aaaaa") def certs_www(request): return HttpResponse("yyyyyyy.aaaaa") In my nginx (/etc/nginx/sites-available/) configuration file I have: server { listen 80; server_name www.xxxx.com xxxx.com A.B.C.D; location = /favicon.ico { access_log off; log_not_found off; } location /staticfiles/ { autoindex on; root /opt/xxxx/core; } location / { include proxy_params; proxy_pass http://unix:/opt/xxxx/xxxx.sock; } } The problem is that if I call the website: xxxx.com/.well-known/acme-challenge/xxxxxxx works but if I call www.xxxx.com/.well-known/acme-challenge/yyyyyyy is not working Where it could be the problem? I have to validate both, with and without www. -
how to use a django variable in an <a> tag's href?
I want to create a list of entries in which each entry is linked to its page like this: wiki/entry-title. I'm using a for loop to add <li>s to HTML. here's the code: <ul> {% for entry in entries %} <a href="{% %}"><li>{{ entry }}</li></a> {% endfor %} </ul> what should I type in href to link the <li> to wiki/entry? -
Can I use select_related Django QuerySet method in reverse relationships?
class A(Model): pass class B(Model): a = ForeignKey(A) B.objects.select_related("a") # this works A.objects.select_related("b") # this doesn't How do I make the second line work? Are there any ways to do the same thing in some other ways? -
How can delete User in Django and DRF using serializers and generic views
I am trying to make user CRUD functions, I have made other functions but can't figure out the way to delete the user using the API, It will be also great if you can provide a review on the code, am I doing it correctly, and in safe way. Here are the serializers I am using: serializers.py from .models import User class UserSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=128, min_length=8, write_only=True ) class Meta: model = User fields = ('email', 'password', 'first_name', 'last_name') extra_kwargs = { 'password': {'write_only': True}, 'first_name': {'required': True}, 'last_name': {'required': True}, } def create(self, validated_data): user = User( email = validated_data['email'], first_name = validated_data['first_name'], last_name = validated_data['last_name'] ) user.set_password(validated_data['password']) user.save() return user class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) class Meta: model = User fields = ('first_name', 'last_name', 'email') extra_kwargs = { 'first_name': {'required': True}, 'last_name': {'required': True}, } def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value def update(self, instance, validated_data): user = self.context['request'].user if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You dont have permission for this user."}) instance.first_name = validated_data['first_name'] instance.last_name = validated_data['last_name'] instance.email = validated_data['email'] instance.save() return instance views.py from rest_framework import generics from rest_framework.views import APIView from rest_framework.response … -
Django vCenter Server REST APIs check if Vcsa is down
I have created an application in django 2.2 that communicates with the vCenter Server REST APIs. Where on it, I can make various requests. On the vCenter I have two ESX servers 10.122.151.60 and 10.122.151.50 where there are several virtual machines. I can communicate with them through my django application. The problem is when the first server does not respond, my application does not understand and so the second one also does not work. The requests don't go through because the first server doesn't answer. I have created a function that checks all the Vcsa and sends an email if one of the vcsa does not respond. The problem is if the first server is down et the second running it's only gonna show me the status of the one working and not the other. I don't know if I made myself understood but read carefully the comments and import of each file. # vm.py from vmware.views.tools import check_vcsa_status def vm_vcsa_chech_status(request): """ A function used to generate a response message about the state of one or several Vcsa and send an email afterwards. :param request:Contains information about current user. :return:Returns a Http response with 1 argument: 1.'mylist' Contains a list … -
ValueError: Field 'id' expected a number but got 'undefined'. in python3
here when i am opening an edit page of an item i am getting this issue Here is my models.py class Category(models.Model): category_name = models.CharField(max_length=20) client = models.ForeignKey("core.Client",on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) is_deleted = models.BooleanField(default=False, help_text="Deleted Category will not display in the UI.") class Meta: ordering = ['-category_name'] def __str__(self): return self.category_name class SubCategory(models.Model): category = models.ForeignKey(Category,on_delete=models.CASCADE) sub_category_name = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) client = models.ForeignKey("core.Client",on_delete=models.CASCADE) modified = models.DateTimeField(auto_now=True) is_deleted = models.BooleanField(default=False, help_text="Deleted SubCategory will not display in the UI.") class Meta: ordering = ['-sub_category_name'] def __str__(self): return self.sub_category_name here i is my script written in the template //category $('#id_category').change(function() { var q = $('#id_category').val() if (q != ''){ $('#id_sub_category').show(); $.ajax({ url: '/admin/ajaxsubcategory/'+ q + '/', dataType: 'json', type: 'GET', // This is query string i.e. country_id=123 //data: {role_type : $('#id_category').val()}, success: function(data) { $('#id_sub_category').html('<option value="">Please Select</option>'); // clear the current elements in select box for (row in data) { //alert(row); $('#id_sub_category').append($('<option></option>').attr('value', row).text(data[row])); } }, error: function(jqXHR, textStatus, errorThrown) { alert(errorThrown); } }); } else{ $.ajax({ url: '/admin/ajaxsubcategory/'+ 0 + '/', dataType: 'json', type: 'GET', // This is query string i.e. country_id=123 //data: {role_type : parseInt('all')}, success: function(data) { $('#id_sub_category').html('<option value="">Please Select</option>');// clear the current elements in select … -
How to add this multiple images into the slider please help me to figure this out
i created social media website and i code for upload multiple images but i don't know to set it in slider please hell me. This is my code: {% if post.image.count > 0 %} <div class="row"> {% for img in post.image.all %} <div class="col-md-6 col-xs-12"> <img src="{{ img.image.url }}" alt="" class="post-image"> </div> {% endfor %} </div> {% endif %} -
making some enhancement on django-survey-and-report library
I need making some survey form for my django website and i'm using django-survey-and-report. but there is problem. I want to let Users can select "other" in radio box, at which point an inline text-type input will appear where they can put a custom text. but I don't know how to do that. -
How to access the value of constant in settings.py
I'd like ask about how to access the value of a constant declared in setting.py the following way: PAYMENT_VARIANTS = { 'redsys': ('payments_redsys.RedsysProvider', { 'merchant_code': '123456789', 'terminal': '1', 'shared_secret': 'aaaaaaaaaaaaaaaaaaaaaaaaaa', 'currency': '978', }) } I can import: from django.conf import settings But, how I can access the value of field 'currency' or other at this level. Thanks, regards, -
Can not get textfield value fetched from MySQL in javascript
I created a model in django like below. class MyDB(models.Model): pub_date = models.DateTimeField(_("Date added"),editable=True, auto_now_add=False) title = models.CharField(max_length=256,blank=True,null=True) text = models.TextField(_("Text")) Then I got the model and mapped into Frontend. in views.py file context['mydb'] = MyDB.objects.all() in HTML file let plots = []; {% for d in mydb %} var id = '{{ d.id }}'; var title = '{{ d.title }}'; var text = '{{ d.text }}'; console.log(text) {% endfor %} When the text contains 'enter' in string. it raise error. -
How can I get input from Django website using Post Method ( Form Processing )?
I am currently making a Django website. In that website I accept data from the user in date format and take that date, search through the data base of the website and get the value attached to that specific date. How do I get Post Method to work for my specific case. Views.py : from django.shortcuts import render from apple.models import predictions # Create your views here. def home_view(request): pre = predictions.objects.filter(date='2020-01-15') return render(request, 'homepage.html', {'prediction': pre}) Models.py : from django.db import models # Create your models here. class predictions(models.Model): date = models.TextField(max_length=10) predicted_price = models.DecimalField(decimal_places=5, max_digits=64) def __str__(self): return "%s %s" % (self.date, self.predicted_price) -
How to make a model field using CurrentUserField() non editable in django
I have a model that will store the currently loged in user who is uploading the data in that model. I made the field non editable earlier but did not know how to store the currently loged in user as the data is being uploaded from the admin pannel. So a user of SO suggested me to use CurrentUserField() to store the user which is working fine. But I want to make the field non eidtable too. This is the code that I am using models.py from django_currentuser.middleware import ( get_current_user, get_current_authenticated_user) from django_currentuser.db.models import CurrentUserField uploaded_by = CurrentUserField() I do not know how to make this field non-editable so that it not displayed at to the user. -
Testcase returning 401 even with force_autenthicate()
I'm trying to test a view of my project with the following TestCase: def test_jump_story(self): c = APIClient() user = User.objects.get(username='test1') c.login(username=user.username, password='123') room_id = PokerRoom.objects.get(name='planning').id room_index = PokerRoom.objects.get(name='planning').index request = c.post(reverse('jumpstory', kwargs={'pk': room_id, 'index': room_index})) c.force_authenticate(user=user) self.assertEqual(200,request.status_code) but it returns this <Response status_code=401, "application/json"> even using force_authenticate. The view that i'm testing: class jumpStory(APIView): permission_classes = [IsAuthenticated] def post(self, request, pk, index): data= self.request.data index = self.kwargs['index'] pk = self.kwargs['pk'] if PokerRoom.objects.filter(id=pk).exists(): body = {'index':index} message_socket("JUMP_STORY", pk, body) return Response({'success':"JUMP_STORY"}, status=200) else: return Response({'error':'message not sended'}, status=400) What is wrong with my test? -
'User' object has no attribute 'staffUser'
I customized the User Model Using Django One To One Field My models.py class StaffUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.ForeignKey(Dept, on_delete=models.RESTRICT) def __str__(self): return self.user.username When uploading a form, i want to get the department of the user 'My Views.py' def FileUploadForm(request, pk): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): form.save(commit=False) u = User.objects.get(username=request.user) form.instance.username = u folder = Folder.objects.get(id=pk) department = u.staffUser.department form.save() messages.success(request, f'File Successfully uploaded to {folder} in {department}!') return redirect('home') else: form = UploadFileForm() context = {'pk':pk, 'form':form} return render(request, "pages/fileup_form.html", context) But it gives error AttributeError at /file/new/1 'User' object has no attribute 'staffUser' Please guys i need help -
Populate a database with python and Django efficiently
We are trying to populate a database with Python and Django with random numbers, but we have a lot of rows to go through, and it takes like 20 minutes to carry out that task. This is our code. We have 210000 rows to go through def populate(request): all_accounts = Account.objects.all() count = 0 for account in all_accounts: account.avg_deal_size = round(random.randint(10, 200000), 2) account.save() print(f"Counter of accounts: {count}") count += 1 Thank you! -
Django Nextjs post method "Unhandled Runtime Error"
I am currently building my first project on Django + Nextjs, but I have a problem when I try to create an object from the front. I have a form that allows me to create a "post" when I submit it. Everything works fine in the backend, I can see my new posts in my /admin dashboard. However, on the front end I get an error : "Unhandled Runtime Error" My front code where I believe the error comes from : const CreationForm = () => { const router = useRouter(); const [creator, setCreator] = useState('Anonymous Creator'); const [slug, setSlug] = useState(''); const [title, setTitle] = useState(''); const [photo_main, setPhoto_main] = useState(null); const [description, setDescription] = useState(''); const onSlugChange = e => setSlug(e.target.value); const onTitleChange = e => setTitle(e.target.value); const onFileChange = e => setPhoto_main(e.target.files[0]); const onDescriptionChange = e => setDescription(e.target.value); const [loading, setLoading] = useState(false); const handleSubmit = async e => { e.preventDefault(); setLoading(true); const config = { headers: { 'Accept': 'application/json', 'Content-Type': 'multipart/form-data', } }; const formData = new FormData(); formData.append('title', title); formData.append('slug', slug); formData.append('creator', 'Anonymous Creator'); formData.append('description', description); formData.append('photo_main', photo_main); const body = formData; try { const res = await axios.post('http://localhost:8000/api/posts/create', body, config); if (res.status === 201) … -
How to filter foreingkey choices in Django Admin?
I have 3 simple models: class Department(models.Model): name = models.CharField( max_length=30 ) class Company(models.Model): name = models.CharField( max_length=30 ) department = models.ManyToManyField(Department) class Employee(models.Model): name = models.CharField( max_length=30 ) company = models.ForeignKey(Company, on_delete=SET_NULL, null=True, blank=True, ) department = models.ForeignKey(to=Department, on_delete=DO_NOTHING) I want to restrict department options in Django Admin panel to those which are related to Employee's company. For example: Departments: HR, DevOpps, WebApps, TVApps Companies: Company_1 with departments - HR, DevOpps, WebApp Company_2 with departments - HR, DevOpps, TVApps Add Employee: if Company_1 is selected, the options for department to be: HR, DevOpps, WebApp if Company_2 is selected, the options for department to be: HR, DevOpps, TVApps