Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In django without using pagination i want to display record page wise
I am trying to do is display record page by page but without using pagination. -
Django - How to hide Server [HTTP Response header] parameter in middleware file?
In my Django application, the following settings ensure that the response headers have the standard key-value pairs enabled. However, the 'Server' name and version information is still visible by default which needs to be hidden (exposed server name and version is an OWASP vulnerability). middleware.py class BrandReputationMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response['X-XSS-Protection'] = "1; mode=block" del response['Server'] # this line of code has no effect. return response Also as suggested in other posts, this middleware.py is declared in the first order of middlewares in settings.py: MIDDLEWARE = [ 'MyApp.middleware.BrandReputationMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] In the above snippet, the idea is not to use del operator but rather to just hide the 'Server' parameter from getting displayed in the response headers, which I am unable to accomplish. -
Django, restricting access to pages
I have various applications in a Django project, but I only want users who are logged in to be able to access those pages. How can I restrict all access to different pages except the login page which is my main page. For instance, mywebsite.com/home/user should be only available to user and if someone types in that it should redirect them to mywebsite.com Currently I have to apps, main and Home, I am using ClassBased views on my Home app how can I restrict access to all my pages except login page and show a message as well? -
Django admin model method field in fieldsets with readonly_fields
i have a model with 2 custom methods class User(AbstractUser): uid = models.CharField( "uid", max_length=255, null=True, blank=True) phone_number = models.CharField( "Phone number", max_length=255, null=True, blank=True) nickname = models.CharField( "Nickname", max_length=255, null=True, blank=True) def eth_address(self): try: wallet = UserWallet.objects.get(user=self, currency=2) return wallet.address except Exception: return None eth_address.short_description = 'eth_address' def evt_address(self): try: wallet = UserWallet.objects.get(user=self, currency=1) return wallet.address except Exception: return None evt_address.short_description = 'evt_address' In order to show custom model methods in admin i need to add the method name to both fields and readonly_fields, which worked great on previous admin models But when i try to use fieldsets with readonly_fields: class UserAdminCustom(admin.ModelAdmin): list_display = ('id', 'email', 'phone_number', 'status', 'created') list_display_links = ('id', 'email', 'phone_number', 'status', 'created') change_form_template = 'admin/backend/user_change_form.html' # verbose_name = "General" # exclude = ('password', 'last_login', 'is_superuser', 'is_staff', 'groups', # 'user_permissions', 'username', 'first_name', 'last_name', 'is_active', 'date_joined', 'eth_private_key', 'evt_private_key', 'modified') inlines = [ UserKycInline, UserWalletInline, UserBankInline, CardBindingInline, TopUpsInline, TransfersInline, WithdrawalsInline, ] fieldsets = ( ('General', { 'fields': ('id', 'uid', 'phone_number', 'email', 'nickname', 'eth_address', 'evt_address', 'created', 'modified',), }), ) readonly_fields = ('eth_address', 'evt_address', ) it return me the following error: Unknown field(s) (eth_address, evt_address) specified for User. Check fields/fieldsets/exclude attributes of class UserAdminCustom. The only way to use model … -
Django app sensitive information in Github
Django app settings.py when uploaded to Github shows secret key, password and other sensitive information about the app. How do you address this? -
Convenient way of using multiple instances of the same Form subclass within a template?
I'm trying to write an application that manages Tasks. One of my requirements is to be able to view a day's tasks and reschedule them, if the user needs to complete this later. models.py: class Task(models.Model): due_date = models.DateField() is_complete = models.BooleanField(default=False) description = models.CharField(max_length=100, blank=True) ## other fields These Tasks are processed by a subclass of DayArchiveView, which uses date_field=due_date and context_object_name=task_list. The resulting template renders each Task as a row in a table. Within this interface, I'd like to provide a way to change the due_date. Because it changes data, a seems to be the best option. My current version uses native HTML mixed into the template: tasklist.html <table> <thead> <tr> <th>Due Date</th> <th>Description</th> <th>Complete?</th> <th>Change Due Date</th> </tr> </thead> <tbody> {% for task in task_list %} <tr> <td>{{ task.due_date }}</td> <td>{{ task.description }}</td> <td>{{ task.is_complete }}</td> <td> <form method="post" action="{% url 'reschedule' %}"> {% csrf_token %} <!--the following field is actually a more complicated dropdown using tempusdominus-bootstrap-4--> <input type="date" name="change_date"> <input type='hidden' name='task_id' value='{{ task.id }}'> <button type="submit">Reschedule</button> </form> </td> </tr> {% endfor %} </tbody> </table> The question I'd like answered is whether there's a good way within a view (CBV or FBV) to pass multiple instances … -
I want make charts in js |
I am looking for bar chart ,for this values , anyone help me, Tanks in advance! ['Year', 'Sales', 'Expenses', 'Profit'], ['2014', 1000, 400, 200,500], ['2015', 1170, 460, 250], ['2016', 660, 1120, 300], ['2017', 1030, 540, ] -
Django how to compute the Percentage using annotate?
I want to compute the total average per grading categories and multiply it by given number using annotate this is my views.py from django.db.models import F gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(grading_Period = period).filter(Subjects = subject).filter\ (Grading_Categories__in = cate.values_list('id')).values('Grading_Categories').annotate( average_grade = Avg * F('Grading_Categories__PercentageWeight') / 100) this is my models.py class gradingCategories(models.Model): CategoryName = models.CharField(max_length=500, null=True) PercentageWeight = models.FloatField() class studentsEnrolledSubjectsGrade(models.Model): GradeLevel = models.ForeignKey(EducationLevel, related_name='grade', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='subject', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='student', on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='category', on_delete=models.CASCADE, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, related_name='period', on_delete=models.CASCADE, null=True, blank=True) _dates = models.CharField(max_length=255,null=True, blank=True) Grade = models.FloatField(null=True, blank=True) For more info: For example the average of Quiz(Grading categories) is 80 and it will multiply with 15(PercentageWeight) Total = 80(Grading_Categories) * 15(PercentageWeight) total=total / 100 The result must be 12 -
We are trying to have authentication based on tokens plus I am confused about tokens in Django libraries
Our project is entirely on Django Rest Framework, so the front-end user interface features of Django are not used. The front-end is on ReactJS. I was told that the built-in authorization creates only 1 token which gives access to everything and without even a refresh token. I'm not sure if this is true. The documentation and reading has led me to that JWT provides refresh tokens only, so seems that this is not in the built-in auth library of django. Also what is the best practice? My co-worker is saying, that we provide a refresh token through JWT, then this refresh token is renewed automatically every 1 hour. We also need to make the login based on email address or phone number, rather than the username as the built-in django auth provides. Is OAth2 really more secure than the built-in django library and JWT? Or is it that only when we want to make our Django server authorize access to our server (does implementing OAth2 as a server on Django makes it like Google or Facebook when they are using OAth2, where they become a 3rd party that authorizes access and login to other websites.) What shall we do? -
Python Pandas Groupby - No objects to concatenate
I have a Dataframe with following values: df = route stop_code stop_name 900 92072 Eastbound @ 257 Kingston Road East 900 1590 Kingston Westbound @ Wicks 900 2218 Kingston Eastbound @ Wicks 900 93152 Salem Northbound @ Kingston 92 728 Kingston Rd. @ Salem Rd. 224 92071 Salem Southbound @ Twilley 215 92071 Salem Southbound @ Twilley 215 92054 Northbound @ 133 Salem 224 92054 Northbound @ 133 Salem 215 93152 Salem Northbound @ Kingston What I want is to group routes by stop_code or stop_name, something like: df2 = route stop_code stop_name 900 92072 Eastbound @ 257 Kingston Road East 900 1590 Kingston Westbound @ Wicks 900 2218 Kingston Eastbound @ Wicks 92 728 Kingston Rd. @ Salem Rd. 224, 215 92071 Salem Southbound @ Twilley 215, 215 92054 Northbound @ 133 Salem 215, 900 93152 Salem Northbound @ Kingston I tried to do the following: df2 = df.groupby(['stop_code']).agg(set).reset_index() while it did work fine in my test environment, when I deployed it in Django (Python Anywhere), I got the following error (maybe due to different versions of Pandas / Python / Django): ValueError: No objects to concatenate can anyone please guide me sort it out? TIA -
Deploying django app to digital ocean unsuccessful (502 Bad Gateway)
Good day guys, I am in a bit of a mess here with deploying a Django app to the digital ocean using Gunicorn and Ngnix. I am following the steps in a video tutorial I bought on udemy, where we are following a link https://gist.github.com/bradtraversy/cfa565b879ff1458dba08f423cb01d71#disable-root-login. while following the tutorial, everything worked to the point before I set up gunicorn, which means I was able to see the website through the IP address. but, only that the static files were not handled by Nginx and I was running the server using python manage.py runserver 0.0.0.0:8000 when I was at this point https://gist.github.com/bradtraversy/cfa565b879ff1458dba08f423cb01d71#run-server. when I followed the step and configured gunicorn and Nginx, I was getting 502 Bad Gateway when I visited using the IP address. I was wondering why I was getting this issue, and I noticed that when I checked the status of gunicorn using sudo systemctl status gunicorn.socket I was getting: gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: failed (Result: service-start-limit-hit) since Fri 2020-02-28 03:03:11 UTC; 7s ago Listen: /run/gunicorn.sock (Stream) here is a link to the project I was trying to add to the server if needed https://github.com/opeodedeyi/medxFinal please I really need help. -
campaign_name = models.ForeignKey(Campaign, on_delete=models.CASCADE)
class Campaign(models.Model): id = models.AutoField(primary_key=True) campaign_name = models.TextField() class SessionLog(models.Model): date = models.DateField() campaign_name = models.ForeignKey(Campaign, on_delete=models.CASCADE) ERROR FROM WEBSITE: OperationalError at /admin/session/sessionlog/ (1054, "Unknown column 'session_log.campaign_name_id' in 'field list'") WHAT I AM TRYING TO DO: create a drop-down list on SessionLog to populate campaign_name based on entries in Campaign. I am new to asking questions. Please be kind if I have explained myself wrong. -
Access Django through model extra fields in m2m_changed signal handler
Let's say I have the following Django models, which represents a sorted relationship between a Parent and Child: class Parent(models.Model): name = models.CharField(max_length=50) children = models.ManyToManyField("Child", through="ParentChild") class Child(models.Model): name = models.CharField(max_length=50) class ParentChild(models.Model): class Meta: constraints = [ models.UniqueConstraint(fields=["parent", "child"], name="uc_parent_child"), models.UniqueConstraint(fields=["parent", "sort_number"], name="uc_parent_child"), ] parent = models.ForeignKey(Parent, on_delete=models.CASCADE) child = models.ForeignKey(Child, on_delete=models.CASCADE) sort_number = models.IntegerField() def save(self, *args, **kwargs): exising_sort_numbers = self.parent.parentchild_set.values_list( "sort_number", flat=True ) if self.sort_number in exising_sort_numbers: raise Exception(f"Duplicate sort number: {self.sort_number}") super().save(*args, **kwargs) Now if I create the relationships using the through model, I get the exception for a duplicate sort_number: ParentChild.objects.create(parent=parent, child=child1, sort_number=0) ParentChild.objects.create(parent=parent, child=child2, sort_number=0) # raises Exception However, if I create the relationships using the .add method, I don't get the exception: parent.children.add(child1, through_defaults={"sort_number": 0}) parent.children.add(child2, through_defaults={"sort_number": 0}) # does NOT raise Exception I know using the .add method doesn't call the .save method on the through model so I need to use the m2m_change signal to run this logic. But I'm not sure how to get the sort_number within this signal. Here's the code I have for the signal so far: @receiver(m2m_changed, sender=Parent.children.through) def validate_something(sender, instance, action, reverse, model, pk_set, **kwargs): if action == "pre_add": for pk in pk_set: child = … -
Can't migrate Django project in new database
I just created a new database for my Django project. When I did the first round of migrate, I got the error: File ".../lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 784, in get_db_prep_value value = self.get_prep_value(value) File ".../lib/python3.6/site-packages/django/contrib/gis/db/models/fields.py", line 186, in get_prep_value obj = GEOSGeometry(obj) File ".../lib/python3.6/site-packages/django/contrib/gis/geos/geometry.py", line 715, in __init__ raise ValueError('String input unrecognized as WKT EWKT, and HEXEWKB.') ValueError: String input unrecognized as WKT EWKT, and HEXEWKB. I suspect it's related to this GeoDjango model field: from django.contrib.gis.db import models as geomodels class image(models.Model): ... location = geomodels.PointField(null=True, blank=True) ... I can't figure out why it's not working when it worked fine before the database change. The postgis extension has been created in the database. I tried assigning a default value to the field with no change. Am I missing a step in setting up the database? What else could trigger this error? -
Django INSTALLED_APP Resolving to "ModuleNotFoundError"
The pip module Im using needs to be listed included in installed apps as such: INSTALLED_APPS = [ ..., 'django_apscheduler', ... ] But I keep getting the following when I build my app: ModuleNotFoundError: No module named 'django_apscheduler' Even though the app is clearly listed in my pip list. The module in question is Django APScheduler. -
Adding arguments to Django include('django.contrib.auth.urls')
I am trying to add an additional argument to my Django default password reset which is mysite.com/password_reset. I am trying to make it look like: mysite.com/user/password_reset.Right now I am using this method: Code for home.html(Contains password change link) <li><a href="{% url 'password_reset' user.username %}">Change Password</a></li> My app/urls.py: path('<str:username>/', include('django.contrib.auth.urls')), This is the Error I am getting: NoReverseMatch at /test3-b Reverse for 'password_reset' with arguments '('test3-b',)' not found. 1 pattern(s) tried: ['password_reset/$'] Thanks in advanc! -
Many to Many relationships in template
Good day guys, im new to django im having in many to many relationship display in template How can display this into a normal list.. from . QuerySet User: webadmin, User: kim, User: sem, User: quinito, User: user1 to. webadmin kim sem quinito user1 Here's my code model.py class ListOfUser(models.Model): users = models.ManyToManyField(User, verbose_name='List of User') views.py def listofusers(request): userlist = ListOfUser.objects.get(id=1) form = ListofUserForms() context = { 'form': form, 'userlist': userlist } return render(request, 'listofusers.html', context) template <p>{{userlist.users.all}}<p> -
django - how to download uploaded files ..not able to download on localhost
Hello I am trying to download a files that I uploaded in my django project. In the List of files available for download, I am storing the url column as a FeildFile object as follows: `>>> File.objects.all() <QuerySet [<File: bvbv>, <File: test-shsh>, <File: gsdsgdsg>, <File: vbvbv>, <File: bnbn>]> >>> file = File.objects.all()[0] >>> file <File: bvbv> >>> file.url <FieldFile: files/contents/test.docx> >>> ` When I construct the links in my view I get then of the form http://localhost:8000/files/files/contents/test.docx instead of http://localhost:8000/media/files/contents/test.docx This is not allowing me to download the files. Any clews Here is my code snippet: settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CRISPY_TEMPLATE_PACK = 'bootstrap4' MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.Home.as_view(), name='home'), path('upload/', views.upload, name='upload'), path('files/', views.file_list, name='file_list'), path('file/upload/', views.upload_file, name='upload_file'), path('files/<int:pk>/', views.delete_file, name='delete_file'), if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) file_list.html <td>{{ file.url }}</td> <td> <a href="{{ file.url }}" class="btn btn-primary btn-sm" target="_blank"> Download File </a> </td> -
Is it possible to use objects created in other forms in Django?
I have a form to create a trip. In this form, you have to choose a client, outbound_flight, inbound_flight and a hotel. Is it to possible to let the user, who is using the trip form, create any of those objects in another form respective to each model, and then automatically bring the object created to the trip form? -
Using Django REST and React Frontend with an external SQL DB. On form submit, need to populate API and also push same data to a stored proc
First up, I know I'm going about this the wrong way, but the SQL database is an existing project so I have to use that right now, and I'm just building this API and Frontend around it as a way to convince the higher ups to get us proper training. Ideally I'd do this from scratch in Django, but I don't have a choice right now. So, where I'm at right now is I have the SQL DB listed in the django settings, and that's all fine. I have some (enough for testing) of the form built, and the data from the form will populate the API: class TodoView(viewsets.ModelViewSet): serializer_class = TodoSerializer queryset = Todo.objects.all() Somewhere along the line (I'm learning as I go (badly)) I found a way to intercept the form data on submit, and call my stored proc. I've absolutely zero doubt there's a better way to do this, but here we are: class TodoView(viewsets.ModelViewSet): serializer_class = TodoSerializer queryset = Todo.objects.all() def dispatch(self, request, *args, **kwargs): if request.method == 'POST': body = json.loads(request.body) title = body['title'] desc = body['description'] owner = body['owner_lan'] sme = body['sme_lan'] etc **stored proc stuff** return super(TodoView, self).dispatch(request, *args, **kwargs) else: return super(TodoView, … -
Django If statement with boolean fields not working
I'm getting the boolean value from a queryset like this: activo = Carros.objects.all().values_list('is_active', flat=True).filter(nombre='carro') then my if statement is this: if activo == True: raise forms.ValidationError('El Auto está activo') even though the variable 'activo' gets a True value it does not return the ValidationError. What I did was to set a variable a = True and then add it in the if statement if activo == True: raise forms.ValidationError('El Auto está activo') And it works. In the Python shell whenver I excute the query I see the result lik this <QuerySet [True]> I'm not sure what is the problem. the 'is_active' field in the model: is_active = models.BooleanField(blank=False, null=False, default=True) Note: DB is Postgresql -
Django FileField upload link for detailview?
My 2nd question of the day, loosely related to the first (trying to accomplish same thing in different ways), so bear with me as I learn stuff! lol My Django app allows me to upload a a FIT file, which is cycling data that contains several thousand rows of data in a ride file. What I'm hoping to accomplish is opening a detailview in which the file is analyzed with graphs and metrics (that's the easy part!). Is there a way to call on the object's url in the detailview class? In the snipped below, I have the detailview class, the model is just comprised of the FileField object and then the last portion is code which I use to parse this type of file. I've done a lot of searching and I haven't seen anything like this, but there's always someone who knows! class FitFileDetailView(DetailView): model = FitFiles fitfile = FitFile(insert location of file associated with object) -
django image ,guidance needed please
i just want to know if there is an image viewer framwork or something so i can display it in my and template and have the functionalities like zoom scroll ..etc ? i will add a randon django code in here with no reason , because i can't post my question from django.shortcuts import render from django.db.models import Q from django.views.generic import TemplateView,ListView # Create your views here. def search(request): template='categories.html' query=request.GET.get('q') results=Gigposter.object.filter(Q(title__icontains=query)) -
Bootstrap table formatting wrong in Chrome but correct in Firefox
I have a bootstrap table which is formatted completely correctly in Firefox but is all thrown to the right on Chrome. Any ideas? Firefox: Chrome: I originally thought it might be something to do with it being within a table-responsive div but I removed that and it made no difference. Here's the HTML: <div class="row"> <div class="col"> <table class="table"> <tr> <th class="col-1 text-center"><input class="form-check-input position-static" type="checkbox" id="checkAll" value="option1"></th> <th class="col-2"><a class="text-body" href="?page={{ contacts.number }}&order_by=displayName">Name</a></th> <th class="col-3 d-none d-lg-table-cell"><a class="text-body" href="?page={{ contacts.number }}&order_by=companyName">Organisation</a></th> <th class="col-3 d-none d-lg-table-cell"><a class="text-body" href="?page={{ contacts.number }}&order_by=jobTitle">Job Title</a></th> <th class="col-1 d-none d-md-table-cell"><a class="text-body" href="?page={{ contacts.number }}&order_by=profession">NSO</a></th> <th class="col-1 d-none d-lg-table-cell"><a class="text-body" href="?page={{ contacts.number }}&order_by=lastModifiedDateTime">Last Updated</a></th> <th class="col-1">Profile</th> </tr> {% if contacts %} {% for contact in contacts %} <tr> <td class="col-1 text-center"><input class="form-check-input position-static" type="checkbox" id="blankCheckbox" name='selected_contact' value={{ contact.per_contact_id }}></td> <td class="col-2"><a href="mailto:?bcc={{ contact.emailAddresses.0.address }}" class="text-primary">{{ contact.displayName }}</a></td> <td class="col-3 d-none d-lg-table-cell">{{ contact.companyName }}</td> <td class="col-3 d-none d-lg-table-cell">{{ contact.jobTitle }}</td> <td class="col-1 d-none d-md-table-cell">{{ contact.profession }}</a></td> <td class="col-1 d-none d-lg-table-cell">{{ contact.modified }}</td> <td class="col-1"><button name="submit_button" type="submit" class="btn btn-link text-success noline" value={{ contact.per_contact_id }}>View</button></td> </tr> {% endfor %} {% endif %} </table> </div> </div> -
Virtual Environment's Activate Does Nothing
I searched a lot for the solution to this issue but I guess fewer people are having the same problem as mine. So, I switched to my new laptop and tried to install VirtualEnv on the latest version of Python. Even though it is successfully installed, when I create a new virtual environment and try to activate it, it switches to a new line as nothing has happened. I checked the folder, I'm entering the right path, it's not in "bin" folder. I'm not sure what's causing the problem. I have to note that I'm on Windows and I'm not using PowerShell. any ideas? P.S. Please note that I know that it must show the VirtualEnv's name in parenthesis but unfortunately, it doesn't.