Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement only accepting username and token as request in django view and not password?
I have created a custom User model in Django that has username, email, password and some other fields. I am using jwt token which can be acquired from /token after providing valid username and password of a user. I have created a serializer for /authstatus and implemented it's view in views.py. Currently it works only when both username and password are provided with authentication token as header. Is there any way to ask only username and not password from user as a request for /authstatus? Code: Serializer: class AuthSerializer(serializers.ModelSerializer): password = serializers.CharField( required=True, style={"input_type": "password"}, write_only=True ) class Meta: model = get_user_model() fields = ["id", "username", "password", "auth_status"] read_only_fields = ["id"] Any help will be appreciated. Thank you! -
Add general [to all models] queryset method
I can create a new class from models.QuerySet to override a specific model queryset manager, but is it possible to write a method that applies to all models? For example: Every time i need to see the unique values of a variable, i need to write (*using SQLite) list(map(lambda v: v[my_var], qs.values(my_var).distinct().order_by())) But it would be nice to have something like my_queryset.unique_values(my_var) # Returns [value1, value2, value3, ...] Without having to specify it to every model -
How can i make a move button for a site created in django, html and python
How can i make a move button for a site created in django, html and python. To make myself better understood. I want to add the questions in categories. example: test 1 - 5 questions test 2 - 5 questions and so on but when I add the questions, they run one after the other this is the source - https://github.com/akashgiricse/lets-quiz -
TypeError: dispatch is not a function React and Redux
I get an error when I delete some lead(item). It deletes from the database but not from UI and gives this error dispatch is not a function. //lead.js from /action export const deleteLead = (id) => { return (dispatch) => { axios .delete(`/api/leads/${id}/`) .then((res) => { dispatch({ type: DELETE_LEAD, payload: id, }); }) .catch((err) => console.log(err)); }; }; //Frontend file import { getLeads, deleteLead } from "../../actions/leads"; <button onClick={deleteLead(lead.id)} className="btn btn-danger btn-sm"> Delete </button> -
How Do I connect a .tech domain to Heroku
I have entered the heroku apps dns to the .tech CNAME form in the Value box. My domain name worked after 10 minutes, but then it stopped working. Should I wait 24 hours (although the domain name has worked) or is there something I have done wrong? .tech CNAME panel: heroku panel: chrome tab: The only thing I have done is input the Heroku App DNS into the Value input in the CNAME form. Any help would be much appreciated. Thanks -
Django getting error when trying to save AbstractUser model
I want to save this AbstractUser in my model. class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) when trying to save before go makemigrations getting this error django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'members.User.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'members.User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes with reverse accessor for 'members.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'members.User.user_permissions'. members.User.groups: (fields.E304) Reverse accessor for 'members.User.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'members.User.groups' or 'auth.User.groups'. members.User.user_permissions: (fields.E304) Reverse accessor for 'members.User.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'members.User.user_permissions' or 'auth.User.user_permissions why getting this error? how to solve it? I also tried to change model name class GlobalUser(AbstractUser) but getting same error -
RetrieveUpdateDestroy and get_queryset how works
i am learning drf and i little confused in the urls.py i have path('todos/<int:pk>', views.TodoRetrieveUpdateDestroy.as_view()), on the views.py class TodoRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView): serializer_class = TodoSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): user = self.request.user return Todo.objects.filter(user=user) by logic i would add to filter like pk = self.kwargs[‘pk’] to send only one element Todo but it works and send only that ‘id=pk’ post without adding additional filter.Can u explain why please and how works RetrieveUpdateDestroy and get_queryset) -
Why drf add underlines to serialized dictfield?
I use djangorestframework==3.9.4, I can't realize why drf changes serialized data (add underlines to field names before numbers and uppercase) # views.py: class RetrieveUpdateJsonFields(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): queryset = JsonFieldObject.objects.all() serializers = { 'default': JsonFieldRetriveSerializer, 'update': JsonFieldUpdateSerializer, } def get_serializer_class(self): return self.serializers.get(self.action, self.serializers['default']) # serializers.py: class JsonFieldUpdateSerializer(serializers.ModelSerializer): id = serializers.IntegerField() context = serializers.JSONField() class Meta: model = JsonFieldObject fields = ('id', 'context') def validate(self, data): """ for trace """ print(data["context"]) return data I try send put request, that contains next data: { "id":1, "context": { "floor_field": 27, "square2": 222, "oneAs": "Hello" } } in serializer I expected this: {'id': 1, 'context': {'floor_field': 27, 'square2': 222, 'oneAs': 'Hello'}} but got: {'id': 1, 'context': {'floor_field': 27, 'square_2': 222, 'one_As': 'Hello'}} how can I disable this behavior? -
Django Rest Framework serializer nested objects internal server error 500
I have three models like those: class Ambulance(models.Model): ambulance_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ambulance_name = models.CharField(max_length=255) forms = models.ManyToManyField(Form) class Form(models.Model): form_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) form_title = models.CharField(max_length=255) class Page(models.Model): page_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) page_title = models.CharField(max_length=100, default='Untitled Page') form = models.ForeignKey( Form, related_name='pages', on_delete=models.CASCADE, null=True ) And the serializers as follow: class AmbulanceSerializer(serializers.ModelSerializer): forms = FormSerializer(read_only=True, many=True) class Meta: model = Ambulance fields = fields = ['ambulance_id', 'ambulance_name', 'forms'] class FormSerializer(ModelSerializer): pages = PageSerializer(many=True, read_only=True) class Meta: model = Form fields = ['form_id', 'form_title', 'pages'] class PageSerializer(ModelSerializer): class Meta: model = Page fields = '__all__' They were working and give me the nested object that I wanted but after adding many-to-many relationships, it gives me an internal server error 500 and it didn't tell me what the problem was, after debugging I found the problem occurs when calling AmbulanceSerializer(ambulance) or FormSerializer(form) Could someone give me some hint? and what the problem actually! -
Azure AD with Django Rest Framework and React [dj-rest-auth allauth]
I'm trying to integrate Azure AD to an existing Django Rest Framework project. I found dj-rest-auth as a great solution for this purpose. It uses django-allauth. I managed to configure it on my Django project, but I have no idea which is the next step. So for now I have configured: urlpatterns = [ ... path(r'auth/azure', AzureLogin.as_view(), name='azure_login') ] which created a new endpoint with 3 optional parameters: access_token, code and id_token. I have also register an app on Azure Active Directory, but I have no idea how to proceed. Note: I am using React for front-end. -
Django Calendar Recommendation - HTMLCalendar no Weekly View
Disclaimer - New to programming, Python and Django. I have been researching calendar solutions for my Django website and immediately thought that the Python included HTMLCalendar would do what I needed. I have been reading the docs and can't seem to find a formatweek method for viewing a single week. There is formatmonth, formatyear and formatyearpage but no week. :( This is the documentation I have been looking at. Is there a better place? https://docs.python.org/3/library/calendar.html Thanks in advance for any direction. -
How can i get a single object?
Model: class Contacts(models.Model): libId = models.ForeignKey(verbose_name='Библиотека', to=Libraries, on_delete=models.CASCADE) name = models.CharField('ФИО', max_length=257, blank=True) position = models.CharField('Должность/название отдела', max_length=257) phoneNum = models.BigIntegerField('Номер телефона', validators=[MaxValueValidator(79999999999)]) def __str__(self): return self.name Serializer: class ContactsSerializers(serializers.ModelSerializer): class Meta: model = Contacts fields = '__all__' I can get all objects from that model: class ContactsView(generics.ListAPIView): serializer_class = ContactsSerializers queryset = Contacts.objects.all() But how can i get one from user input? -
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.