Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
One client id secret against many users django aouth2
I am using Oauth2 I want to generate one client id and client secret against many users. When i login and generate client id and secret then that is generated against user who is logged in. But my condition is that i want to generate client id and secret against Company Model and using username and password user can access api's. I am very new to Rest API please Guide me. Settings.py OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } -
Django 1.11.4 LOGIN_REDIRECT_URL does not work
I am changing an existing Django app.. MacOS OSX 10.13.6 , Django 1.11.3 The setting LOGIN_REDIRECT_URL apparently has no effect. I am logging in as an admin. What I wanted is to go to a specific page after the user logs in ( instead of admin interface with model links). LOGIN_REDIRECT_URL seems to be ignored. Even if I set it to bogus, there's no error and I end up on Admin page with the links to the models. Maybe I just did not understand the docs about its functionality. The docs states: The URL where requests are redirected after login when the contrib.auth.login view gets no next parameter In the POST request in browser inspect tool I see "next=/login/", I don't know if this is bad and how to get rid of it. There seems to several threads on SO on the subject for older versions of Django, and they did not help. Setting USE_X_FORWARDED_HOST = True does not change the behaviour Setting APPEND_SLASH = True does not change the behaviour Removing "login"-matching entry from urlpatterns list does not change the behaviour. Adding url(r'myapp/admin/',myview) to urlpatterns does not have any effect either. Appending and / or prepending a slash to … -
Allow user to perform signin which required from my Django application within the Ubuntu 18.04 server
I'm working on a Project using Python(3.7) and Django(2) in which I need to authenticate the user against his Azure account to use the resources on his behalf. My application is executing a bunch of az commands to set up a simple infrastructure for the user, so to create any resource users need to login to the Azure portal. Here's how I'm executing the login command using azure.cli.core python package in my django application: cli().invoke(['login']) On my local system, it's just redirecting the user to login to the azure portal in the browser. But now, I have deployed my application to the Ubuntu 18.04 server using gunicorn now when user sends the post request then a statement prints in my server logs which says: To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code HUF793HDD to authenticate. But it's not redirected the user to the login page of azure. How can I achieve this behavior? I have to allow the user to login to his azure account and the rest of the commands in my application will be executed on his behalf. Thanks in advance! -
user logged in conflicting with dynamic url user
user logged in conflicting with the user's dynamic URL. I built the application so that if the user is logged on in navbar it appears his photo and his name with the settings of change register, this in a fixed menu, and it is working, therefore, when I type the url dinamca exemplu petaqui.com/maumaster it goes to that url based on username, and also changes the logged-in profile to the profile it is showing. I would like to use facebook, where I am logged in, but I can see the profile of other users, but when I view these profiles, it changes the user logged in to the profile I visited. views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib import messages from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.template.loader import render_to_string from .tokens import account_activation_token from django.contrib.auth.models import User from django.core.mail import EmailMessage from sistema.tokens import account_activation_token from django.contrib.sites.shortcuts import get_current_site from .models import ( Usuario, Negocio ) from .forms import ( UsuarioForm, NegocioForm ) def profile_detail(request, username): if User.objects.get(username=username): user = User.objects.get(username=username) return render(request, "profile.html", { … -
I want to add a number for every row in this table , html css [duplicate]
This question already has an answer here: Django - iterate number in for loop of a template 2 answers I am creating a Table for an order history and i want to display a number for every row in the Table. <table> <thead> <tr> <th>#</th> <th>Profil</th> <th>Follower</th> <th>Datum</th> </tr> </thead> {% for instance in object_list %} <tbody> <td></td> <td>{{ instance.profile_link }} </td> <td>{{ instance.follower }} </td> <td>{{ instance.date|date:"G:i, d.m.o" }} </td> </tbody> {% endfor %} </table> I want that the empty td prints a incrementing number. -
How can I populate data (from CSV file) into sqlite database using custom management command in Django?
I am trying to read csv file and populate its data into sqlite database.However, when I checked whether the data was inserted, it returns empty "QuerySet []". here is my code: from django.core.management.base import BaseCommand import csv from students.models import Student class Command(BaseCommand): help = 'import data' def handle(self, *args, **options): file = "../students/data.csv" with open(file,newline='', encoding='utf-8') as f: reader = csv.reader(f) for w in reader: created = Student.objects.update_or_create(student_id = int(w[0]), gender = w[1], dob=w[2]) created.save() -
Overwriting the AuthenticationForm class to log in with email
I have an application in django 1.11 and I created a login by email instead of a username. In order to log in using the login form I had to overwrite the AuthenticationForm class and insert an email instead of username. forms.py UserModel = get_user_model() Here I overwritted AuthenticationForm class and change username to email. class AuthenticationForm(forms.Form): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ email = forms.EmailField( label=_("Email address"), max_length=254, widget=forms.EmailInput(attrs={'autofocus': True}), ) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, ) error_messages = { 'invalid_login': _( "Please enter a correct %(username)s and password. Note that both " "fields may be case-sensitive." ), 'inactive': _("This account is inactive."), } def __init__(self, request=None, *args, **kwargs): """ The 'request' parameter is set for custom auth use by subclasses. The form data comes in via the standard 'data' kwarg. """ self.request = request self.user_cache = None super(AuthenticationForm, self).__init__(*args, **kwargs) # Set the label for the "username" field. self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD) if self.fields['email'].label is None: self.fields['email'].label = capfirst(self.username_field.verbose_name) def clean(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') if email is not None and password: self.user_cache = authenticate(self.request, email=email, password=password) if self.user_cache is None: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', … -
Profiling Django-Channels
I've whipped up a proof-of-concept for a multiplayer game with a script to simulate a heavy load, but I'm not quite sure how to see how many streams of data it can handle. For reference I'm sending ~1kb of data every 20ms for realtime multiplayer. I'm trying to determine what kind of load channels can take because I'm currently weighing channels vs nodejs or golang. What's the best way to do this? Maybe average time between WebSocket received and broadcast as a proxy for server performance? So when that drops to some slower value performance is beginning to degrade? -
Success message after parsing keywords in print output in view.py
First of all am very new to coding in general, but have managed to setup an automation website for network devices. Basically am trying to parse an output generated by "print (output)" in view.py for some keywords and if that keyword exist display a success message in my template view.py if request.method == 'POST': hostname = request.POST.get ('host') username = request.POST.get ('username') password = request.POST.get ('password') srcrouting = request.POST.get ('srcrouting') rtsubnet = request.POST.get ('rtsubnet') destrouting = request.POST.get ('destrouting') remote_conn_pre = paramiko.SSHClient() remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) remote_conn_pre.connect(hostname=hostname, port=22, username=username, password=password, look_for_keys=False, allow_agent=False) remote_conn = remote_conn_pre.invoke_shell() remote_conn.send("\n") remote_conn.send("en\n") remote_conn.send(str(password)+ "\n") remote_conn.send("conf t\n") remote_conn.send("ip route" + " " + srcrouting + " " + rtsubnet + " " + destrouting + "\n") remote_conn.send("end\n") remote_conn.send("sh run | s" + " " + srcrouting + "\n") time.sleep(1) route = remote_conn.recv(65535) print (route) context = {'route': route} I want to parse output of the "print (route)" and if it includes something, display a success message. Thanks, -
Django admin: Change the displayed value of a key
i have a model that includes a key "service_id" and the values stored in database are like "10001", i want to add a method to admin page that instead of displaying the id it displays a custom value like "Car Wash". -
Django AutoComplete display related foreign details in dropdown
I'm new to autocomplete in Django 2.0. I have it working however I cant seem to make the django admin change the label_from_instance when using the AutoComplete feature. Does anybody know how to modify the autocomplete_fields lables? Normally without autocomplete my djangoadmin get form would look like the below def get_form(self, request, obj=None, **kwargs): form = super(ChampProductMappingAdmin, self).get_form(request, obj, **kwargs) form.base_fields['sharepoint_product'].label_from_instance = lambda obj: "{} {}".format(obj.product_name, obj.final_publications_product_id) if i use autocomplete_fields = ['sharepoint_product'] it just uses the standard object (ID) label -
Django: Error when saving ZipFile to database through FileField
I'm not really sure how to do this but my hunch is the FileField does not accept a zip file? Although I've read that FieldField is agnostic to file types so I'm not really sure what's wrong here. Error message: AttributeError: 'ZipFile' object has no attribute '_committed' Models.py class UserDownloads(django.db.models.Model): user = django.db.models.ForeignKey( django.contrib.auth.models.User, on_delete=django.db.models.CASCADE, blank=True, null=True, ) file = django.db.models.FileField(storage=S3Storage()) Views.py class DownloadZipFileView(LoginAndPermissionMixin, View): permission_required = 'downloads.view_userdownloads' def get(self, request, *args, **kwargs): files = [] attachments = TaskAttachment.objects.\ order_by('-date_entered').\ filter(user=self.request.user).\ only('file') for attachment in list(attachments): obj = {'file_name': attachment.file.name, 'url': attachment.file.url} files.append(obj) zipped_file = get_zipped_file(files) A = UserDownloads(file=zipped_file, user=self.request.user) A.save() get_zipped_file function def get_zipped_file(files, zip_subdir='attachments'): zip_filename = zip_subdir + '.zip' byte_stream = io.BytesIO() zf = zipfile.ZipFile(byte_stream, 'w') for file in files: filename = file.get('file_name') url = file.get('url') file_response = requests.get(url) if file_response.status_code == 200: f1 = open(filename, 'wb') f1.write(file_response.content) f1.close() fdir, fname = os.path.split(filename) zip_path = os.path.join(zip_subdir, fname) zf.write(filename, zip_path) os.remove(fname) zf.close() return zf -
Getting error while trying to delete a model object in django
def employee_delete(request, id=None): user = get_object_or_404(User, id=id) #user = User.objects.get(id=id) if request.method == 'POST': print(type(user)) self.user.delete() return HttpResponseRedirect(reverse('employee_list')) else: context = {} context['user'] = user return render(request, 'employee/delete.html', context) Error showing while deleting the object using delete() in django 2.1.5 Screenshot of error -
highcharts and django passing a dictionary
I'm trying to structure my data for display in a pie chart. I have a table with Boolean columns: roots, bone, sediment. I can get the data filtered into a dictionary (in views.py): a = Fraction.objects.values('roots').filter(roots=True) b = Fraction.objects.values('bone').filter(bone=True) c = Fraction.objects.values('sediment').filter(sediment=True) dataset4 = {"roots": a, "bone": b, "sediment": c} it is returned 'dataset4': dataset4, In the html highchart code I usually add the data: #views.py dataset4 = Fraction.objects.values('roots') #html <script> Highcharts.chart('container4', { chart: {type: 'pie'}, title: {text: 'Sample Remains'}, credits: {enabled: false}, xAxis: { categories: [ {% for entry in dataset4 %}'C {{ entry.roots }}'{% if not forloop.last %}, {% endif %}{% endfor %} ] }, series: [{ name: 'Botany Records', data: [ {% for entry in dataset4 %} {{ entry.roots }} {% if not forloop.last %}, {% endif %} {% endfor %} ], color: 'green' }] How do I pass the dictionary object rather than a queryset? -
NoReverseMatch at /products/
I'm trying to route between urls. Product is a class that: from django.db import models from django.urls import reverse # Create your models here. class Product(models.Model): title = models.TextField(max_length=20) description = models.TextField(blank=True) price = models.DecimalField(max_digits=20, decimal_places=2, blank=True) summery = models.TextField(blank=True) feature = models.BooleanField(blank=True, null=True, default=True) def get_absolute_url(self): return reverse("product-detail", kwargs={"id": self.id}) and its view is like: def product_list_view(request): queryset = Product.objects.all() # list of objects context = { "object_list": queryset } return render(request, "products/product_list.html", context) html: {% block content %} {% for instance in object_list %} <p>{{ instance.id }} - <a href="{{ instance.get_absolute_url }}">{{ instance.title }}</a></p> {% endfor %} {% endblock %} urls: urlpatterns = [ path('', product_list_view, name='list'), path('create/', render_initial_data, name='product_create'), path('<int:my_id>/', dynamic_lookup_view, name='product-detail'), path('<int:my_id>/delete/', product_delete_view, name='product_delete'), ] this should work but when I runserver and try to see list of products it raise this error: NoReverseMatch at /products/ while I use this method in instances of object list. what is wrong with the #reverse function? -
Django Add multiple dropdown and select value in admin panel
In my extended User model I am trying to add dropdown like feature in admin panel and I understood that if I create ForeignKey relationship then in admin panel I can see the dropdown. But right now I want multiple dropdown, like on click we can select multiple values. I tried creating ManyToMany field but then the widget forces you to select but I am interested in having Select type of feature. I have my UserProfile as: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company_year = models.ManyToManyField(CompanyYear) company_name = models.ManyToManyField(CompanyName) CompanyName has just 1 field of CharType and CompanyYear has 1 field in IntegerType. In admin panel I am trying to do it like: class UserProfileInline(admin.TabularInline): model = UserProfile class UserAdmin(DjangoUserAdmin): inlines = [UserProfileInline] admin.site.unregister(User) admin.site.register(User, UserAdmin) So right now things are working fine but I just want to have this dropdown like feature but I am not sure how to do it -
How to reload a whole queryset from db in django?
I'm running periodic tasks with celery. One such task gets objects from db with by filter: pages = Page.objects.filter(active=True) initially(before starting celery itself) there are 10 such objects in db with active=True. The task executes accordingly when started, on all these 10 objects. from django.db import transaction from celery.task import task from celery import group from .models import Page #@transaction.atomic @task() def check_pages(): #@transaction.commit() pages = Page.objects.filter(active=True) #not updated later g = group(page_check.s(page.id) for page in pages) g() #settings.py app.conf.beat_schedule = { 'run-every-1-second': { 'task': 'tasks.check_pages', 'schedule': 1.0, }, } Now, if I add another Page object with active=True, this is not recognized or filtered in the task(which is already running periodically). I know obj.reload_from_db(). But that is applicable only to reload an object and not a <QuerySet>. I also tried using transaction.commit() with @transaction.atomic. But that stops tasks' execution since transaction doesn't work over multiple workers and tasks. What am I doing wrong here? -
How to pass absolute URI through <a href> tag in HTML/DJango
Is there any way to pass the build_absolute_uri of a page through the tags in HTML? Currently I have my login button in navbar like this: {% url 'students:login' as login_url %} <!-- Login --> <li class="nav-item {% if request.path == login_url %}active{%endif%}"> <a class="nav-link" href="{{ login_url }}" tabindex="-1" aria-disabled="true">Login</a> </li> students>views.py: def login_page(request): login_form = LoginForm(request.POST or None) context = { "login_form": login_form, } next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if login_form.is_valid(): # print(login_form.cleaned_data) username = login_form.cleaned_data.get("username") password = login_form.cleaned_data.get("password") # this part comes from django authentication document user = authenticate(request, username=username, password=password) if user is not None: # print("User logged in admin:", request.user.is_authenticated) login(request, user) if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect("/") else: print("error") error = "Username/Password is incorrect" context["error"] = error return render(request, "students/login.html", context) I want the users to be able to log in from the navbar and return to the page they were in. Hence, I want to pass the build_absolute_uri of the current page. What are the possible options? -
How to write tests for two Order Models
I'm a complete novice to testing, been reading documentation still can't understand how to write specific tests for my models. Essentially the code is currently filling data given the OrderItem's net_price, quantity and tax value - this is all working accordingly in the "Model". But how do I write tests that do the same thing / test cases? class Order(models.Model): order_number = models.IntegerField(default="1", unique=True) sub_total = models.DecimalField(max_digits=6, decimal_places=2, default="0.00") tax = models.DecimalField(max_digits=6, decimal_places=2, default="20.00") total_gross = models.DecimalField(max_digits=6, decimal_places=2, default="0.00") last_updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def calculate_totals(self): ## Addresses point 1 items = OrderItem.objects.filter(order_number_fk=self) sub_total = 0 for item in items: sub_total += item.net_total self.sub_total = sub_total self.total_gross = self.sub_total * (1+(self.tax/100)) self.save() def __str__(self): return str(self.order_number) class OrderItem(models.Model): order_number_fk = models.ForeignKey(Order, on_delete=models.CASCADE, verbose_name='Order Number') order_number_fk.tax = models.IntegerField(unique=True) net_price = models.DecimalField(max_digits=6, decimal_places=2, default="0.00") quantity = models.IntegerField( default=1, validators=[MaxValueValidator(100), MinValueValidator(1)] ) net_total = models.DecimalField(max_digits=6, decimal_places=2, default="0.00") total = models.DecimalField(max_digits=6, decimal_places=2, default="0.00") created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.order_number_fk) def save(self, *args, **kwargs): self.net_total = self.net_price * self.quantity self.total = self.net_total * (1+(self.order_number_fk.tax/100)) super().save(*args, **kwargs) self.order_number_fk.calculate_totals() -
How to resolve 'NoneType' object is not subscriptable
I'm making a simple movie recommender app on django . On views.py it gives the TypeError: 'NoneType' object is not subscriptable on mobjs[:]: views.py for obj in mobjs[:] : texts.append(obj.description) newrow = np.array(obj.array) #print 'enw:',newrow if cnt==0: matr[0]=newrow else: matr = np.vstack([matr, newrow]) titles_list.append(obj.title) cnt+=1 vectorizer = TfidfVectorizer(min_df=1,max_features=ndim) processedtexts = PreprocessTfidf(texts,stoplist,True) model = vectorizer.fit(processedtexts) -
How to fix SQL doing 4 extra queries when using easy_thumbnails in combination with Amazon S3?
I'm setting up Amazon S3 to use as my media server. I use easy_thumbnails for thumbnailing the images. Without Amazon S3, the page does 2 queries to load the page. With Amazon S3 it uses 6 queries for the same page. How can I fix that? -
How to use same tag for different pages in django wagtail
I have created two child pages from index pages, I want to put same tags for those pages , Is there any way? or can anyone give idea to handle blog categories in django wagtail? class JournalIndexPage(Page): intro = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] subpage_types = ['JournalArticleVideoPage','JournalArticleHalfPage' ] class JournalArticleVideoPage(Page): short_description = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('journal_category'), FieldPanel('short_description'), ] parent_page_types = ['JournalIndexPage'] subpage_types = [] class JournalArticleHalfPage(Page): short_description = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('journal_category'), FieldPanel('short_description'), ] parent_page_types = ['JournalIndexPage'] subpage_types = [] -
how to populate data of the models database into dropdownlist in django
i am trying to populate existing data in the database into a dropdownlist where i want just to make the data appear inside the dropownlist. when i run the system it display the below error : DoesNotExist at / testmodel3 matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 2.1.7 Exception Type: DoesNotExist Exception Value: testmodel3 matching query does not exist. it says that the error is at line 14 tmn3 = testmodel3.objects.get(name = tmn) i create class in models.py map the page in the url.py create form create a template create a function in views.py. models.py class testmodel3(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) url.py from django.contrib import admin from django.urls import path from.views import * urlpatterns = [ path('admin/', admin.site.urls), path('', home), ] forms.py from django import forms from .models import * class drodownForm(forms.ModelForm): class Meta: model = testmodel fields = ('name',) home.html <!DOCTYPE html> <html> <head> <title></title> </head> <body> <form method="POST">{% csrf_token %} <table> <tr><td>mouhafazat name:</td> <td> <select name = "dropdwn1"> {% for testmodel in testmodel3name %} <option value="{{ testmodel3.name }}">{{ testmodel3.name }}</option> {% endfor %} </select> </td> <td><input type="submit" value="click" /></td> </tr> </table> </form> </body> </html> views.py from django.shortcuts import render … -
ListAPIView with JSONRenderer returns text/html
Straightforward question, I am using DRF with a class-based view to serve up an API for consumption by Angular. In particular, I want to respond to a GET request with JSON data that Angular can subscribe to: class AuditListAPIView(generics.ListAPIView): queryset = Audit.objects.all() serializer_class = AuditSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = AuditFilter renderer_classes = (JSONRenderer,) The problem is that the content type for the response is "text/html" instead of "application/json". For example: > curl -s -I <host>:8000 | grep "^Content-Type:" Content-Type: text/html Can anyone explain why this is so, and how to address this? -
How to fix "relation does not exist"
I am trying to run existing Django project, but always get the same error After running python manage.py I get error relation does not exist. I am using Django version 1.11.11. I think that there no need to be an error with database, because when I downgrade Django version to 1.8.1, there is no errors and migration is successful. What might be the problem? Traceback (most recent call last): File "C:\Vizia_project\env\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "qa_qagroup" does not exist LINE 1: SELECT (1) AS "a" FROM "qa_qagroup" LIMIT 1 ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "C:\Vizia_project\env\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Vizia_project\env\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Vizia_project\env\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Vizia_project\env\lib\site-packages\django\core\management\base.py", line 327, in execute self.check() File "C:\Vizia_project\env\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Vizia_project\env\lib\site-packages\django\core\management\commands\migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "C:\Vizia_project\env\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Vizia_project\env\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Vizia_project\env\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Vizia_project\env\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Vizia_project\env\lib\site-packages\django\urls\resolvers.py", line 254, in …