Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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' -
django 3.2- error creating superuser in sqllite3
PS C:\Users\Abdulla Zia\PycharmProjects\EnhanceImage> python manage.py createsuperuser Username (leave blank to use 'abdullazia'): admin Email address: Password: Password (again): Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 157, in handle validate_password(password2, self.UserModel(**fake_user_data)) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\auth\password_validation.py", line 44, in validate_password password_validators = get_default_password_validators() File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\auth\password_validation.py", line 19, in get_default_password_validators return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\auth\password_validation.py", line 30, in get_password_validators validators.append(klass(**validator.get('OPTIONS', {}))) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\auth\password_validation.py", line 174, in __init__ with gzip.open(password_list_path, 'rt', encoding='utf-8') as f: File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\lib\gzip.py", line 57, in open raise TypeError("filename must be a str or bytes object, or a file") TypeError: filename must be a str or bytes object, or a file performed all the migrations still getting this error. I've deleted database file and created new one still getting the same error. server is up and in running without any errors -
Django random css names
I want the background color to change every time with Django. For example: bg-success, bg-primary, bg-light, bg-dark... etc. and just randomly. How can I do? <div class="bg-success"> </div> -
passing a tuple in a Google charts table using Django
Good afternoon everyone, I am implementing Google Charts API in my Django project. I would like to draw two different charts, a pie chart and a table chart. I am able to display the Pie chart without problems. However, I am having trouble with the table chart. I am passing a tuple to the data.setCell() method. When I do that the table chart does not render. Hereunder is the code that I wrote: function drawTable() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Company Name'); data.addColumn('number', '52 week high'); data.addColumn('number', '52 week low'); data.addRows(5); {% for company in data_cell|safe %} data.setCell(company); {% endfor %} // data.setCell(0, 0, 'John'); var table = new google.visualization.Table(document.getElementById('table_div')); table.draw(data, {showRowNumber: true, width: '50%', height: '50%'}); google.visualization.events.addListener(table, 'select', function() { var row = table.getSelection()[0].row; alert('You selected ' + data.getValue(row, 0)); }); } data_cell is a variable that contains a list of tuples and it is part of the context dictionary in my views.py file. As follows you can find an example; ('Facebook', 384.33, 244.61) I have tried looping through the list of tuples without the safe method and it does not work. Any hints? -
Is escapejs filter is enough for public submitting fields like blog?
Is escapejs filter is enough for public submitting fields like blog? I am using escapejs and escape filters to protect fields from XSS attacks. -
What's an alternative to webapp2?
I am working with an old python2 code that used webapp2 module but I need to build an app for app engine flex environment that uses python3, so I am thinking of using an alternative package to webapp2, can someone please suggest a simple to use alternative to webapp2 that works with python3 and does exactly same thing? Thanks in advance! -
How to pass Django context variables into JavaScript function?
I have a function in Django views.py which passes a context variable called "queues" into an HTML page. In the HTML page, I have a button where if I click it, it should pass the context variable "queues" into a JavaScript function func. However, as shown in the image attached, I see some errors with the way I am doing this. What is the correct syntax to do this? HTML code -
DateTimeInput() widget putting a random T in between Date and Time, causing ValidationError
I have a datetimefield, which I am inputting data using the following form field: delivery_pickup = forms.DateTimeField(label = "Delivery or Pickup Appointment", required = False, widget=forms.DateTimeInput(attrs={'type':'datetime-local'})) A nice little datetime widget appears automatically due to the type attribute declaration. The problem is when I try to submit using the widget, I get an error, and when I remove the widget and look at the input as a simple string, it includes a random T in between the date and the time, like so: 2021-09-26T13:17 Removing the T manually causes the error to go away. What's the best way to remove the T? Is it by formatting the string within the input field? Creating a clean method? Some other technique? Any help is appreciated. -
Annotations multiplication with filtering on many to many relationship
I have models: class Tag: name class User: tags = M2M to Tag ... class Bill: id tags = M2M to Tag ... class BillRow: bill = FK to Bill, related_name='rows' quantity ... And I want for an User filter the Bills on Tags and annotate with some aggregates, for example Count of rows, Sum of quantity... Bill.objects.filter(tags__in=user_tags).annotate(row_count=Count("rows")) The problem is that if User and Bill have more tags in common (some User U1 has user_tags ['T1', 'T2', 'T3'] and some Bill B1 has ['T2', 'T3', 'T4']) the resulting query is using an inner join on the Tag table for the filter and it duplicates in this example the row_count annotation, because for each row of B1 there are 2 joined rows (for both of the shared tags) which satisfy the condition. Is there some solution for this type of annotation specifically in Django ORM, but more broadly what would be the optimal approach in SQL to obtain the correct results? -
Server Error 500 while authentication | Django
Having server error 500 when trying to save user record and authenticating him to the dashboard. CODE user_id = 5 unique_username = "kashif" user = User.objects.get(pk=user_id) user.unique_username = unique_username user.is_active = True useremail = user.email user.save() user = auth.authenticate(request, email=useremail, password=password) auth.login(request, user) return redirect('home') EROOR Server Error (500) CODE EXPLANATION In above code, user email is already stored in database. Also, Django default login from username is overridden with Email. So here, getting username from user and from already stored email and password and then authenticating user. But having error on authentication line. NOTE Project is uploaded at app.barter.monster -
Has many categories without duplicates across parent
I have three models class Offer: class OfferBonus: offer_bonus_category = models.ManyToManyField(OfferBonusCategory) offer = models.ForeignKey(Offer, on_delete=models.CASCADE, blank=True, null=True) class OfferBonusCategories: category_title = models.CharField(max_length=60,null=True, blank=True) category_description = models.TextField(null=True, blank=True) Each offer may have multiple OfferBonuses and each OfferBonus may have multiple OfferBonusCategories. Offer 1 may have one bonus in Categories A and B and another bonus in categories C and D. Offer 1 cannot have an OfferBonus in both A and C and another OfferBonus in B and C. The existence of the first OfferBonus in A and C would prevent a subsequent OfferBonus added in A or C when adding in the Admin interface. So my question is how to restrict the OfferBonus so that it considers the other records within the Offer so that each OfferBonusCategory can only be used once across all OfferBonus. Is there a way to do this out of the box in Django Admin where the displayed Categories would be disabled on subsequent addition of records? If it needs to be custom, could you please direct me to the "right path"? I am new to Python and Django so I'm not sure what to search for. -
django accent caracter in field
I want to add an accent to my field name . if I do it django w'ill considerated as another field .enter image description here