Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is_popup option in django does not seem to work
I'm overriding admin/change_form.html right now. As far as I understand I can make the new page popping up setting is_popup variable to True like so: data = { 'brands': brands, 'opts': opts, 'change': True, 'is_popup': True, 'save_as': False, 'has_delete_permission': False, 'has_add_permission': False, 'has_change_permission': False, 'app_label': app_label } But as a result I don't have any window popping up. Just another tab opens up. Here is my template: {% extends "admin/change_form.html" %} {% load i18n admin_static admin_list %} {% block title %} Apply users to brand {% endblock %} {% block content %} <h1>Select brands</h1> {% for brand in brands %} <li> <a href="http://localhost/admin/user/user/{{brand.id}}/test/">{{ brand }}</a> </li> {% endfor %} {% endblock %} I don't get what I'm doing wrong. I'm very new in django so any help is much appreciated. -
JavaScript adding too many table rows
I have a JS script as follows: function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+-)'); var replacement = prefix + '-' + ndx + '-'; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function addForm(btn, prefix) { var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val()); if (formCount < 3) { var row = $(".item:last").clone(false).get(0); $(row).removeAttr('id').hide().insertAfter(".item:last").slideDown(300); $(".errorlist", row).remove(); $(row).children().removeClass("error"); $(row).find('.formset-field').each(function () { updateElementIndex(this, prefix, formCount); $(this).val(''); $(this).removeAttr('value'); $(this).prop('checked', false); }); $(row).find(".delete").click(function () { return deleteForm(this, prefix); }); $("#id_" + prefix + "-TOTAL_FORMS").val(formCount + 1); } return false; } function deleteForm(btn, prefix) { var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val()); if (formCount > 1) { var goto_id = $(btn).find('input').val(); if( goto_id ){ $.ajax({ url: "/" + window.location.pathname.split("/")[1] + "/formset-data-delete/" + goto_id + "/?next=" + window.location.pathname, error: function () { console.log("error"); }, success: function (data) { $(btn).parents('.item').remove(); }, type: 'GET' }); }else{ $(btn).parents('.item').remove(); } var forms = $('.item'); $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length); var i = 0; for (formCount = forms.length; i < formCount; i++) { $(forms.get(i)).find('.formset-field').each(function () { updateElementIndex(this, prefix, i); }); } } return false; } $("body").on('click', '.remove-form-row',function () { deleteForm($(this), String($('.add-form-row').attr('id'))); }); $("body").on('click', … -
function consumption optimization in python
I have a function that receives a list of integers and what each integer does is build a json, consume some api, do validations and then insert it into a database. But there is a problem, with a list of 2 values the function takes seconds but with a list of 200 values it takes minutes more than 8 minutes, is it possible to optimize that time by sending that amount of values? , it is possible to send a series of values so that the function does its job and at the same time send another amount of values and that the function does its job and thus, simultaneously send, for example, 50 values to the function and then send other 50 to the same function at the same time to optimize time? or how would be the ideal way to optimize it -
Django: "missing 1 required positional argument: 'lookup _name'" when it is not missing?
I am working with Django 3.1 ORM and am running (with pytest) a test involving a complex nested query. I get this failure: self = <django.db.models.expressions.Subquery object at 0x0000027CE184D2B0> lookup = 'lte' def get_lookup(self, lookup): > return self.output_field.get_lookup(lookup) E TypeError: get_lookup() missing 1 required positional argument: 'lookup_name' That get_lookup(lookup) to be called is defined (as far as I can see) in django.db.models.query_utils.RegisterLookupMixin as def get_lookup(self, lookup_name): ... The corresponding source statement of my test involves something like value = now() - OuterRef(OuterRef('myattr2')) * timedelta(days=1) queryset2.annotate(has_x=Exists(queryset.filter(myattr__lte=value))) and there is more query construction code around it. My debugger tells me that self.output_field is a DateTimeField object. So overall: The context is an Exists subquery. The lookup is 'lte' (as intended). The call provides a DateTimeField as self (from output_field) and 'lte' as lookup_name. The method-to-be-called expects self and lookup_name. The call should work, shouldn't it? Where is the TypeError? -
Unknown errors in console
I am building a copy of a social media app with Django backend and vanilla JS front end. I would like to update the likes of post asynchronously through PUT. In models.py are the following two models for post and like class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") date_posted = models.DateTimeField(default=timezone.now) content = models.TextField() def serialize(self): return { "id": self.id, "author_id": self.author.id, "date_posted": self.date_posted.strftime("%b %d %Y, %I:%M %p"), "content": self.content, "likes": self.post_likes.all().count() } def __str__(self): return f"{self.author.username} added a post" ... class Like(models.Model): # Use who 'likes' the post user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_likes") # Post 'liked' post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post_likes") def __str__(self): return f"{self.user.username} liked post {self.post.id}" In index.html is the following: {% for post in posts %} <div class="border border-light rounded pl-2 pr-2 pt-2 pb-2 mb-3"> <h6> <a href="{% url 'profile' post.author.id %}">{{ post.author }}</a> </h6> <hr> <p id="post_content-{{ post.id }}">{{ post.content }}</p> <div class="form-group mt-2" id="edit_div-{{ post.id }}" style="display: none;"> <textarea name="edit" id="edit_area-{{ post.id }}" class="form-control"> </textarea> <span> <button class="btn btn-sm btn-success mt-2" id="edit_btn-{{ post.id }}" style="display: inline;">Save</button> <button class="btn btn-danger btn-sm mt-2" id="close_btn-{{ post.id }}" style="display: inline;">Close</button> </span> </div> <p><small> Posted: {{ post.date_posted|timesince }} ago</small></p> <div id="btnsDiv"> <span> {% if request.user.id == post.author.id %} <button … -
Cloud Storage wtih Django - general structure
Well, I don't have any code yet (have, but it's unusable), so, I can't ask anything specific. Everything I need right now - structure of this software. Instruments, libraries, models, classes, where I can find information about API for this software, maybe another framework (advices, as well). Here is what I want to do: Upload files from command line using curl; Tiny frontend, which include registration, authentification, files list and base instruments like upload, delete, transfer from folder to folder; Administration: who and when uploaded the file, possibility to change and delete it. I understand, that it's not an easy project. But I'm really interested in it. -
Regex paths with Django. a list of items via clean URLs
I need url like /catalog/catalog_slug/tag_slug1/tag_slug2/tag_slug3 re_path(r'^catalog/(?P<category_slug>\w+)/(?P<tag_slugs>(?:\w+/)+)', ...) I read how to do multiple tag_slugs, but when I mix it with a single slug by another model (catalog) This stackoverflow answer[], I got: TypeError: get() got multiple values for argument 'category_slug' My view class CategorySeoTagsView(APIView): def get(self, category_slug, tag_slugs): pass -
Show similar users which matches with my profile's about
I am building a BlogApp and I am trying to show users which matches request.user profile's about. Suppose :- My about is Life is Good and Happy and if user_1's about is Life then show that user_1 in similars page list. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') about = models.CharField(max_length=2000,default='',null=True) views.py def similarUsers(request): users = Profile.objects.filter(about=request.user.profile.about) context = {'users':users} return render(request, 'similarUsers.html', context) -When i try the above code then, it is only working if Both user's profile about is exactly same. Any help would be much appreciated. Thank You in Advance. -
*** fatal error - Internal error: TP_NUM_C_BUFS too small: 50
I got my first intership. Clone project from gitlab, install all requirments with pipenv, connect postgres in .env. When i try to do pipenv run python app/manage.py migrate VSC send me this error. *** fatal error - Internal error: TP_NUM_C_BUFS too small: 50 screenshot -
How to sort , filter and display model data using week number in django
I would like to sort my model's data on a week number for example when user logins user will see current week number and associated data and user should be able to select previous week number and get all past data as well also week starts on Sunday and ends on Saturday (considering 1 week) Select Week :[2021 - 30 ] <- week number -
Django - Assigning Id to model
I am creating a donation like ecommerce site that allows people to donate and sell stuff. I have a screen, called acceptdonation, which allows people to see details about a certain donation. I have a button on that screen, which a user can click if they want to accept the donation. When this button is clicked, I display an alert (it uses swal to style, but functions like a regular alert), and if the user clicks on the ok button, I want to delete that specific data that they are looking at. I asked this question, and I was given an answer that requires me to use an id. I don't assign an id in my model, and they way I render out my donation is down bellow. I was wondering how I can assign a unique id to each one of my donations so I can delete them later on. My code is in detail bellow. Also please feel free to ask any questions, I am always on my pc. Swal alert (I need to assign an id in order for this to work): swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation … -
Creating input fields inside a form using JavaScript
I'm working on a quiz app and want to generate a number of input fields representing the answers based on the value that the user types. I'm using a button named "create" to do that Using JavaScript, but when clicking the button it submits the form. Please Check the two images below. Input Output HTML Code {% load static %} {% block body %} <button class="btn btn-primary new">Add a question</button> <form class="question" method="POST" style="display: none"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail1">Title</label> <input type="text" class="form-control" id="title" placeholder="Question title"> </div> <div class="form-group" id="answers_num"> <label for="exampleInputPassword1">Number of answers</label> <input type="number" class="form-control" id="ans_number"> <button class="create_answers">Create</button> </div> <div class="form-group"> {% comment %} Generated input fields {% endcomment %} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> {% block script %} <script src="{% static 'mcq/index.js' %}"></script> {% endblock %} {% endblock %}``` JS code document.querySelector(".new").addEventListener("click", ()=> { document.querySelector(".question").style.display = 'block'; document.querySelector("#create_answers").addEventListener("click", ()=> { answers = this.value; console.log(answers); // Create input fields for (let i = 0; i < answers; i++) { input = document.createElement("input"); input.classList.add('form-control'); answersDiv = document.querySelector("#answers").appendChild(input); } }) })``` -
Django: get_or_create()[0] raises a multiple-return error
I thought I understood that get_or_create() returns a tuple, therefore assigning [0] at the end should pick the first object in the query result. However, it raises an error like the following: MultipleObjectsReturned at /admin/hr/clientcontact/add/ get() returned more than one ClientDepartment -- it returned 4! (I do have 4 objects in the ClientDepartment model.) Below is the code for ClientContact model where I used get_or_create()[0]. class ClientContact(Person): def get_default_client_department(): return ClientDepartment.objects.get_or_create()[0].id department = models.ForeignKey( 'ClientDepartment', on_delete=models.RESTRICT, default=get_default_client_department, ) def company(self): return self.department.company I would appreciate any help and the explanation. Thank you. -
Django forms stop form processing on ValidationError
I'm designing a Django form with recaptcha and custom cleaning method for address field. I want to stop form processing on first ValidationError in other words I don't want to execute clean_address method if recaptcha is bad. For recaptcha I using django-recaptcha. My form: from django import forms from captcha.fields import ReCaptchaField from .models import Server, Category from .utils.status_manager import ServerStatus class AddServerForm(forms.ModelForm): captcha = ReCaptchaField() categories = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'checkbox'}), error_messages={ 'required': 'You need to select server type' }, choices=[(c.pk, c.name) for c in Category.objects.all()] ) def clean_address(self): address = self.cleaned_data['address'] server = Server.objects.filter(address=address).exists() if server: raise forms.ValidationError("Server is on the list") if not ServerStatus(address).is_server_on(): raise forms.ValidationError("Server is offline") return address class Meta: model = Server fields = ['address'] View: class AddServer(LoginRequiredMixin, FormView): template_name = 'add_server.html' login_url = '/users/discord/login' form_class = AddServerForm def form_invalid(self, form): errors = get_form_errors(form) for error in errors: messages.add_message(self.request, messages.ERROR, error) return super(AddServer, self).form_invalid(form) def form_valid(self, form): server = form.save() self.success_url = f'/servers/{server.id}' return super(AddServer, self).form_valid(form) For now on ValidationError or if recaptcha is bad form still processes. -
Django DRF - Patch request object in viewset?
We are using oauth2 and perform force_login() in our tests simulate authentication. However in our modelviewset, we now want to override create() to check for some specific authorization (in the requests object eg request.auth['MYROLES']) permissions we would get in our access tokens. I cannot work out how I can patch the request object to have the expected attribute to ensure our test can work without failing due to missing object attributes. Any ideas? -
how to fetch two models at the same time in django
i want to fetch two model in same html but unable to get both only getting one i am using class based view in django here is my views.py class home(View): def get(self, request,): category_list = Categories.objects.all() print(category_list) return render (request, 'home.html', {'category_list': category_list }) def get (self, request): subcategory_list = Subcategories.objects.all() return render (request, 'home.html', {'subcategory_list': subcategory_list}) i guess i cannot call get function two time in cbv i have to make both of the model in same function help will be appreciated thank you -
Are there alternative methods to using hashrouter to make page urls work? (Django Backend + React Frontend)
I am using a React JS frontend and Django Backend, and I was wondering if there are any solutions, other than hashrouter, when using urls with BrowserRouter, once I npm run build the frontend code. I've heard that using hashrouter has a negative impact on the SEO of the website. E.g. I want urls to be http://localhost:8000/products instead of http://localhost:8000/#/products (HashRouter). Any help would be much appreciated. Thanks -
Django - unable to create build API
Well, I'm trying to get to 'http:// 127.0.0.1:8000/api/files/", but getting a mistake, that: Using the URLconf defined in WTF_2.urls, Django tried these URL patterns, in this order: admin/ graphql/ Start/ The current path, api/file/, didn’t match any of these. I understand what is this about, but can't really find where I did the mistake. My 'File' model from 'Start/models.py: class File(models.Model): class Meta: ordering = ['-publish_date'] title = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True) ... ... My 'urls.py' from 'Start/urls.py': from django.urls import path from .views import FileView app_name = 'Start' urlpatterns = [ path('Start/', FileView.as_view()), ] And my 'urls.py' from 'mainproject/urls.py': from django.contrib import admin from django.urls import path, include from django.views.decorators.csrf import csrf_exempt from graphene_django.views import GraphQLView urlpatterns = [ path('admin/', admin.site.urls), # graphiql = true указывает графену сделать доступным graphiql интерфейс path('graphql', csrf_exempt(GraphQLView.as_view(graphiql=True))), # api интерфейс path('Start/', include('Start.urls')) ] -
How can I get Posts related to the user in Django?
class ShowProfilePageView(DetailView): model=User template_name="users/profile.html" paginate_by = 5 def get_context_data(self, *args, **kwargs): users=User.objects.all() nested_posts = {} context = super(ShowProfilePageView,self).get_context_data(*args, **kwargs) page_user = get_object_or_404(User, id=self.kwargs['pk']) context['page_user'] = page_user return context I am able to get the id but not the posts related to that id. what i am able to retrieve is the user's name, profile description, and profile image. -
OpenCV read image from Reactjs base64
Hello i'm currently working with react js for frontend and django for backend to do some image processing. But i'm struggling with upload an image from base64 react js to opencv python. This is my code in React.js to upload image and convert it to base64 handleImageSubmit = async (e) => { e.preventDefault() let image = await this.convertBase64(this.state.imageSrc) console.log(image) axios.post("/image/", { image }).then((res) => { // this.setState({ imageDst: res.data }) console.log(res.data.data) }).catch((err) => console.log(err)); } convertBase64 = (file) => { return new Promise((resolve, reject) => { const fileReader = new FileReader() fileReader.readAsDataURL(file) fileReader.onload = () => { resolve(fileReader.result) } fileReader.onerror = (error) => { reject(error) } }) } And this is my code in django views : @api_view(['GET', 'POST']) def image(request): sbuf = StringIO() sbuf.write(base64.b64decode(request.data['image'])) pimg = Image.open(sbuf) img_array = np.array(pimg) cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR) print(img_array) return JsonResponse({"data": "data"}) When i'm decode base64 image there is an error like this Invalid base64-encoded string: number of data characters (184641) cannot be 1 more than a multiple of 4 How to upload an image, process the image to opencv python and give the image back to the react (frontend)? Thank you! -
How to insert an ad in between paragraphs on Django site?
I would like to place ads randomly in between paragraphs on the blog post page. I want to do it dynamically as I can't insert an ad when creating a post. The blog post content was saved in Django Text or HTML field. For example, this is a paragraph {{ here is an ad }} this is another paragraph please give me a solution. -
Can get cleaned_data when customyzing LoginView in django
Beginner with Django 3.2. I'm trying to add a Recaptcha V3 from Google on my login screen. I'am using django-recaptcha3 well configured The logo is showing on my login page When debugging the json response when calling ReCaptchaField.clean is OK ! The problem is that the form is not validated "'CustomAuthenticationForm' object has no attribute 'cleaned_data'" Here is my code : In urls.py from django.urls import path from .views import CustomLoginView urlpatterns = [ path('login', CustomLoginView.as_view(), name='login'), ] In Forms.py from django.contrib.auth.forms import AuthenticationForm from snowpenguin.django.recaptcha3.fields import ReCaptchaField class CustomAuthenticationForm(AuthenticationForm): captcha = ReCaptchaField() In Views.py from django.contrib.auth.views import LoginView from django.views import generic from django.contrib.auth.forms import AuthenticationForm from .forms import CustomAuthenticationForm class CustomLoginView(LoginView): def post(self, request, *args, **kwargs): if request.method == "POST": form = CustomAuthenticationForm(request.POST) if form.is_valid(): captcha_score = form.cleaned_data['captcha'].get('score') print("SCORE" + str(captcha_score)) return super().post(self, request, *args, **kwargs) form_class = CustomAuthenticationForm template_name = 'accounts/login.html' request.POST gives <QueryDict: {'csrfmiddlewaretoken': ['TGoQaJTZACp4MbwB3iGVVdL4IHbqWDQaIhE1ldb9M8fkpjSRDHV7l1A1tTb62f3B'], 'g-recaptcha-response': ['03AGdBq270w7Z23MTavtAHLAUNSY9IWKuVpFZe0eueIiXimW6BvhTeWKANQQIFj43m903GA-cUA-dXZm7I6br.......5Z9vdM6RY9v-Kk1ZLX1uwH5nSoc7ksWUQuA00w0T8'], 'username': ['remi@XXXXXe.fr'], 'password': ['vXXXXX']}> which is normal. form.is_valid() is failing and I suspect form = CustomAuthenticationForm(request.POST) to be the problem but I don't know how to do. Thanks a lot for your help, -
Hosts file working for custom subdomains but not custom domains
I am developing a multi tenant app and need to modify my etc/hosts file to test the different URLs tenants might use. Some will use a sub domain like tenant1.mysite.com and others will use entirely their own URL like tenant2.com (to mask the fact it's a whitelabel site and pretend its their own). In my hosts file I have: 127.0.0.1 mytenantsdomain.com 127.0.0.1 localhost 127.0.0.1 thor.localhost 127.0.0.1 potter.localhost 127.0.0.1 testtenant.com localhost, thor.localhost, potter.localhost all work as expected when adding :8000 to them. i.e. they connect to the local development server and show expected tenant-specific content. But, mytenantsdomain.com and testtenant.com both give ERR_CONNECTION_REFUSED - I'm guessing its for the lack of the port :8000 tbh. I have tried a few fixes like flushing the cache with the below but nothing has worked. sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder Anybody know what else I can try to get them all working? -
{% if user.is_authenticated %} for specific user only
i am using : {% if user.is_authenticated %} to check if people are logged in, so i can set the navbar links depending on logged in or not. I want to make navbar links special for admin user. So there has to be a check not just if het user is authenticated, but also if that authenticated user is Admin. I was thinking about something like {% if user(Admin).is_authenticated %) but that didn't work. Somebody got an idea? -
Django corruption when the server is reloaded
The Django server listens on files and tries to restart itself. But, every time, it fails by returning this error in the console : double free or corruption (out) Abandon (core dumped) When the only scripts modified are written in HTML, CSS and JS, this error doesn't appear, so it seems to come from the server. This error appeared when my application becomes more and more advanced. As the error message returned is not very explicit (no file name, no line number), I can't know which part of my application I could publish on StackOverFlow.