Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form URL Error :Reverse for 'printReports' with no arguments not found. 1 pattern(s) tried
I am currently running into the above error when trying to access my reportsHome page. It seems to be a problem with the 'HREF' section of the form where the code is href="{% url 'printReports' reports_pk %}" The templates , views and URLs are listed in the below code: reportsHome.html : {% block content%} <h1 style=" text-align: center">Reports</h1> <hr> <br> <div class="list-group"> <a href="#" class='list-group-item active'>Print Single Complex's</a> {% for x in model %} <a href="{% url 'printReports' reports_pk %}" class="list-group-item list-group-item-action" >{{ x.Complex }} Reports</a> {% endfor %} </div> {% endblock %} printPDF.html : <title>PDF Outuput - TrialBalance</title> {% block content%} <h1 class = 'center'>Kyle Database Trial Balance</h1> <br> </div> <br> <br> <div class="table-container"> <table style="width: 100%"> <th >Account</th> <th>Description</th> <th>Debit</th> <th>Credit</th> {% for arr_trbYTD in arr_trbYTD %} <tr> <td>{{ arr_trbYTD.Description }}</td> <td>{{ arr_trbYTD.Account }}</td> <td> {%if arr_trbYTD.Debit > 0%} {{arr_trbYTD.Debit}} {%endif%} </td> <td> {%if arr_trbYTD.Credit > 0%} {{arr_trbYTD.Credit}} {%endif%} </td> </tr> <tr > {% endfor %} <td> <b>Totals</b> </td> <td> </td> {% for xDebitTotal in xDebitTotal %} <td><b>R {{ xDebitTotal }}</b></td> {% endfor %} {% for xCreditTotal in xCreditTotal %} <td><b>R {{ xCreditTotal }}</b></td> {% endfor %} </tr> </table> </div> <br> <br> <br> {% endblock %} Views.py : … -
Combine 2 django models based on multiple columns without using select_related
I have 2 models where both of them contain 2 columns which can be treated as keys and a third column which is the value The goal is to inner join both the models but somehow I'm having trouble doing that I tried following this link but I don't think in my case I would want the columns to foreign key to the other so I can't use "select_related" My Models are as follows: class AssetReturnTs(models.Model): data_date = models.DateTimeField() asset = models.ForeignKey(Asset, on_delete=CASCADE) return = models.DecimalField(max_digits=19, decimal_places=10, null=True) class Meta: db_table = "return" class AssetWeightTs(models.Model): data_date = models.DateTimeField() asset = models.ForeignKey(Asset, on_delete=CASCADE) weight = models.DecimalField(max_digits=19, decimal_places=10, null=True) class Meta: db_table = "weight" I want to do a query such that I join the AssetReturn and AssetWeight on data_date and asset_id The end goal is to then do a weighted sum of the return. Currently I'm querying both separately and converting them to pandas and merging them. It looks like this: asset_return_ts = AssetReturnTs.objects.get_returns(start_date, end_date, asset_list).values(*columns_required) asset_weight_ts = AssetWeightTs.objects.get_weights(start_date, end_date, asset_list).values(*columns_required2) # Convert to df # Use pd.merge() and then compute weighted sum Any solution which reduces 2 separate queries to one and helps compute the weighted sum would be greatly … -
Reorder UserCreationFrom fields from django.contrib.auth and allauth
I am trying to reorder fields in a user sign up form using django.contrib.auth. There seem to be, however, some fields (username, email and password) that I cannot reorder that I think may be coming from django allauth. settings.py ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.UserCreationForm' forms.py class UserCreationForm(UserCreationForm): error_message = UserCreationForm.error_messages.update( { "duplicate_username": _( "This username has already been taken." ) } ) first_name = forms.CharField(max_length=12, min_length=4, required=True, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'})) last_name = forms.CharField(max_length=12, min_length=4, required=True, widget=(forms.TextInput(attrs={'class': 'form-control'}))) email = forms.EmailField(max_length=50, help_text='Required. Inform a valid email address.', widget=(forms.TextInput(attrs={'class': 'form-control'}))) password1 = forms.CharField(label=_('Password'), widget=(forms.PasswordInput(attrs={'class': 'form-control'})), help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label=_('Password Confirmation'), widget=forms.PasswordInput(attrs={'class': 'form-control'}), help_text=_('Just Enter the same password, for confirmation')) username = forms.CharField( label=_('Username'), max_length=150, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={'unique': _("A user with that username already exists.")}, widget=forms.TextInput(attrs={'class': 'form-control'}) ) class Meta(UserCreationForm.Meta): model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',) def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise ValidationError( self.error_messages["duplicate_username"] ) I am able to reorder first and last name fields but these always come below username, email, and password. -
Recording user activity in django?
I have a project in which some user can perform CRUD activities. I want to record who did what and when. Currently, I am thinking of making a model class UserAction(models.Model): user_id = models.CharField(max_length=100) action_flag = models.CharField(max_length=100) class_id = models.CharField(max_length=100) action_taken_at = models.DateTimeField(default=datetime.now()) and making a function that fills my UserAction table. Is there any better way to do this? -
How to queue requests in Django?
I manage a physical locker with Django (DRF). Users fill out a form, authenticate via link sent to their e-mail, authorize via a pin displayed on the locker. My view should handle three cases: If user authenticates and authorizes successfully, pin displayed on the locker is replaced with a generic message and the locker opens. (Already implemented) If the user fails to authorize within 3 minutes, locker pin is replaced with a generic message. If a new authorization request is made by user Foo, while authorization for user Bar is still incomplete, stack the request in a queue and wait for case 1. or case 2. to complete. How can I: Implement a request queue, such that the pin displayed on the locker does not get overridden/replaced when a new request comes in? How can I wait 3 minutes for authorization to be completed before processing the next request? View as is, in case it is useful: if request.method == 'POST': form = ConfirmationForm(request.POST) if form.is_valid(): if pin == form.cleaned_data['pin']: open_bay(jwt_token=jwt[1], pin=pin) display_generic_message(jwt_token=jwt[1]) lock_bay(jwt_token=jwt[1], pin=pin) return render(request, 'static/pages/request-success.html') else: pass else: form = ConfirmationForm() return render(request, 'static/pages/confirmation.html', {'form': form}) -
How to apply paging in Django's formview?
my view.py class Formtestview(FormView): template_name = 'test.html' form_valid(self, form): 'my code to search' => 'result is object_list' page = self.request.GET.get('page','1') paginate = Paginator(object_list, 10) page_obj = paginator.get_page(page) return render(self.request, 'test.html', {'form':self.form_class, 'object_list':object_list, 'page_obj' = page_obj}) As in the code above, input is received through form_valid, paged, and then sprayed on the same html template. Results and paging are also displayed normally, but if you go to another page like ?page=2, only the basic template without all the results is shown. Is there a way to paginate the form and search results in one template? -
How to improve my Django PWA push notification process?
I'm learning to do push notifications in Django PWA -app. I've chosen to use fcm-django library for the job in the back end but I'm unsure about the process and if I'm about to do it correctly. This is how I imagine I would build the process, please correct me if there's something wrong. Please also note that I'm more a back end person and don't know that much of the front end side: Get permission from the user for the notifications in front end (service worker). This is the JS -library I think I'll use for the front end job Get the token in the front end and save it to the database with device and user info. For this I first thought I'd need to build some custom view in my Django back end, but researching more revealed that I can use fcm-django built in classes like FCMDeviceViewSet and FCMDeviceAuthorizedViewSet. Send push messages to the user. This will include custom views and logic in the back end to get the users and send the notifications to them when some criteria is met (for example datetime). I would be really grateful to get some feedback and suggestions if I've … -
Update search content in HTML table in django
I want to update the search content in the HTML table under the column hostname and want to display the IP address of the hostname under IPv4 and IPv6 column this is my views.py from django.shortcuts import render import dns import dns.resolver def index(request): if request.method == 'POST': search = request.POST.get('search') ip_address = dns.resolver.Resolver() IPv4 = ip_address.resolve(search, 'A').rrset[0].to_text() IPv6 = ip_address.resolve(search, 'AAAA').rrset[0].to_text() -
GET request 404 error (not found) this is the error that i am getting when i am calling a file present in same folder
This is the javascript code in which I am using the get method. [This is the directory in which both the files are present, the html file that the js code is part of and also the text file.[][This is the image of the console with errors.[][2]2[2]]3 -
How to get id of selected row in table using javascript
Current student information list is being printed. Then, by selecting the checkbox and clicking the "Add Teacher" button, a function has been added so that the currently logged in name is added to the teacher column. Here, I want to apply an event to all selected rows by passing multiple values to the parameter when multiple checkboxes are selected. I've been looking for it, but I can't find a solution, so please help. urls.py path('student/add_teacher/<int:id>/', views.add_teacher) views.py def add_teacher(request, id): student = Student.objects.get(pk=id) student.teacher = request.user.name student.save() return HttpResponseRedirect(f'/student/') student_list.html <table id="student-list" class="maintable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Register date</th> <th>Select</th> </tr> </thead> <tbody> {% for student in student %} <tr class="text-black tr-hover table-link text-center student" student-id="{{ student.id }}"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.register_date }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <button type="button" class="btn btn-secondary addteacher">Update Teacher</button> student_function.js $(function () { $('button.addteacher').click(function (e) { var elem = $(".maintable input:checked").parents("tr"); var studentID = elem.attr('student-id'); var updateTeacher = confirm("업데이트하시겠습니까?"); if (updateTeacher) { window.location.href = 'student/add_teacher/' + studentID + '/'; } }); }); -
Can i make sfu webrtc in django for live broadcasting of stream to many people ? any source code or tutorial?
I wanna connect upto 10 people in live stream where they are sharing there video and audio with each other. And this stream should be capable to seen by million people on the internet.I wanna make it with django(webrtc), i know about p2p connection, i found some tutorials on net about it but it wasn't efficient for 10 peers(because it uses more cpu). so i wanna use SFU. Your suggestion will be helpful. WebRTC - scalable live stream broadcasting / multicasting -
Difference between groups and permissions on django?
I have 7 roles of users under same user table and these roles have different access and permission. As most of them using same panels, I need to restrict certain functions for certain users and while researching i found that that can be done using two ways: Using groups and assigning the users to certain group and check permission // ( but it cant restrict the url access, it can only restrict model instance access And second: using permission mixins like user_passes_test // and check if the user role type When to use when and where to use which ? Is there any other way of dealing restricting access to certain views ? -
Django - Add authenticator to every endpoint automatically unless otherwise specified
So I have this custom authenticator created and I have over 30 endpoints. For all, but 3 endpoints it requires authentication. So I'm pretty much adding @custom_authenticator to every function or @method_decorater(custom_authenticator) in the case of APIView classes. Is there a way I can automatically add this to endpoints and add a decorator that turns off authentication for specific endpoint functions? For example @donotauth def endpoint(request) then endpoint() won't run the authenticator first. -
replacing token with a value
i am trying to replace token by checking whether the token is valid and then taking out the details using that token . eg: {"jwt":"asdahasjkaiubdkjsdjasdajkdjakdon","hostel":"BCJ bhawan","room_no":"300"......} something like this i will receive how can i replace that token portion with the value in serializer1 but i am unable to merge them together here is my views.py class leaveview(APIView): def post(self,request): token = request.data['jwt'] if not token: raise AuthenticationFailed('Unauthenticated') try: payload = jwt.decode(token,'secret',algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated') user=User.objects.filter(id=payload['id']).first() serializer1=UserSerializers(user) serializer2 = leaveSerializers(data=request.data) serializer2.is_valid(raise_exception=True) serializer=serializer1+serializer2 serializer.save() return Response(serializer.data) models.py class leave(models.Model): name=models.CharField(max_length=100) father_name=models.CharField(max_length=100,null=True) branch=models.CharField(max_length=40,null=True) coer_id=models.CharField(max_length=12,unique=True,null=True) hostel = models.ForeignKey(hostel_manager,on_delete=models.CASCADE) room_no = models.CharField(max_length=10) where_to = models.CharField(max_length=100) reason = models.CharField(max_length=300) start_date = models.CharField(max_length = 100,null=True) end_date = models.CharField(max_length=100,null=True) phone_regex=RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+9999999999'. Up to 12 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17) serializer.py class leaveSerializers(serializers.ModelSerializer): class Meta: model = leave fields = ['id','hostel','room_no','where_to','reason','time_period','phone_number','name','father_name','branch','coer_id'] -
Using order_by date in list
I am building a Blog App and I am accessing different models query and adding them in a single list and I am trying to order_by('-date') in the list. Name date is all same in all models. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) date = models.DateTimeField(auto_now_add=True) class Comment(models.Model): comment_by = models.ForeignKey(User, on_delete=models.CASCADE) post_of = models.ForeignKey(BlogPost, on_delete=models.CASCADE) body = models.CharField(max_length=30) date = models.DateTimeField(auto_now_add=True) class Like .... date = models.DateTimeField(auto_now_add=True) class Dislike .... date = models.DateTimeField(auto_now_add=True) views.py def list_page(request,blogpost_id): post = get_object_or_404(BlogPost, id=blogpost_id) comments = [] for q1 in post.comment_set.all() comments.append(q1) likes = [] for q2 in post.like_set.all() likes.append(q2) dislikes = [] for q3 in post.dislike_set.all() dislikes.append(q3) # Mixing all the lists all_lists = sum([comments,likes,dislikes], []) context = {'all_lists':all_lists} return render(request, 'list_page.html', context) I also tried by adding order_by('-date') But it showed 'list' object has no attribute 'order_by' I tried like .all().order_by('-date') but it was only effecting on query. I will really appreciate your Help. Thank You -
GIF stops animating when element is shown Safari
This is driving me crazy. I'm making a django website and when you click submit on the form, the form goes away and this loading bar with an animation appears. The situation I'm working with is pretty much identical to this https://jsfiddle.net/6t5xsag8/1/ I want to be able to use this on mobile and a lot of my users have iphones so safari will be the default browser used for this. When I hide and show elements, the gif stops moving! function show_loading_bar() { document.getElementById("form").style.display = "none"; document.getElementById("loading-bar").style.display = "flex"; } If I keep the gif on the page and don't hide or change anything, it animates properly. Anybody have any ideas on how to solve this? -
How i can send ajax request in Django with vanilla JavaScript
I want to send 'GET' and 'POST' requests using ajax in Django. I looked few articles but they all were using jquery, I don't know how to use jquery so is there any way I can send 'GET' and 'POST' requests by using plain JavaScript. -
Django - PUT endpoint serializer should ignore missing attributing
so I have this put endpoint def put(self, request): user_uuid = get_uuid_from_request(request) user_obj = User.objects.get(pk=user_uuid) serializer = UpdateUserSerializer(user_obj, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(dict(error=serializer.errors, user_msg=generic_error_message), status=status.HTTP_400_BAD_REQUEST) with the following serializer class UpdateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('given_name', 'middle_name', 'family_name', 'birthdate') if the incoming request has missing values as in request.data ={'given_name':'Tom'} I'd ideally like it to update anything that isn't missing in the current entity. How do I do this? -
Model with foreign keys taking ~90 seconds per query (foreign key model / serializer problem I think)
I'm having trouble with both my serializer and models for a table using foreign keys. I have a view for my Cost table ( see below ) that when I query, I get the following output in about 300-400 ms : [ { "id": 12, "hours1": 10, "hours2": 0, "hours3": 0, "hours4": 0, "date": "2021-07-12", "employee": 14, "job1": 417, "job2": 671, "job3": 671, "job4": 671 }, { "id": 13, "hours1": 8, "hours2": 0, "hours3": 0, "hours4": 0, "date": "2021-07-12", "employee": 10, "job1": 411, "job2": 671, "job3": 671, "job4": 671 } ] The employee, job1, job2, job3, job4 fields are foreign key IDs that I wish to see their main/primary value for (in this case, names!). I've played around with a serializer to achieve this, however, the problem is that it takes about 90 seconds per query and keeps getting longer! [ { "id": 12, "employee": { "employee_name": "Person 1" }, "job1": { "No": "30201" }, "job2": { "No": "N/A" }, "job3": { "No": "N/A" }, "job4": { "No": "N/A" }, "hours1": 10, "hours2": 0, "hours3": 0, "hours4": 0, "date": "2021-07-12" }, { "id": 13, "employee": { "employee_name": "Person 2" }, "job1": { "No": "30101" }, "job2": { "No": "N/A" }, … -
Django restrict other users from editing posts
I have an update view that is working properly. The only issue is currently anyone can edit any post. To solve this issue I implemented the LoginRequiredMixin and UserPassesTestMixin. I believe I have implemented it correctly but any one is still able to edit any post. view: class PostUpdateView(UpdateView, LoginRequiredMixin, UserPassesTestMixin): model = Post form_class = PostFormUpdate template_name = 'update_post.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False -
Trouble selecting drop-down menu selector using AJAX
Currently I'm trying to create a page where my database is updated upon a drop event. More specifically, I have a page with drag-drop capabilities, what I need is anytime I drag and drop a particular div (deal-card) into a another div (stage-column), I need to make update to the database, that represents that "deal" placed in a different "stage". For this project my backend is Django, and up to this point, I'm able to successfully change the basic CharFields on a drop event, though selecting a selector in the drop-down menu has me stumped. As of now I just arbitrarily picked "value" = 3 for the targeted selector, just to see if I could get it to work. Unfortunately, whatever I try, I always get a prompt saying "This field is required". I attached a picture showing this below. Any help would be greatly appreciated! AJAX CODE $(document).one('drop', function(ev){ ev.preventDefault(); var stage_title_path = '#' + el.id + " .stage-title"; var stage_title = $(stage_title_path).html(); $.ajax({ type:'POST', url:deal_card_url, data:{ deal_owner: 'John Doe', deal_address: '745 Amen Street', deal_arv: '150050', deal_repair: '140000', csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(){ $("#id_stage").val("3").change(); } }); }); FORM DROP-DOWN HTML <p><label for="id_stage">Stage:</label> <select name="stage" required="" id="id_stage"> <option value="">---------</option> <option value="1" selected="">New</option> … -
Unable to retrieve the value of the argument passed through the URL
I am trying to learn Django by working on a small project. The website has 3 buttons on the home page (Home.html). Each button represents a type of user. Upon clicking a button, the user is taken to the signup page. In the GET request to the Signup page, a variable named user_type is set based on the value of the button that was clicked on the home page. The variable is passed on to the Signup.html template and is used as a parameter for the POST request. My intention is to use this parameter from the URL in my signup view and set the database field named user_type. But I am unable to retrieve the value of the parameter in the view. I get an empty string when I print u_type. Even though the URL in the browser shows the value of user_type. Kindly help me with this issue. I am also open to trying alternate ways to achieve the same results. view.py from django.shortcuts import render from django.http import HttpResponse from .forms import SpaceUserForm from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required def home(request): return render(request, 'Users/Home.html') def signup(request, u_type=''): if request.method == 'POST': form = SpaceUserForm(request.POST) … -
how to retrieve the token generated while using django allauth and django-rest-auth with django rest framework
I am using django allauth and django-rest-auth from this tutorial to generate a token for django rest framework. The tutorial can be found on this page, at the bottom. (https://www.softcover.io/read/92780ad5/django_book/token_authentication) I am able to generate the token after accessing api/dj-rest-auth/register/, which is the sign up page from the browsable API. Now the issue is that i am on python3 manage.py shell and i am trying to retrieve any of the token generated for either user test001 or test002 does any one know how to do it? I am having a hardtime to achieve it Thanks in advance -
Django Creating a custom user model
Hello i am trying to create a custom user model (that inherit from User) to make the user to put their email rather than usernames, and i am getting an error in settings.py, I have no idea about CustomUser app, but i am trying to figure out if we can include this as an app inside settings.py, the code and traceback: models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class Ticket(models.Model): email = models.EmailField(max_length=255) title = models.CharField(max_length=250) desc = models.TextField(max_length=99999) class RespondToTicket(models.Model): name = … -
django-admin startproject doesn't work (macOS Big Sur)
Able to install and create projects with older version of Django(2.1.5), but with the latest version of Django, I got errors when running django-admin startproject project-name: Traceback (most recent call last): File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/bin/django-admin", line 8, in sys.exit(execute_from_command_line()) File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/core/management/init.py", line 419, in execute_from_command_line utility.execute() File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/core/management/init.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/core/management/commands/startproject.py", line 19, in handle options['secret_key'] = SECRET_KEY_INSECURE_PREFIX + get_random_secret_key() File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/core/management/utils.py", line 82, in get_random_secret_key return get_random_string(50, chars) File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/utils/crypto.py", line 72, in get_random_string return ''.join(secrets.choice(allowed_chars) for i in range(length)) File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/utils/crypto.py", line 72, in return ''.join(secrets.choice(allowed_chars) for i in range(length)) AttributeError: module 'secrets' has no attribute 'choice'