Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom Django Form Widgets
I have a field for which I am populating data using js. The data in user field is being populated from view using ajax call. I want to create a custom widget which can be used to filter and select the values. like the TypedChoiceField Widget; I want to create TypedSelectField that can be used to filter and select from the options that are populated. user = forms.CharField(widget= forms.Select(),required=True) Any ideas on how to create such custom widget. I tried overriding forms.ChoiceField but it is not working. -
A table of MySQL database asociated to Django App is "corrupted"
I have problem that has never happened to me before. It is an application made with Django that has never given me errors. For some reason, a table in the database (MySQL) is corrupted, but the app is still working. However, when I make a call like this: queryset = Tuition.objects.filter(agent = user) Then, the database gives me this error: django.db.utils.OperationalError: (1712, 'Index base_tuition_agent_id_b1b4dfb6_fk_base_staff_user_ptr_id is corrupted') But, if I change the call to: queryset = Tuition.objects.filter(Q(date__lte="1900-01-01")|Q(agent__id=90)) Then, There is no error... Surprise! (Obviously in the database there is no date prior to 1900 so both functions are similar). But, if I change the call to: queryset = Tuition.objects.filter(Q(date__gte="1900-01-01")&Q(agent__id=90)) Then, the database through the error again... So: If I filter by "agent" doesn't work. If I filter with an "OR" conditional combining the "agent" field with another one it works. If I filter with an "AND" conditional combining the "agent" field with another one doesn't work. You can see the details of the table here: I don't know much about MySQL and would like to know how the result of the above calls is possible. Because from my ignorance, the normal thing would be that none of them work, or well, … -
Django: How to use OuterRef() for .get() in annotate?
I am using django-treebeard and use a model that allows recursive relations. So, I need to count the number of my descendants using .annotate(), but To get it, you need to go through .get() once, as shown below. However, in that case, OuterRef("pk") does not seem to work and the following error occurs. This queryset contains a reference to an outer query and may only be used in a subquery. What can I do to solve this problem? queryset.filter(post=post) .annotate( reply_count=Count( Comment.objects.get( pk=OuterRef("pk") ).get_descendants() ) ) -
Allow user to fill only one of the fields not both | Django
I'm creating an app like reddit where you can post videos and texts. I want to let the user choose between video and image field but not both here is what I've done: class CreatePostForm(ModelForm): class Meta: model = Post fields = ['title','video','image','text'] widgets ={'title':forms.TextInput({'placeholder':'تیتر'}), 'text':forms.Textarea({'placeholder':'متن'})} def clean(self): cleaned_data = super().clean() text = cleaned_data.get("text") video = cleaned_data.get("video") if text is not None and video is not None: raise ValidationError('this action is not allowed', 'invalid') this shows the validationError but even when the user only fills the video fileField and not the texField it still shows the validationError -
Send image as a JSON with Pytest
I have a DRF POST endpoint that accepts some data + image, my question is how can I test this endpoint using something like Pytest, I'm facing a prob with sending images as a JSON, I tried to use PIL but didn't work. serializer class CreateCategorySerializer(serializers.Serializer): title = serializers.CharField(max_length=255) description = serializers.CharField(max_length=500, required=False) priority = serializers.IntegerField(default=0) image = serializers.ImageField() test @pytest.mark.django_db def test_name_exist(authenticate_superuser, category): data = { "title": "CAT 1", "description": "Description", "priority": 20, "image": "??" } response = authenticate_superuser.post(reverse('category_admin:create'), data=data) assert response.status_code == status.HTTP_400_BAD_REQUEST assert response.data['detail'] == 'This title already exists' -
How to do SSO between Wordpress and Django?
Is it possible to do SSO with WordPress and Django as I have found old documentation related to SSO between WordPress and Django? Is there any implemented example or documentation from which I can get help Thanks -
Django - Log response for each request
I have an API built using Django framework . I have to log the following datapoints for each time a request hits the API. Request Method Request Path Request object Response Status code Response Latency (if possible) I tried using the request_finished signal but it does not bring the response object with it. How can I accomplish this? -
Vue.js-Failed to load resource: the server responded with a status of 401 (Unauthorized)
I'm currently working on a project that collects payment info(like the products the client wants to buy, and how much that product costs) and client details(client name, client address, client credit card info, etc.) and I need to access Stripe's online payment system for the purchase. However, during my trial run, every time I try to click all "Pay", I keep getting notifications that something went wrong. I checked the terminal and it keeps displaying this error: Failed to load resource: the server responded with a status of 401 (Unauthorized) I'm also using Django's rest framework for my backend development, and it keeps displaying this HTTP 401 Unauthorized Allow: POST, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Token { "detail": "Authentication credentials were not provided." } This is the code I think the problem is located in: <template> <div class="page-checkout"> <div class="columns is-multiline"> <div class="column is-12"> <h1 class="title">Checkout</h1> </div> <div class="column is-12 box"> <table class="table is-fullwidth"> <thead> <tr> <th>Product</th> <th>Price</th> <th>Quantity</th> <th>Total</th> </tr> </thead> <tbody> <tr v-for="item in cart.items" v-bind:key="item.product.id"> <td>{{ item.product.name }}</td> <td>{{ item.product.price }}</td> <td>{{ item.quantity }}</td> <td>₱{{ getItemTotal(item).toFixed(2) }}</td> </tr> </tbody> <tfoot> <tr> <td colspan="2">Total</td> <td>{{ cartTotalLength }}</td> <td>₱{{ cartTotalPrice.toFixed(2) }}</td> </tr> </tfoot> </table> </div> <div class="column is-12 … -
TypeError: context must be a dict rather than module
I am trying to follow along with a tutorial for Django. link In my views.py in the folder articles def article_create_view(request): # print(request.POST) if request.method == "POST": title = request.POST.get('title') content = request.POST.get('content') print(title, content) article_object = Article.objects.create(title = title, content = content) context['object'] = article_object context['created'] = True return render(request, "articles/create.html", context= context) articles/create.html is the following code: {% extends "base.html" %} {% block content %} {% if not created %} <div style="margin-top:30px;"></div> <form method = "POST"> {% csrf_token %} <div><input type = 'text' name ='title' placeholder = 'Title' /></div> <div><textarea name ='content' placeholder ='Content'></textarea></div> <div><button type='submit'>Create article </button></div> </form> </div> {% else %} <p> Your article was created</p> <a href="/articles/{{object.id}}/"> {{object.title}} - {{object.content}}</a> {% endif %} {% endblock content %} I am getting this error: TypeError: context must be a dict rather than module. [26/May/2022 15:06:36] "GET /articles/create HTTP/1.1" 500 81512 -
Django admin static files need to be redirected to different path
I am sorry if I am asking this question again. But I did try to find the answer without success. My static files of the admin page seem to be in different location then it is looking for them. How can change the location of where it should look? I could move the admin static folder but that would to much hassle if I make changes, right? Thanks -
POST Request to HTTPS(SSL) url from Android/Java
I am pretty new to Java and Android. Working on Python all the time. I am trying to make an Android Apps via Android Studio BumbleBee (2021.1.1 Patch 3) that can make GET and POST request to a https(SSL) server. The server is run by Django 3.2, deploy on IIS(version 10.0) powered by Window Server 2019. GET requests are fine but POST requests are not! What i am trying to do is to make a POST request to login to the website. My idea is to send a GET request to obtain the csrftoken and csrfmiddlewaretoken for subsequent POST request. (From my understanding, Django POST requires csrfmiddlewaretoken in the POST data and csrftoken in the cookies). Everything works fine when i tried on http://localhost:8000 OR i use @csrf_exempt decoration on both HTTP and HTTPS(SSL) server. But the actual server which run by Django is HTTPS(SSL) instead of HTTP and i want to remain the csrf function. Since i keep failing on Android Studio, I tried to make POST request to https by Java(on Eclipse IDE Version: 2022-03 (4.23.0)) and it keeps returned an error of 403. I tried with SSL Socket Factory in Java but still it does not work. … -
how to show many nested childs in a queryset in efficient way, for loops dont work
I have created two models, 1st is Book and 2nd is SubBookPart (Sub Part of Book) User creates a book first then add its sub part like "Chapter 1", "Chapter 2" and so on to that book then add "Page 1", "Page 2" and so on to each chapter then add "Paragraph 1", "Paragraph 2" and so on to each Para I successfully does this My Book Look Like This BookName |- Chapter 1 |- Page 1 |- Paragraph 1 |- Paragraph 2 |- Paragraph 3 |- Page 2 |- Paragraph 1 |- Paragraph 2 |- Paragraph 3 |- Chapter 2 |- Page 1 |- Paragraph 1 |- Paragraph 2 |- Paragraph 3 |- Page 2 |- Paragraph 1 |- Paragraph 2 |- Paragraph 3 |- Page 3 |- Paragraph 1 |- Paragraph 2 |- Paragraph 3 But I dont know how to show it in frontend, because it will take very very long nested for loop, Is There and other way models.py class Book(models.Model): name = models.CharField(max_length=50) subparts = models.ManyToManyField("SubBookPart", related_name="book_subparts", blank=True) class SubBookPart(models.Model): # for only first sub part subpart_of_book = models.ForeignKey(Book, on_delete=models.CASCADE,null=True, blank=True) # for only non-first sub parts, giving reference to previous subpart subpart_of = models.ForeignKey("SubBookPart", … -
Django - a.html include b.html file which is not located in the template folder
I have two htmls a.html and b.html. a.html is located in the template folder by default. b.html is located in appname/static/images/b.html In a.html, I am trying to include b.html but it's not working, unless b.html is in the same template folder. <body> {% include 'appname/static/images/b.html' %} </body> questions: how to include b.html? how to include b.html dynamically if it's in different folder, e.g. images/username/b.html where username is different. -
nested serializer error. 'str' object has no attribute 'values'
i am currently working social media type app where i wants to get the group detail and users detail which are posted the post. the problem is occure when i used nested serializer in post serializer the group serializer is working perfectly when i write the user serialize it gives the following error packages/rest_framework/serializers.py", line 368, in _readable_fields for field in self.fields.values(): AttributeError: 'str' object has no attribute 'values' [26/May/2022 09:01:21] "GET /group/posts/3 HTTP/1.1" 500 123293 Here is my models and serialzers post model class Post(models.Model): post_data = models.FileField(upload_to='group_post', null=True) post_description = models.TextField(null=True,blank=True) post_time = models.DateTimeField(auto_now=True) post_group = models.ForeignKey(to='Group', on_delete=models.DO_NOTHING, related_name='post_group') post_user = models.ForeignKey(to=MyUser, on_delete=models.DO_NOTHING, related_name='post_user') class Meta: db_table = "group\".\"Post" post serializers class PostSerializer(serializers.ModelSerializer): post_group = GroupSerializer(read_only=True) post_user = UserSerializer(read_only=True) class Meta: model = Post fields = '__all__' user Model class MyUser(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(verbose_name='Enter Email', max_length=50,unique=True) password = models.CharField(max_length=1000) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) user serialzer class UserSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = '__all__' -
How can I do a redirect in Django and React?
I need to do a redirect right after pressing a button. <Button onClick={changeCalendar}>Integrate Google Calendar</Button> So I'm sending a request to a server to do the redirect const changeCalendar = async () => { let response = await fetch("http://localhost:8000/gcalendar/", { mode: "no-cors", method: "GET", headers: { Authorization: "Bearer " + String(authTokens.access), }, }); On the server side I process the request, and get a URL def change_calendar(request): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES) flow.redirect_uri = 'http://localhost:3000/' authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true') return redirect(authorization_url) If I print authorization_url it looks like this: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=**ID**&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.events&state=**STATE**&access_type=offline&include_granted_scopes=true If I copy and paste the link into a Google search, it opens a Google authorization window. I need to do the same one through code. But redirect doesn't work. Even if I try to do a redirect to other links. -
create custom mixin in DRF
I want to create custom mixin in Django Rest Framework, which will return data in CSV format. This to_csv method should convert fields to CSV format class ToCSVMixin: @action(detail=False, methods=['get']) def to_csv(self,request): fields = None /* some stuff here to convert fields list to CSV */ Problem is that I'm not sure how to use to_csv method in view. fields list should be populated in MyViewSet class MyViewSet(ModelViewSet,ToCSVMixin): /*.... */ Thank you in advance -
Django - Delete FOLDER from amazon S3
I'm using django post_delete signals to delete all files or folders (folders that would be empty after files be deleted) related to a deleted object in my DB. For some reason I am not able to make the s3 delete a FOLDER, even after searching numerous guides and snippets, maybe someone here knows. I use django 3.2.7 and boto3. Here's my code: models.py from django.db import models class Album(models.Model): """ Category Model Attributes: *name: A string indicating the category name; *friendly_name: A string indicating category friendly name. Sub-classes: *Meta: Display the object's plural name. Methods: *__str__: Display the object's headline in the admin interface, it returns a nice, human-readable representation of the model; *get_friendly_name: Display the object's friendly name. """ category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(null=True, max_length=150) pre_desc = models.CharField(null=True, max_length=500) date = models.DateField(null=True) place = models.CharField(null=True, max_length=500) cover = models.ImageField(blank=True, null=True, upload_to="portfolio/covers/") description = models.TextField(null=True) def save(self, *args, **kwargs): """ Override the original save method to set the lineitem total and update the order total. """ album_type = self.category.name folder_type = album_type.replace(" ", "_") album_title = self.title folder_name = album_title.replace(" ", "_") for field in self._meta.fields: if field.name == 'cover': field.upload_to = f"portfolio/covers/{folder_type}/{folder_name}" super(Album, self).save() def … -
single form for the whole process or separate for each post type | django
I'm trying to make an app like reddit where you can create post for any server you want but you are only allowed to post image&video/text not both. but the problem is i don't know if i have to make a single ModelForm for the whole process and hide or show fileField and textField using Javascript ,or make a ModelForm for each type of post and change the form that is displaying using Javascript posts/forms.py: class CreatePostTextForm(ModelForm): class Meta: model = Post fields = ['title','video','image','text'] widgets ={'title':forms.TextInput({'placeholder':'تیتر'}), 'text':forms.Textarea({'placeholder':'متن'})} posts/views.py class CreatePostView(LoginRequiredMixin, View): form_class = CreatePostTextForm def dispatch(self, request, *args, **kwargs): user = User.objects.get(id=kwargs['pk']) if not user.id == request.user.id: messages.error(request, 'شما نمیتوانید باپست ایجاد کنید') return redirect('home:home') return super().dispatch(request, *args, **kwargs) def get(self, request, pk): form = self.form_class() return render(request, 'posts/create-post.html', {'form':form}) def post(self, request, pk): form = self.form_class(request.POST, request.FILES) if form.is_valid(): saved_form = form.save(commit=False) saved_form.creator = request.user saved_form.save() messages.success(request, 'پست شما باموفقیت ایجاد شد') return redirect('home:home') return render(request, 'posts/create-post.html', {'form':form}) posts/create-post.html <div class="create-post-form-wrapper col-8"> <div class="form-header"> <div class="form-types"> <button onclick="postType(0)"> <p>متن</p> <img src="{% static 'posts/svgs/file.svg' %}" alt="" /> </button> <button onclick="postType(1)"> <p>عکس</p> <img src="{% static 'posts/svgs/image.svg' %}" alt="" /> </button> <button onclick="postType(2)"> <p>فیلم</p> <img src="{% static 'posts/svgs/video.svg' %}" alt="" /> … -
How to customize learner profile in OpenEdx?
I managed to customize some templates in lms, but now I need to customize learner profile. I know how to overwrite learner_profile.scss, but I have trouble with html template. I found learner_profile.html template in location outside of lms directory: openedx/features/learner_profile/templates/learner_profile/learner_profile.html I have tried to overwrite it with: themes/my-theme/openedx/features/learner_profile/templates/learner_profile/learner_profile.html themes/my-theme/openedx/templates/features/learner_profile/learner_profile.html themes/my-theme/lms/features/learner_profile/learner_profile.html None of these paths worked. How can I do that? -
I recently updated pycharm and now having trouble with django-heroku
I'm getting this error message when I attempt to run the server: "/Users/brandonstockwell/Dropbox_Gmail/Dropbox/mindbrain/mindbrain/settings.py", line 15, in import django_heroku ModuleNotFoundError: No module named 'django_heroku' Process finished with exit code 1 Same thing happens with rollbar. Everything worked fine before I updated. -
How to make AJAX post request in Django
I want to post comment using ajax in Django. I have Message Class related to Post class, and I using PostDetailView to show content of the post and coments. I succeeded to show posted comment on the console. I'm getting error jquery.js:9664 POST http://127.0.0.1:8000/post/39 403 (Forbidden) this is my code views.py class PostDetailView(DetailView): model = Post def post(self,request,*args,**kwargs): if request.method == 'POST': postid = request.POST.get('postid') comment = request.POS.get('comment') # post = Post.objects.get(pk=postid) user = request.user Message.objects.create( user = user, post_id = postid, body = comment ) return JsonResponse({'bool':True}) html(where is corresponds to comment section) {% if request.user.is_authenticated %} <div> <form method="POST" action="" id="form_area"> {% csrf_token %} <input class="form-control mr-sm-2 comment-text" type="text" name="body" placeholder="Write Your message here..." /> <button class="btn btn-outline-success my-2 my-sm-0 save-comment" type="submit" data-post="{{object.id}}" data-url="{% url 'post-detail' object.id %}" > Comment </button> </form> </div> {% else %} script.js function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != "") { var cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie("csrftoken"); function csrfSafeMethod(method) { … -
View decorator @verified_email_required takes user back to original view instead of to the clicked view after verifying email, django-allauth
When a user with an unverified email clicks a link in their profile page to go to a new page ServiceSignupView, they are redirected to verify their email first. Once verified they are redirected again back to the profile view instead of the intended view: @verified_email_required def ServiceSignupView(request): return render(request, 'service_signup.html', {}) My settings.py has the login redirect view set to the profile view, except this is not login redirect, this is verifying the email and clicking the link in the email. LOGIN_REDIRECT_URL = 'profile' How can I get the view to proceed to the ServiceSignupView instead of back to the profile view after clicking the verification link in the django-allauth email? -
prevent django test runner from creating stale table
I have mariadb database that used to have CHARSET utf8 COLLATE utf8_general_ci config but now CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci. All tables have the same CHARSET and COLLATE as those of the database. When I run ./manage.py test, stacktrace looks like this: .... django.db.utils.OperationalError: (1118, 'Row size too large (> 8126). Changing some columns to TEXT or BLOB may help. In current row format, BLOB prefix of 0 bytes is stored inline.') I managed to find out what the troubling table is, and the sql query looks like the following. Note that I changed names of table and fields for security: CREATE TABLE `troubling_table` ( `id` INTEGER auto_increment NOT NULL PRIMARY KEY, `no_tax` VARCHAR(20) NOT NULL, `cd_pc` VARCHAR(7) NOT NULL, `cd_wdept` VARCHAR(12) NOT NULL, `id_write` VARCHAR(20) NULL, `cd_docu` VARCHAR(10) NULL, `dt_acct` VARCHAR(8) NULL, `st_docu` VARCHAR(3) NULL, `tp_drcr` VARCHAR(3) NULL, `cd_acct` VARCHAR(20) NULL, `amt` NUMERIC(19, 4) NULL, `cd_partner` VARCHAR(20) NULL, `nm_partner` VARCHAR(50) NULL, `tp_job` VARCHAR(40) NULL, `cls_job` VARCHAR(40) NULL, `ads_hd` VARCHAR(400) NULL, `nm_ceo` VARCHAR(40) NULL, `dt_start` VARCHAR(8) NULL, `dt_end` VARCHAR(8) NULL, `am_taxstd` NUMERIC(19, 4) NULL, `am_addtax` NUMERIC(19, 4) NULL, `tp_tax` VARCHAR(10) NULL, `no_company` VARCHAR(20) NULL, `dts_insert` VARCHAR(20) NULL, `id_insert` VARCHAR(20) NULL, `dts_update` VARCHAR(20) NULL, `id_update` VARCHAR(20) NULL, `nm_note` VARCHAR(100) NULL, `cd_bizarea` VARCHAR(12) … -
How to gettext from django.contrib.auth
I am working on translate my Django app, But there are some messages text don't appear in django.po like: This password is too common. A user with that username already exists. The password is too similar to the email address. and they from django.contrib.auth i did run django-admin makemessages -l ** Any idea how to fix this? -
Google OAuth2 integration with kiwi tcms
I have followed exact steps on the documentation provided to integrate google OAuth2. From Kiwi github page. social-auth-app-django - extra authentication backends Google sign-in details. https://python-social-auth.readthedocs.io/en/latest/backends/google.html#google-sign-in I have included relevant settings in /tcms/settings/common.py AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "guardian.backends.ObjectPermissionBackend", "social_core.backends.google.GooglePlusAuth", ] SOCIAL_AUTH_GOOGLE_PLUS_KEY = "XXXXXXX-XXXXXXXX.apps.googleusercontent.com" SOCIAL_AUTH_GOOGLE_PLUS_SECRET = "XXXXXXXXXXXXXXXXXXXXX" With above configuration, i am able to runserver and get to localhost page. The UI page doesn't contain expected way of sign in via SSO. Am i missing something? How to get the changes in the kiwi tcms UI like https://public.tenant.kiwitcms.org/accounts/login/?next=/ Or Continue With Google section of sign in.