Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pagination in Django Admin with Custom List Filters
I have a proxy model and admin section where I am implementing a custom multi select filter. The results are coming correctly. How ever, pagination is not working with this filter. http://127.0.0.1:8000/users/?taggroup=1&taggroup=2 When I try to click on page 2 the url turns to : http://127.0.0.1:8000/users/?page=2&taggroup=2 But the expected result is : http://127.0.0.1:8000/users/?page=2&taggroup=1&taggroup=2 I tried overriding the change list using [https://stackoverflow.com/questions/62960518/overriding-django-admin-pagination-along-with-url-parameters][1] But now the pagination is like below when I try navigating from page 1 to page 2 and also the pagination is starting from 0 and not 1: http://127.0.0.1:8000/users/?page=2&page=1 Below is the code that I have tried: @register.inclusion_tag('admin/custom_pagination.html', takes_context=True) def custom_pagination(context, cl): pagination = admin_list.pagination(cl) if 'group_id' in context: pagination['params'] = (('taggroup', context['group_id']),) return pagination change_list_template = 'admin/users_changelist.html' def changelist_view(self, request, extra_context=""): response = super(PartnerUsersAdmin, self).changelist_view( request, extra_context) group_id = request.GET.urlencode() if group_id: extra_context = { 'group_id': str(group_id), } response.context_data.update(extra_context) return TemplateResponse(request, "admin/partner_users_changelist.html", response.context_data) #custom_pagination.html {% load admin_list %} {% load i18n %} {% load content_extras %} <p class="paginator"> {% if pagination_required %} {% for i in page_range %} <a href="?p={{ i }}{% for key, value in params %}{% if key != 'p' %}&{{ value }}{% endif %}{% endfor %}"> {{i}}</a> {% endfor %} {% endif %} {{ cl.result_count … -
How to get user object from Django DRF when logged in with TemplateView?
I am begginer in Djnago and logged in to my app with this code: class LoginHandler(TemplateView): def get(self, request, *args, **kwargs): user = authenticate(request, email='jaxen@gmail.com', password='123456') login(request, user) return render(request, "login.html", context={}) But i need to detect logged in user in other app that use DRF. I don't know how fetch the user. I tried this code but not worked: class OtherAppHandler(APIView): def post(self, request): print(f"user: {request.user}") ... Thank you. -
How can I get the rows from the PostgreSQL with specific value. Django
How can I get the rows from the PostgreSQL with specific value? I have this table with columns: id | accountid | dictdata | date | Inside the dictdata column contains a bunch of dictionary data. in my models.py class charts(models.Model): id = models.AutoField(primary_key=True) accoundid= models.IntegerField(default=None,blank=True) dictdata= models.JSONField(default=None,null=True, blank=True) date = models.DateTimeField(auto_now=True) class Meta: db_table = "charts" in my python file data = list(charts.objects.values('dictdata ')) //all dictionary data print(data) Example of print(data): [{'dictdata': {'select': 'bar', 'title': 'some title'}}, {'dictdata': {'select': 'line', 'title': 'some title'}}, {'dictdata': {'select': 'pie', 'title': 'some title'}}] how can I get the rows that contains a specific 'select' value? for example I want to get all the rows with 'bar' {'dictdata': {'select': 'bar', 'title': 'some title'}} -
Why do I get this error "HttpRequest.accepts() missing 1 required positional argument: 'media_type'"?
The source code originally had Httpsrequest.is_ajax which after some reading I realised was depricated. So I changed it to Httpsrequest.accepts and it now throws an error: HttpRequest.accepts() missing 1 required positional argument: 'media_type' How can I solve or bypass this error ? def home_view(request): published_jobs = Job.objects.filter(is_published=True).order_by('-timestamp') jobs = published_jobs.filter(is_closed=False) total_candidates = User.objects.filter(role='employee').count() total_companies = User.objects.filter(role='employer').count() paginator = Paginator(jobs, 3) page_number = request.GET.get('page', None) page_obj = paginator.get_page(page_number) if request.accepts(): job_lists = [] job_objects_list = page_obj.object_list.values() for job_list in job_objects_list: job_lists.append(job_list) return render(request, 'jobapp/index.html', context) -
I am trying to install pillow module on my python django web.. but is not installing in cpnael linux server
Collecting Pillow==2 Downloading Pillow-2.0.0.zip (1.4 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.4/1.4 MB 8.4 MB/s eta 0:00:00 Preparing metadata (setup.py) ... done Building wheels for collected packages: Pillow Building wheel for Pillow (setup.py) ... error error: subprocess-exited-with-error -
Using Django Tenants with Channels - AppRegistryNotReady
We are trying to use django channels to implement websockets in a multi-tenant django application. I have followed the tutorial page in the django channels documentation and also applied the instructions found in the deploying page. However, I am seeing the django.core.exceptions.AppRegistryNotReady error when running pytest cases or even when running a simple "python manage.py check". django@fa5404e77654:/usr/src/app$ python manage.py check Traceback (most recent call last): File "manage.py", line 36, in <module> main() File "manage.py", line 32, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/lib/python3.8/site-packages/channels/apps.py", line 4, in <module> import daphne.server File "/usr/local/lib/python3.8/site-packages/daphne/server.py", line 7, in <module> twisted_loop = asyncio.new_event_loop() File "/usr/local/lib/python3.8/asyncio/events.py", line 758, in new_event_loop return get_event_loop_policy().new_event_loop() File "/usr/local/lib/python3.8/asyncio/events.py", line 656, in … -
How to make text fit in div?
I'm styling a link to make it look like the photo. The problem is in the second div, text over div. In the scope of the question is an example of the photo of how it is and how it should be. (I left the text color in black to illustrate the problem) How it should be var div_color = document.getElementsByClassName('div-categoria'); console.log div_color[0].style.backgroundColor = '#7d35ed'; div_color[1].style.backgroundColor = '#e93f3f'; div_color[2].style.backgroundColor = '#e4bf2a'; .categoria{ margin: 2.5rem 0; } .div-categoria{ display: inline-flex; height: 120px; width: 120px; border-radius: 10px; transition: transform .2s; margin-right: 20px; position: relative } .div-categoria:hover{ transform: scale(1.10); } .categoria a{ text-decoration: none; color: white; } .div-categoria p { margin: 0; color: black; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); text-transform: uppercase; font-size: 25px; } <div class="categoria"> <a href="#link"><div class="div-categoria"><p>Comida</p></div></a> <a href="#link"><div class="div-categoria"><p>Bebidas Alcoolicas</p></div></a> <a href="#link"><div class="div-categoria"><p>Bebidas</p></div></a> </div> -
Django HttpResponseRedirect() function
flag = 0 folder_id = 0 if FolderEntries.objects.filter(entry = entry_id).exists(): print("=======================yes in folder") flag = 1 folder_object = FolderEntries.objects.get(entry = entry_id) folder_entries_object = model_to_dict(folder_object) print("-------------------------", folder_entries_object) folder_id = folder_entries_object['folder'] else: flag = 0 if flag == 1: returnHttpResponseRedirect('folder/'+str(folder_id)+'/') else: if request.session.get('HTTP_REFERER', None): HTTP_REFERER = request.session.get('HTTP_REFERER') del request.session['HTTP_REFERER'] return HttpResponseRedirect(HTTP_REFERER) return HttpResponseRedirect('editentry/'+str(entry_id)) In this case if flag = 1, this is redirecting me to 2 urls these are:- http://127.0.0.1:8000/admin/form-entries/edit-entry/folder/174/ url "folder/174" is url that i need. But i am getting unwanted url "admin/form-entries/edit-entry/" What i am doing wrong please guide me. I am a entry level django developer Thanks and Regards Abhishek -
Assign custom role to user
I am a beginner in django and trying to create a web application for my task. I am trying to assign a roles to every to user. But i have an error. enter image description here My model class Rol(Group): state = models.BooleanField(default=True) description = models.CharField(max_length=200) permission = models.ManyToManyField(Permission) def __str__ (self): return '{}'.format(self.state,self.description, self.permission) In this part i don't have any problem the permission is asigned to rol But here My model: class User(AbstractUser): state = models.BooleanField(default=True) roles = models.ManyToManyField(Rol) def __str__ (self): return '{}'.format(self.username,self.state,self.roles) My form: class UserForm(UserCreationForm): username = forms.CharField(label="User",widget=forms.TextInput(attrs= {"class":"form-control"})) password1 = forms.PasswordInput() password2 = forms.PasswordInput() state = forms.CheckboxInput() roles =forms.ModelMultipleChoiceField(label="Roles",queryset=Group.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = User fields = [ "username", "password1", "password2", "activo", "roles" ] In roles lists the roles created but not assigned to the user at the time of saving, it shows me an error: Field 'id' expected a number but got <Group: standart>. The above exception (int() argument must be a string, a bytes-like object or a real number, not 'Group') was the direct cause of the following exception: And highlight this line form.save_m2m() My view def create_user(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form2=form.save(commit=False) form2.save() form.save_m2m() return redirect('list_user') … -
unwanted duplicate objects in Javascript recursion
I'm trying to create a non-profit social media site using Django. Part of the site is nestable comments. However, when I create a comment it gets duplicated by the factor of its depth. so at a depth of one one comment is rendered, at a depth of two two comments are rendered, and at three three. I'm rendering the comments with javascript: function showComments(comment, parent_id, user_id) { // ... (the code of how to render the comment) ... for (subment of comment.subments) { showComments(subment, comment.comment.id, user_id) } } fetch(`/get_comments/${post}`) .then(response => response.json()) .then(data => { results = data.data console.log(results) for (comment of results[0]) { showComments(comment, 0, results[1]) } }) The fetched data doesn't contain any duplicates. How do I recursively render the data without duplicating it? Thank you -
403 net::ERR_ABORTED 403 (Forbidden) error in static files
Please I have been stocked for days now trying to clear the error in my browser console (403 net::ERR_ABORTED 403 (Forbidden)) and my static files is not been severed. Nginx Ubuntu -
django how to Pass an id from a template to a view
I want to update an item and I have this views.py def update(request,cl_itemid): if request.method == "POST": cursor = connection.cursor() resolve_item = get_object_or_404(Clearanceinsert, pk=cl_itemid) cursor.execute("select resolve_clearance_item('"+resolve_item+"')") return render(request, 'clearance/index.html') else: return render(request, 'clearance/index.html') when I clicked an item, the data goes to my def update then run this postgres function let's say I have this list of items test001 | update test002 | update here's my template <table style="width:100%"> <tr> <th>cl_itemid</th> <th colspan="2">Actions:</th> </tr> {%for data in data%} <tr> <td>{{data.cl_itemid}}</td> <td><a href="{% url 'update' data.cl_itemid %}">Update</a></td> </tr> {%endfor%} </table> if this is not possible then maybe someone can recommend an alternative solution -
Updating database based on previous csv file uploads - delete - create - or update Python/Dajngo
Please need help with the following I am trying to update database in comparison to previous uploaded csv file. I need to update all fields except the vin if it changes (vin is the unique value), delete the item if it is no longer in the csv file and create one if one is new vin. stock_no make model trim miles 12345789098765432 4535 honda civic lx 89000 j4j4jj49098765432 3453 toyota corolla DX 54555 12345345438765432 6254 ford mustang es 101299 When I change any value and the csv is uploaded it makes a duplicate: def upload_file__view(request): form = form(request.POST or None, request.FILES or None) company = Comp_info.objects.last() if form.is_valid(): form.save() obj = c.objects.get(activated=False) with open(obj.file_name.path, 'r+') as f: reader = c.reader(f) for i, row in enumerate(reader): if i==0: pass else: # row = "".join(row) # row = row.replace(",", " ") # row = row.split() print(row) print(type(row)) vin = row[0].upper() condition = row[1].replace("U", "Used").replace("N", "New") stock_no = row[2] year = int(row[5]) make = row[3] model = row[4] trim = row[6] mileage = row[8] mpg_city = row[18] mpg_hwy = row[19] engine = row[9] transmission = row[12] fuel_type = row[11] vehicle_type = row[7] drive_type = row[20].replace("4X2", "2WD").replace("4X4", "4WD") exterior_color = row[15] interior_color = row[16] … -
Export Excel from Django with verbose names
I am using DjangoObjectActions from django_object_actions package that adds an action in Django Admin to export my Querys model to excel. class QueryAdmin(DjangoObjectActions, admin.ModelAdmin): def export_to_xls(self, request, obj): query_record = Query.objects.all().values('profile__full_name') return excel.make_response_from_records( query_record, 'xlsx', file_name="Querys" ) list_display = ('weight', 'height') export_to_xls.label = "Export to Excel" changelist_actions = ('export_to_xls',) I could not find how to export my table with columns' verbose names. I found how to just get the verbose names of columns but is there a way to export them to excel? I need it because verbose names are in different language and that would be really great to show columns titles like that. Also I was using charfields with choices in my models. If there is a way I could export values from choices (not only keys), that'd be very good. Would be grateful for any help! -
How do you immediately redirect to another view once a view is rendered in Django?
I have a view like below. class ConfirmationPageView(generic.TemplateView): template_name = "confirmation.html" What I want is to immediately move onto the below view once the ConfirmationPageView is loaded (which means its templates were loaded too). class SecondPageView(generic.TemplateView): template_name = "second.html" I don't care if the user can't see the ConfirmationPageView in this very short transition. I just need this confirmation page to show up breifly so that a third party analytics application can track whether a user visited this confirmation page. Thank you, and please leave any questions in the comments. -
Django free and pro version in one project [closed]
How do I go about having 2 versions of django projects, one is free the other is paid? I don't know how to restrict some users from the pro version. I also want to include speech to text in the app -
How to optimize a batch query to make it faster
When changing the status of a document, I would like to put all the products in the document into stock. This involves changing several fields. At low amount of product instances, the query works quickly >50ms. However, some documents have products in quantities of, for example, 3000. Such a query takes more than a second. I know that there will be cases with much higher number of instances. I would like the query to be faster. A simple loop takes ~1sec. class PZ_U_Serializer(serializers.ModelSerializer): class Meta: model = PZ fields = '__all__' def update(self, instance, validated_data): items = instance.pzitem_set.all() bulk_update_list = [] for item in items: item.quantity = 100 item.quantity_available_for_sale = 100 item.price = 100 item.available_for_sale = True item.save() return super().update(instance, validated_data) Batch_update takes about 400ms per field. In this case 1600ms (which is slower than a loop). class PZ_U_Serializer(serializers.ModelSerializer): class Meta: model = PZ fields = '__all__' def update(self, instance, validated_data): items = instance.pzitem_set.all() bulk_update_list = [] for item in items: item.quantity = 100 item.quantity_available_for_sale = 100 item.price = 100 item.available_for_sale = True bulk_update_list.append(item) items.bulk_update(bulk_update_list, ['quantity', 'price', 'quantity_available_for_sale', 'available_for_sale'], batch_size=1000) return super().update(instance, validated_data) In post-gre console I see at (3000 objects) about 11,000 read hits. I tried adding transaction.atomic before … -
Why user.is_authenticated not working? django, LoginRequiredMixin
I'm logged in. why display NOT LOGIN! in html? VIEWS from django.contrib.auth.mixins import LoginRequiredMixin class UserHomeView(LoginRequiredMixin, ListView): model = User template_name = 'users/users_index.html' paginate_by = 10 context_object_name = 'user' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) return context HTML {% if user.is_authenticated %} LOGIN! {% else %} NOT LOGIN! {% endif %} setting.py LOGIN_URL = '/users/login/' -
Editing Profile not updating
I am editing profile using Django framework. The problem lies where I cannot save or update the data inputted by the user and it shoes the error list. If I make it as not required, it shows blank in the system. How can I only save the ntry which user update and remain all other entry unchanged? Thank you Error: <ul class="errorlist"><li>username<ul class="errorlist"><li>This field is required.</li></ul></li><li>email<ul class="errorlist"><li>This field is required.</li></ul></li><li>password<ul class="errorlist"><li>This field is required.</li></ul></li><li>confirm_password<ul class="errorlist"><li>This field is required.</li></ul></li><li>password_readonly<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Edit User Profile def sa_profile_edit(request): if request.user.is_authenticated: form =UserFormAdmin(instance=request.user) form_profile = MemberForm(instance=request.user.usermember) context = {'form':form, 'form_profile': form_profile} if request.method == 'POST': form =UserFormAdmin(request.POST,instance=request.user) form_profile = MemberForm(request.POST, request.FILES, instance=request.user.usermember) if form.is_valid() and form_profile.is_valid(): form.save() form_profile.save() messages.success(request,'Profile Successfully Updated') return redirect('sa_profile') else: print(form.errors) form =UserFormAdmin(instance=request.user) form_profile = MemberForm(instance=request.user.usermember) user_data = request.user context = {'form':form,'user_data':user_data, 'form_profile': form_profile} return render(request, 'pages/sa_editProfile.html', context) return render(request, 'pages/sa_editProfile.html', context) If role is super -- only super can view this def check_role_super(user): if user.role == 3: return True else: raise PermissionDenied Model class User(AbstractBaseUser): MEMBER = 1 ADMIN = 2 SUPERADMIN = 3 ROLE_CHOICE = ( (MEMBER, 'Member'), (ADMIN, 'Admin'), (SUPERADMIN, 'Super Admin') ) ACTIVE = 1 DELETED = 2 DEACTIVATED = 3 STATUS = ( … -
Django AuthenticationForm Error messages not showing
My question is when I give the wrong email or password, No error message is Shown, but why ?? and how can I fix that? This is my signin View function def signin(request): form = AuthenticationForm(request=request, data=request.POST) if form.is_valid() == True: user = authenticate(email=form.cleaned_data['username'], password=form.cleaned_data['password']) if user is not None: login(request, user) return HttpResponse(f'{request.user}') else: context = {'form': form} return render(request, 'signin.html', context) This is my Html <form action="{% url 'signin' %}" method="post"> {% csrf_token %} {% for field in form %} {{ field.errors }} {{ field }} <br> {% endfor %} <button type="submit">Signin</button> </form> -
I don't know why this class is not adding through javascript
I am trying to add a javascript class show with dropdown-content, but it is not adding there infact while console logs are working perfectly fine upto the last scope of the javascript script tag. Can anyone help me out from this? The text with the id is basically coming from django database which is unique. <div class="eps_dots more_dropdown dropdown"> <a href="#" onclick="get()" id="{{course.course_id}}" class=""><i class="uil uil-ellipsis-v"></i></a> <div class="dropdown-content "> <span><i class="uil uil-heart"></i>Save</span> <span><i class="uil uil-ban"></i>Not Interested</span> <span><i class="uil uil-windsock"></i>Report</span> </div> </div> <script> function get() { const focused = document.activeElement.getAttribute("id"); console.log(focused); menu(focused); } function menu(focused) { const path = '#' + focused + ' .dropdown-content'; console.log(path); $(path).toggleClass("show"); } </script> .eps_dots .show{ display: block !important; } -
How to store and work on traffic map data efficiently
I have been to work on a project which deals with traffic map data from Here API and I wanted to know what is the best way of storing data that is fetched from API. The performance issue can be resolved on frontend if the data is stored either in Relational or Non-Relational Database. Traffic data is in json and I have been dumping all data at frontend to work on it. I am looking for the efficient way and guidance to build a structured web application. The Backend is in Django-Python and the json-response are used for data. There is a need for ML and AI in project. LeafletJs is used for frontend maps. In short, what should be the suitable formation of database and architectural design of backend? -
check if passed context is Empty in Template
what I'm trying to achieve here is if context is empty or if STUDENT variable is empty, instead of returning all students. it should return none and in template it shows No results found. currently when nothing is stored in q my template render all the students. in views. def student_home(request): q = request.GET.get('q') if request.GET.get('q') != None else "" students = Student.objects.filter(Q(first_name__icontains=q) | Q(last_name__icontains = q) | Q(grade__icontains=q)) context = {'students': students} return render(request, 'StudentManager/home.html', context) search-bar in NAVBAR. <form class="d-flex" role="search" action='{% url 'student_home' %}'> <input class="form-control me-2" type="search" name='q' placeholder="Search Student" aria-label="Search"> <button type="submit" class="btn" style="background: #fff2df;">Search</button> </form> -
What would be the best approch to display a commenting form in the ListView for each blog post?
I currently have fully functional commenting form in my blog post view that I want to display in the ListView. Sort of like linkedin has under every list item, if you have noticed, i think facebook has the same thing. Is there a shortcut to achieve this? -
Not null constraint failed django with clean function
I am getting the error you see in the title. my purpose if banner_button_activate is true then banner_button_title and banner_button_url must be filled. But if it is false it doesn't matter if it is full or not. I did number 1, but when it comes to number 2, I get the error in the title. example NOT NULL constraint failed: appearance_banner.banner_button_url models.py class banner(models.Model): banner_name = models.CharField(max_length=200,primary_key=True) banner_image = models.ImageField(("Banner resmi"), upload_to="media/images/site/banner",help_text="1770x550 boyutunda resim önerilmektedir.") banner_title = models.CharField(max_length=100,null=True,blank=True) banner_title_activate = models.BooleanField(default=True) banner_description = models.TextField(null=True,blank=True) banner_description_activate = models.BooleanField(default=True) banner_button_title = models.CharField(max_length=50,null=True,blank=True) banner_button_url = models.SlugField(null=True,blank=True) banner_button_activate = models.BooleanField(default=True) banner_button2_title = models.CharField(max_length=50,null=True,blank=True) banner_button2_url = models.SlugField(null=True,blank=True) banner_button2_activate = models.BooleanField(default=True) banner_order = models.IntegerField(editable=True,default=1,blank=False,null=False,verbose_name="Sıra") banner_status = models.CharField(max_length=100,choices=STATUS,verbose_name="Banner Statüsü") def __str__(self): return self.banner_title def delete(self, *args, **kwargs): self.banner_image.delete() super(banner, self).delete(*args, **kwargs) def clean(self): # if (self.banner_title_activate): # if not (self.banner_title): # raise ValidationError({"banner_title":"Eğer bu bölüm aktifse buton title dolu olmalı.",}) if not (self.banner_button_title and self.banner_button_url and self.banner_button_activate): print("selam") print(self.banner_button_url) if None == self.banner_button_title and None == self.banner_button_url and False != self.banner_button_activate: print("selam 3") raise ValidationError({"banner_button_url":"Eğera bu bölüm aktifse buton url dolu olmalı.","banner_button_title":"Eğer bu bölüm aktifse button title dolu olmalı."}) elif (None == self.banner_button_url and True == self.banner_button_activate): print("selam 2") raise ValidationError({"banner_button_url":"Eğer bu bölüm aktifse button url dolu …