Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NameError at /model/detect/
I am creating a Django project with one app for the moment. I have created a view inside the app and have tried to add url.py file inside the app folder. Secondly, I have also referenced the url.py file to the url.py file of the Djano Project. Now when I start the server and try to access the view from the browser I get the following error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/model/detect/ Django Version: 1.8 Python Version: 3.7.6 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'model') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/handlers/base.py" in get_response 119. resolver_match = resolver.resolve(request.path_info) File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/urlresolvers.py" in resolve 368. sub_match = pattern.resolve(new_path) File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/urlresolvers.py" in resolve 368. sub_match = pattern.resolve(new_path) File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/urlresolvers.py" in resolve 240. return ResolverMatch(self.callback, args, kwargs, self.name) File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/urlresolvers.py" in callback 247. self._callback = get_callable(self._callback_str) File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/urlresolvers.py" in get_callable 106. mod = import_module(mod_name) File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/importlib/__init__.py" in import_module 127. return _bootstrap._gcd_import(name[level:], package, level) File "/home/nauyan/Desktop/EsperSolutions/SystemCodes/March2020/Face_Recognition_Django/model/views.py" in <module> 5. base_path=os.path.abspath(os.path.dirname(__file__))) Exception Type: NameError at /model/detect/ Exception Value: name 'os' is not defined Url.py file of App is: from django.conf.urls import include, url urlpatterns = [ url(r'^detect/', 'model.views.detect', name = 'detect'), ] Urls.py file of Django … -
How to pass uidb64 and token to email template from custom form in Django
I have a Django app, and I want to make a password restore page. I have custom form, which inherits from PasswordResetForm. PasswordResetForm can pass uidb64 and token to emails/restore.html by itself, but how to do this by myself in my custom form? Now Django says me: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. 1 {% autoescape off %} 2 http://{{ domain }}{% url 'Authentication:password_reset_confirm' uidb64=uid token=token %} 3 {% endautoescape %} because I did pass nothing to the params. How do i pass the uidb64 and token? forms.py from django import forms from django.contrib.auth.forms import User, PasswordResetForm, SetPasswordForm ... class RestoreForm(PasswordResetForm): email = forms.EmailField(required=True) class Meta: model = User fields = ["email"] views.py def request_restore_password(request): if request.method == 'POST': form = RestoreForm(data=request.POST) if form.is_valid(): form.save(from_email=AdminEmail, email_template_name='emails/restore.html', request=request) return HttpResponse('123 for now') else: form = RestoreForm() return render(request, 'request_restore_password.html', {'form': form}) emails/restore.html {% autoescape off %} http://{{ domain }}{% url 'Authentication:password_reset_confirm' uidb64=uid token=token %} {% endautoescape %} -
I can't use django with python 3.7
My original python version is 3.6.9 >> I have installed 3.7 manually >> then I tried to use pipenv to create a virtual environment >> pipenv --python 3.7 every thing was fine until I tried to install django, I had this error and I don't know how to deal with it. ERROR: ERROR: Could not find a version that matches django If I created my virtual environment using python 3.6, every thing works just right. image of the error -
Chartjs draw line chart where line go back and forth (by chronological order)
So I want to draw a line chart where the line goes from point to point by chronological order but points can go back and forth so the line would have to go all directions not only right. I don't really know if this is possible but I haven't find any solution so far. I initialize a new line chart with null data and I pass through ajax a list of players (datasets) and each of them has a list of points with x and y in chronological order. For example: Data: [Player 1: [0,1][3,5][1,2], Player 2: [2,5][1,0]] I am now able to draw all the points to each dataset but the line follows the xaxis label order and not the one which I inserted the points. My code is the following: data.players.forEach( function(a, i) { console.log(a); chart.data.datasets.push({ label: a, data: [null], backgroundColor: get_color(i).background, borderColor: get_color(i).border, borderWidth: 3, fill: false, showLine: true, pointStyle: get_shape(i), pointRadius: 5, spanGaps: true }); data.default[i].forEach( function(e, j) { console.log(e); chart.data.datasets[i].data[e[1]] = e[0]; }); }); chart.update(); Hope someone knows how to solve it in case it is possible or maybe suggest another tool where it can be possible. Thanks and sorry for my english! -
'password1': None – password is always None on registration in Django UserCreationForm
I have been developing my project for several months. Registration has been working perfectly, but at some point it stopped accepting the password: the password is always saved as None and the user is saved into the database with password not set. I did not change anyhow either the form or the view working with sign-up, so I don't know where it comes from. My code is: forms.py class UserSignUpForm(UserCreationForm): username = CharField(max_length=35, required=True}) email = UnicodeEmailField(required=True) password1 = CharField(max_length=35, required=True, widget=PasswordInput) captcha = ReCaptchaField(error_messages={'required': 'Prove you are not a robot.'}) class Meta: model = User fields = ('username', 'email', 'password1') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self.fields['password2'] views.py class UserSignUpView(generic.CreateView): form_class = UserRegistrationForm template_name = 'accounts/registration.html' def form_valid(self, form): form.cleaned_data['password'] = form.cleaned_data.pop('password1') form.cleaned_data.pop('captcha', None) user = User.objects.create_user(**form.cleaned_data) ... return HttpResponseRedirect(reverse('account_activation_sent')) templates.py <div class="password"> <label for="{{ form.password1.id_for_label }}">Password</label> </div> {{ form.password1.errors }} {% render_field form.password1 placeholder="Enter your password" class="text-pass" %} My User model: class User(AbstractUser): username = CharField( max_length=150, unique=True, validators=[CustomUsernameValidator()],) email = UnicodeEmailField(blank=True) id = AutoField(primary_key=True) uid = UUIDField(default=uuid.uuid4, editable=False) email_confirmed = BooleanField(default=False) is_active = BooleanField(default=False) last_movie_seen = CharField(max_length=150, blank=True) associated_user = OneToOneField(AssociatedUser, on_delete=CASCADE, null=True, blank=True) The question is: why form.cleaned_data['password1'] always returns None and the user is … -
Django, RestAPI, Microsoft Azure, website, virtual machine, ubuntu
is there any chance somebody could point me in good direction in this problem: I have developed website and restapi using django and djangorestapiframework. On local machine they are working perfectly so my next step is trying to publish it on remote server. I chose microsoft azure (for some weird reasons and i cannot change it). I created a virtual machine with ubuntu server 18.04, installed everything to run my project there. While i run it locally on virtual machine it's working perfectly, at localhost:8000 my websiste and rest-api is showing. Now i want it to publish to the world so it can be accessed under IP of my virtual machine (azure) or some different addres so everybody can access it. I was looking through azure tutorials on microsoft website and google, but i cannot find anything working (I know i am really bad person at this). I don't want to use their microsoft webapp solution or windows server. It's need to be working with Ubuntu on virtual machine from Azure. Is it possible to do and if yes then how? Thank you a lot for your time and help :) BR, Me -
Django one database per user or one in general?
I'm currently writing a chat-application for my Website and storing all the Messages in one database, by referring to sender and receiver with a Foreign-key. Is this really the smartest Idea? I think the site could become slow when everybody is trying to access the same database or when the number of sent messages gets big. Would it be smarter/faster, to use one database per user, storing his/her messages there? If yes, am i right that this is not really possible to achieve this with Django? Thanks for your Answer! -
Querying Multiple Database on the same server with same table structure
I have a specific problem where I have to query different database to show results in dashboard. The tables that I have to query in those db are exactly same. The number of database can be max 50 and minimum is 5. NOTE: I can't put all the data in same database. I am using postgres and django. I am not able to understand how to query those database to get data. I also need to filter and aggregate and sort the data and show 10 - 100 results on the search query params. APPROACH that I have in mind Loop through all database and fetch the data based on the search params and order it by created date. After that take 10 - 100 results as per search params. I am not able to understand what should be the correct approach and how it should be done considering speed and reliability. -
How to embed matplotlib graph/figure on django
Can someone tell me how to embed matplotlib or send matplotlib graph from django views to the template?. I already try searching for the example code and still noone work or the code i copy is outdated. Then i try code like this one from django.shortcuts import render from django.http import HttpResponse, JsonResponse import matplotlib.pyplot as plt import io import numpy as np import urllib import base64 # Create your views here. def index(request): plt.plot(range(10)) fig = plt.gcf() buf = io.BytesIO() fig.saveFig(buf, format='png') buf.seek(0) string = base64.b64encode(buf.read()) uri = urllib.parse.quote(string) return render(request, 'home.html', {'data': uri}) and for the html code {% extends 'base.html' %} {% block content %} <h1>Hello</h1> <img src="data:image/png;base64,{{ data }}" alt=""> {% endblock %} when i run that code error message "'Figure' object has no attribute 'saveFig'" pop up on the browser. Maybe someone can help me to fix this code or show me the other way to do this -
Show Many to many field images in the admin page next to the field itself
First of all, after you read this question, feel free to suggest edits for the title cause I'm not sure what to type I have this hierarchy.. Stone -> Subtype -> Subtype -> Subtype and this goes as long as the Stone has a Subtype in real life. So it's not known how many times will I add Subtypes to a specific stone. Let's inspect it # models.py from django.db import models from django.utils.safestring import mark_safe class Stone(models.Model): name = ... sub_type = models.ForeignKey('StoneSubType', on_delete=models.DO_NOTHING ,related_name='stones', blank=True, null=True) class StoneSubType(models.Model): name = ... sub_type = models.ManyToManyField('self', related_name='sub_types', blank=True) class StoneSubtypeImage(models.Model): stone = models.ForeignKey('StoneSubType', on_delete=models.CASCADE, related_name='images') image = models.ImageField(default=None, upload_to='stone_subtypes/') class StoneImage(models.Model): stone = models.ForeignKey('Stone', on_delete=models.CASCADE, related_name='images') image = models.ImageField(default=None, upload_to='stones/') def image_tag(self): return mark_safe(f'<img src="{self.image.url}">') Let's go the admin page to illustrate what I want Now, Every Subtype has some images, and the Stone itself has some images of course, Images are as shown in the code, So I made them appear in the admin page as an Inline which is shown there when I scroll down. Like this Now, I want to show the images of the Subtype next to the Subtype field. Any suggestions on how can we … -
Must the update form in Django update all fields of an object?
I have created multiple update forms in my Django app. My question is: does Django need to update every single field of an object, or is there a way to only update fields that were actually changed? So, for example, I might have a form with Name, Mail, City. And I might use the update form to update my Mail. Does Django also need the Name and City form fields filled and then update, or is there a way to leave them blank and not update the database? -
django-allauth receiver signal to add group permission to user on signup
My goal is to add a new group to a user when they signup. I'm using the django-allauth package and it seems the best way to do this is to use the package defined signals. Not totally sure how to debug this as I have not been getting any error messages. signals.py from allauth.account.signals import user_signed_up from django.dispatch import receiver from django.contrib.auth.models import User from django.contrib.auth.models import Group #Group Added To New Users: "Can Add Pattern, Symbol, Broker" @receiver(user_signed_up) def user_signed_up_signal_handler(request, user): group = Group.objects.get(name='Can Add Pattern, Symbol, Broker') user.groups.add(group) user.save() -
How to disable TinyMce cdn for one textarea?
I'm using TinyMce as cdn how do I disable for a specific textarea. I see everyone is explaining to do the bellow code but I'm using as cdn. tinyMCE.init({ ... editor_deselector : "mceNoEditor" }); -
TypeError at /website/login/:login() takes 1 positional argument but 2 were given
I am creating a website using Django and i am a beginner in it. views.py: def login(request): if request.method == "POST": form = AuthenticationForm(data=request.POST) if form.is_valid(): user=form.get_user() login(request,user) if 'next' in request.POST: return HttpResponseRedirect(reverse(request.POST.get('next'))) else: return HttpResponseRedirect(reverse('website:books')) else: return render(request,'website/login.html') else: form=AuthenticationForm() return render(request,'website/login.html',{'form':form}) The error i am getting is: File "D:\playground\blog\website\views.py", line 16, in login login(request,user) TypeError: login() takes 1 positional argument but 2 were given [10/Mar/2020 14:34:57] "POST /website/login/ HTTP/1.1" 500 74342 What am i missing? -
HOW TO PASS AN ID IN DJANGO FORM INTO VIEWS
I've this django form and I am trying to pass an ID that are related to a specific record on my project,this is forms.py class AcademicForm(forms.ModelForm): class Meta: model=Academic fields="__all__" labels={ 'Average_grade':'Average Grade', 'Overall_position':'Overall Position', 'Total_number_in_class':'Total Number In Class' } Date = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) Here is my views.py and i don't know how to pass an ID ef add_academic(request): form=AcademicForm(request.POST) if form.is_valid(): form.save() return redirect('/child/more/') else: form= AcademicForm() context={ 'form':form } return render(request,'functionality/more/academy/add.html',context) Here is my urls.py urlpatterns=[ path('base',views.base,name='base'), path('index',views.index,name='index'), path('academic',views.add_academic,name='academy'), ] And this is my template by which form can be displayed {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="container" style="margin-top:15px"> <div class="col-md-12"> <b> <p class="text-center" style="font-weight: 1000;font-size:25px">Add Student Here</p> </b> </div> <div class="container"> <div class="col-md-8"style="margin-bottom:20px"> <form action="" method="post" autocomplete="off"> {% csrf_token %} {{ form | crispy }} <input type="submit" value="Register" class="btn btn-primary btn-block"> </form> </div> </div> </div> {% endblock %} -
Creating a Django model that stores a randomly selected list of objects from another model
Summary: I'm creating an app that involves exams, categories and questions, each exam, when created, will query data from each catagory, each category will then return a pre-determined number of random questions from themselves Exam needs 25 questions from category A and 25 from category B. Category A and B both return 25 items each. The exam model needs to store these 50 items. I'm having trouble figuring out how to go about storing the returned data in the exam model. I know it's just gonna be question IDs but can I just store them in a string CharField? The number of questions per exam can get to around 200 and question IDs are expected to be around four to five digits in length too. Is there a better way to do this than storing it in a string? I can't store the selection criteria because I'm going to be using randomization/shuffling... I think the actual solution would be simple but I'm pulling my hair out trying to figure this out lol. Can I just use both ForeignKey and ManyToMany for Category-Question and Exam-Question? -
Django ModuleNotFoundError from Heroku stored files
Running a blog app within Django which has been working fine until now, encountering an issue when I try to utilize any of the manage.py functions (collectstatic, migrate, runserver etc). I had to retrieve this build from a previous git which was going to a Heroku dyno so I believe a lot of the issues are results of Heroku editing path directories, although, I've scanned the code and see no issues. Current directory (previously working) home/myproject/myproject/mysite settings.py import django_heroku import dj_database_url import dotenv import os.path import django.core.mail # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Load enviroment variables from .env dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = {} DATABASES['default'] = dj_database_url.config(conn_max_age=600) # Password validation # … -
Export results from django-filter
I am trying to download results from a filtered view in Django 2.1. class ListadoEmployeeViewContactoFormularioColombia(FilteredListView): filterset_class = ListadoFormulariosFilter paginate_by = 10 model = ContactoInfoColombia fields = ['plataformaPrincipal', 'numeroPlataformaPrincipal'] #context_object_name = 'quiz' template_name = 'usuarios/listadoContactoEmployee.html' I have been looking for it but haven't found any responses so far. I have thought of creating another class where I get the request parameters like below but I don't feel this is a good way of getting the results. class PaymentExportView(FilteredListView): filterset_class = ListadoFormulariosFilter model = ContactoInfoColombia def render_to_response(self, context, **response_kwargs): # Could use timezone.now(), but that makes the string much longer filename = "{}-export.csv".format(datetime.now().replace(microsecond=0).isoformat()) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename) writer = csv.writer(response) writer.writerow(['nombre']) query = ContactoInfoColombia.objects.filter(numeroPlataformaPrincipal=self.request.GET.get("numeroPlataformaPrincipal")) for obj in query: writer.writerow([obj.nombre]) return response -
DRF: Conditially change serializer
I'm using Django 3.0 and I have a serializer using django-rest-framework. Let's say that for example I have a Forum object. Each forum has an owner that is a user. In my GET /forums/ endpoint, I'd like to just have the owner_id. However, in my GET /forums/<forum_id>/ endpoint I'd like to return the entire embedded object. Is there any way to have one serializer support both of these scenarios? -
Django - Are there security risks with not implementing is_valid and cleaned_data for forms in Django?
I'd prefer to implement A and C instead of B and D, because I'd like to implement my custom css for the form in the html css files without having to deal with forms.py or formatting the css in python. Do A and C present any security risks versus B and D? Are there any other downsides of using A and C? #A if request.method == "POST": user = authenticate(email=request.POST["email"], password=request.POST["password"]) #B if request.method == "POST": if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(email=email, password=password) #C if request.method == "POST": contact_name = request.POST["contact"] #D if request.method == "POST": if form.is_valid(): contact_name = form.cleaned_data['contact'] -
Django models with Imagefield upload_to failed
I would like to upload to the directory below according to the file name. But it failed models.py from xxx import settings import os from pathlib import Path def get_file_path(instance,filename): li = ['index',"zxns","qyfw","login","cloud","about"] prefix = str(filename).split("_",1)[0] if prefix in li: target_folder = "/".join([settings.MEDIA_ROOT,"imgs",prefix]) if Path(target_folder).exists(): return "imgs/{0}".format(prefix) else: os.mkdir(target_folder) return "imgs/{0}".format(prefix) class XXX: photo = models.ImageField("图片",upload_to=get_file_path,null=True,blank=True) This is the result of the uploaded image, not the image format, and not under the corresponding directory. Hope someone can help me. Thanks. -
How to update background task status periodically in Django?
I have a django project which contains a long running process. I have used django-background-tasks library for this. It works but I want to create a pending page for users and display the status of the task. I should refresh that page every 60 seconds and update the status. How can I do that? Thank you. -
Cannot login in Django tests
Trying to write tests for a legacy Django 1.11 project. The project is using unittest package (I don't know if that's standard or a choice). I'm trying to use django.test.Client.force_login to test a view with LoginRequiredMixin but it does nothing. I have added print(self.request.user) to the mixin's dispatch method. It outputs AnonymousUser whether I use force_login or not. Why is it not working? The test (simplified for readability's sake): class CheckoutTest(TestCase): def test_successful_payment(self): user = UserAccount.objects.create(email='foo@bar.com', is_owner=True, is_customer=True) self.client.force_login(user) self.client.post('/subscription/buy/' + str(package.id) + '/', { ... redacted ... }) The view: class BuyPackageView(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): ... redacted ... -
python django cant access the other objects only the first object can access`
In my HTML file i have script tag that contains a variable called nameSearch this will get the value from the textboxt HTML and Javascript: <!-- SEARCH BAR --> <section class = "search_bar" id ="search_bar"> <h1 class = "search_bar-h1">Find a Grave</h1> <form action="" class = "main_form"> <input type="text" id = "name" placeholder="Full Name"> <input type="button" name = "searchButton" value ="Start your Search" onclick="searched()"> </form> </section> <section> <script type="text/javascript"> function searched(){ let a = {{ nameSearched }}; nameSearched = document.getElementById('name').value; {% for names in name %} {% if nameSearched in names %} document.getElementById('dis').innerHTML = "{{ names.Last }}"; } else { document.getElementById('dis').innerHTML = "none"; } {% endif %} {% endfor %} } </script> <h1 id = "dis">test</h1> </section> i want to use the variable nameSearched in my if statement in python but i dont know if its posible because its always return nothing. -
How to play video from local folder in django?
I am working on Anomaly detection project working with django app.i tried to play video from local folder in django app but stuck in how to play video kindly help me if some one done this before??