Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
not getting the data from Serializer
view.py @csrf_exempt def blog_list(request): if request.method == 'GET': post = Post.objects.all() serializer = BlogSerializer(post, many=True) return JsonResponse(serializer.data,safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = BlogSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) class BlogSerializer(serializers.Serializer): class Meta: model = Post fields = ['author', 'title', 'text', 'published_date'] class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title -
How can I dispay the data in django admin panel
I am creating an eCommerce website but I want to know how can I display a product_name or customer_name in the admin panel. The concept is that if a customer places an order that it will go to the admin panel. So the other details are displaying properly except product_name or customet_name. As shown in the below image: models.py class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) address = models.CharField(max_length=50, default='', blank=True) phone = models.CharField(max_length=50, default='', blank=True) price = models.IntegerField() date = models.DateField(default=datetime.datetime.today) status = models.BooleanField(default=False) admin.py class AdminOrders(admin.ModelAdmin): list_display = ['product', 'customer', 'quantity', 'address', 'phone', 'price', 'date', 'status'] -
How to add a list of numbers in a function?
I am trying to create a function which can add a list of numbers. I am using the for loop for that. Here is the code: I don't know where I am wrong but it gives me error. def add(amounts): for amount in amounts: total = add(amount) x= print(total) return x amounts= [1, 3, 5, 7, 8 ,9] add(amounts) here is error PS C:\Users\Lenovo\Documents\PP> & C:/Users/Lenovo/AppData/Local/Programs/Python/Python39/python.exe "c:/Users/Lenovo/Documents/PP/Advance python/class_method.py" Traceback (most recent call last): File "c:\Users\Lenovo\Documents\PP\Advance python\class_method.py", line 8, in <module> add(amounts) File "c:\Users\Lenovo\Documents\PP\Advance python\class_method.py", line 3, in add total = add(amount) File "c:\Users\Lenovo\Documents\PP\Advance python\class_method.py", line 2, in add for amount in amounts: TypeError: 'int' object is not iterable PS C:\Users\Lenovo\Documents\PP> -
Django Rest Framework: optimize nester serializers performance
I have problem with my endpoint performance which returns around 40 items and response takes around 17 seconds. I have model: class GameTask(models.Model): name= models.CharField() description = RichTextUploadingField() ... and another model like that: class TaskLevel(models.Model): master_task = models.ForeignKey(GameTask, related_name="sub_levels", on_delete-models.CASCADE) sub_tasks = models.ManyToManyField(GameTask, related_name="master_levels") ... So basicly I can have "normal" tasks, but when I create TaskLevel object I can add master_task as a task which gonna fasten other tasks added to sub_tasks field. My serializers look like: class TaskBaseSerializer(serializers.ModelSerializer): fields created by serializers.SerializerMethodField() ... class TaskLevelSerializer(serializers.ModelSerializer): sub_tasks = serializers.SerializerMethodField() class Meta: model = TaskLevel def get_sub_tasks(self, obj: TaskLevel): sub_tasks = get_sub_tasks(level=obj, user=self.context["request"].user) # method from other module return TaskBaseSerializer(sub_tasks, many=True, context=self.context).data class TaskSerializer(TaskBaseSerializer): levels_config = serializers.SerializerMethodField() class Meta: model = GameTask def get_levels_config(self, obj: GameTask): if is_mastertask(obj): return dict( sub_levels=TaskLevelSerializer( obj.sub_levels.all().order_by("number"), many=True, context=self.context ).data, progress=get_progress( master_task=obj, user=self.context["request"].user ), ) return None When I tried to measure time it turned out that get_levels_config method takes around 0.25 seconds for one multilevel-task (which contain 7 subtasks). Is there any way to improve this performance? If any more detailed methods are needed I will add them -
How to read a log file?
So I am new Django and using Django documentation regarding logging, I found how to get a log file, so I followed the steps and got my first log file. Now what? How do I read it?, I opened it in notepad to read but how to decode like what to look in those files? -
Django Many-to-Many query not returning related records
so this is my job records model that has a many to many relationship with employees model, but when I try to get the job records using {{ employee.jobs }} in my template it returns nothing I can successfully get the employee info, but not the jobs, it's as if they're not related (which they are I checked from database) Jobs Model class Jobs(models.Model): employee_id = models.ManyToManyField(Employee) department_id = models.ForeignKey(Departments,null=True,on_delete=models.SET_NULL) job_title_id = models.ManyToManyField(Job_titles) start_date = models.DateField(null=True) end_date = models.DateField(null=True) salary = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) primary = models.BooleanField(null=True) hire_date = models.DateField(null=True,blank=True) pay_schedule = models.ForeignKey(Pay_schedule,max_length=100,null=True,blank=True,on_delete=models.SET_NULL) pay_type = models.ForeignKey(Pay_type,max_length=100,null=True,blank=True,on_delete=models.SET_NULL) division = models.ForeignKey(Divisions,max_length=100,null=True,blank=True,on_delete=models.SET_NULL) My View def JobView(request,username): if request.user.is_authenticated: try: employee = Employee.objects.get(user__username=username) return render(request,'job.html',context={'employee':employee}) except: pass also , when I directly try to filter job records using jobs = Jobs.objects.filter(employee__id=1) I get a this : The view Employees.views.JobView didn't return an HttpResponse object. It returned None instead. -
Django, DRF: How to cache Pagination count
I think the official paginator uses @cached_property like this, but Even though the cache is used, the DB is accessed every time to get the COUNT. which can be a problem if the COUNT query is slow. Is there a way to cache the counts for a certain amount of time? class Paginator: ... @cached_property def count(self): """Return the total number of objects, across all pages.""" c = getattr(self.object_list, "count", None) if callable(c) and not inspect.isbuiltin(c) and method_has_no_args(c): return c() return len(self.object_list) ...