Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Jinja loop iteration in javascript
I am able to fetch data from models and able to display in table format .But now i want to use javascript for few attributes so how can i loop through java script (if checkbox is clicked disable input field ).Below is my code i tried using Jinja for loop for javascript but it is not working. <<models>> class datavalue(models.Model): myname=models.CharField(max_length=250,default=None) finalnames=models.CharField(max_length=250,default=None) def __str__(self): return self.nameif <<views.py>> def context(request): myvalue = datavalue.objects.all() return render(request, 'context.html', {'dbvalue':myvalue}) <<context.html>> {% for i in dbvalue %} <tr> <td > {{ i.myname }}</td> <td>C1</td> <td>L1</td> <td> <label class="radiocontainer" >Manual <input type="radio" name={{ i.myname }} checked><span class="circle"></span> </label><br><br> <label class="radiocontainer">Automatic <input type="radio" name={{ i.myname }} id={{i.id}} onclick="disablefun()"><span class="circle"></span> </label> </td> <td><input type="text" id={{i.finalnames}}></td> </tr> <script> function disablefun() { if (document.getElementById({{i.id}}).checked == true){ document.getElementById({{i.finalnames}}).disabled=true; } else { text.style.display = "none"; } } </script> {% endfor %} </table> -
how can i access a context of function view with a separate page in base page?
i created newsletters app with below code after that i have a URL : subscribe that perfectly work and save my email after that i want to add this ability in base page for example a user don't go to subscribe page and subscribed i want directly have access in base template and subscribe . i want to know this because i want add login form to base page and have this problem with that . this my code and this is my template tnx for help. views.py def Subscribe(request): form = SiqnupNewslettersForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if SignupNewsletters.objects.filter(email=instance.email).exists(): print("this email already taken ") else : instance.save() context = { 'form':form } template_name = "subscribe.html" return render(request,template_name,context) def Unsubcribe(request): form = SiqnupNewslettersForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if SignupNewsletters.objects.filter(email= instance.email).exists(): SiqnupNewslettersForm.objects.filter(email = instance).delete() else: print("your email is not here") context = { 'form' : form } template_name = "unsubscribe.html" return render(request,template_name,context) subscribe.html {% block content %} <div class="container"> <div class="row"> <form method="POST" action=""> {% csrf_token %} <div class="form-group"> {{ form }} </div> <input type='submit' class="btn btn-primary" value="submit"> </form> </div> </div> {% endblock %} urls.py urlpatterns = [ path('subscribe/',views.Subscribe,name="subscribe"), path('unsubscribe/',views.Unsubcribe,name= "unsubscribe"), ] and finally what i … -
Handling errors 404/500 in Django
There is a little problem with my Django application: my project is a blog with several posts. You can access the first post by typing localhost:8000/blog/post/1 in the URL bar. To read the post no. X you have to type localhost:8000/blog/post/X. So I need to display a custom "Error 404" page when an inexistant post is requested (for example localhost:8000/blog/post/32 if there are only 3 posts available). The problem is, instead of throwing a 404 error, it throws a Server Error (500) error however I never coded something to throw this kind of error. Here is the concerned code parts, but not my full code which I think is useless. Project name is red_pillers, app name is blog. in red_pillers/settings.py DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] red_pillers/urls.py from django.contrib import admin from django.urls import path, re_path, include from django.conf.urls import handler404 from . import views handler404 = 'red_pillers.views.handler404' urlpatterns = [ re_path('^blog/', include('blog.urls')), re_path('^$', views.home), re_path('^admin/', admin.site.urls), ] red_pillers/views.py from django.shortcuts import render def home(request): return render(request, 'home.html') def handler404(request): return render(request, 'errors/404.html', {}, status=404) blog/pycode/post.py from django.http import Http404 class Post: POSTS = [ {'id': 1, 'title': 'First Post', 'body': 'This is my first post'}, {'id': 2, 'title': … -
django-heroku 0010_alter_group_name_max_length.py missing in auth/?
I'm trying to make users login with a "email - password" combo instead of "username - password" on my django website hosted on heroku I have used this tutorial which works well on my computer (migrations included) but when i try to migrate my online installation i get an error saying that : "django.db.migrations.exceptions.NodeNotFoundError: Migration account.0001_initial dependencies reference nonexistent parent node ('auth', '0010_alter_group_name_max_length')" The migration file looks like that: class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0010_alter_group_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('email', models.EmailField(max_length=254, unique=True, verbose_name='email address')), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user … -
Crop uploaded image and send cropped coordinates using Cropper.js
I am new to Django and frontend technologies, trying to build a Django web application in which the user uploads a image, view the full image and crops the same image at the client side only.The server side will only receive original uncropped image and cropped coordinates(x,y,width, height) of the cropbox user selected.I have read couple of tutorials using cropper.js but I am unable to figure out what is the correct way to do this? Thanks in advance. Currently my files are as follow forms.py from django import forms class ImageUploadForm(forms.Form): image = forms.ImageField() model.py from django.db import models class ImageModel(models.Model): image = models.ImageField(upload_to = 'media/') views.py from django.shortcuts import render from .models import ImageModel from .forms import ImageUploadForm def upload(request): if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): p = ImageModel(image = request.FILES['image']) p.save() return render(request, 'abc.html') else : form = ImageUploadForm() return render(request, 'index.html', {'form': form}) template index.html <body> <table> <tr> <td> <form action="" method="POST" enctype="multipart/form-data"> <p> {{form}} </p> <br /> <input type="submit" value="Upload File" /> </form> </td> </tr> </body> -
Django CMS placeholder on Plugins
I'm using Django CMS and wanting to create a news plugin. The News plugin should split into three sections, Title Left Content and Right Content. How can I have a placeholder within the plugin so I can drop any plugin into these placeholders? Can this be created on plugin level? -
ModuleNotFoundError: No module named 'django.urls' not working in Django 1.9
I'm using Django 1.9 from django.contrib admin from django.conf.urls import include, url from slack.views import DRSWebhookTransactionView, DRSMessageView from django.urls import path api_patterns = ([ path('web/', DRSWebhookTransactionView.as_view()), path('events/', DRSMessageView.as_view()), ], 'api') urlpatterns = [ url(r'^admin/', admin.site.urls), path('api/v1/', include(api_patterns)), ] after running python manage.py runserver from django.urls import ( # noqa ModuleNotFoundError: No module named 'django.urls' I'm getting this error after I tried including path. If I don't include path it's not showing the error for the 'path', it's still showing the same error. Can someone tell how can I rewrite this program? and tell me what I'm doing wrong? -
Django social auth error 500 after facebook redirect
I've set up social-auth-app-django in production. But after facebook redirect I got error 500 and still unable to get it work. In my user model email address used to sign up. This is my user model: class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) avatar = models.ImageField(blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] in settings.py: MIDDLEWARE = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ ... 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'accounts.backends.ModelBackend' ) LOGIN_URL = '/' LOGOUT_URL = '/' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) SOCIAL_AUTH_FACEBOOK_KEY = '..' # App ID SOCIAL_AUTH_FACEBOOK_SECRET = '...' # App Secret SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id,name,email', } Thank you for your time and help. -
How do I restore my logs window into code block
I have an issue regarding code block logs and other I can't see my logs and other window so I am not able recognised my errors I have done default view of code blocks as well as I went through view window and allow logs there still I am not able to my logs Please help me to solve this -
Is there a possibility of extracting data from a pc application and displaying on a webpage using python
I'm trying to design a website using python, django precisely to display data from a pc weather software on a webpage in real time. wondering if there is a possibility to that. Thanks -
How to fix ConnectionRefusedError: [WinError 10061] the target machine actively refused it? (Django e.mails)
How to fix [WinError 10061] with Django e.mails? (No connection could be made because the target machine actively refused it) I am using Django to send e.mails. I am getting a common network error apparently, but not any of the answers I've read solved. I have a problem with the socket I believe, When I send the e.mail I get the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\Jaime\Miniconda3\envs\mydjango\lib\site- packages\django\core\mail\message.py", line 291, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\Jaime\Miniconda3\envs\mydjango\lib\site- packages\django\core\mail\backends\smtp.py", line 103, in send_messages new_conn_created = self.open() File "C:\Users\Jaime\Miniconda3\envs\mydjango\lib\site- packages\django\core\mail\backends\smtp.py", line 63, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "C:\Users\Jaime\Miniconda3\envs\mydjango\lib\smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "C:\Users\Jaime\Miniconda3\envs\mydjango\lib\smtplib.py", line 336, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Users\Jaime\Miniconda3\envs\mydjango\lib\smtplib.py", line 307, in _get_socket self.source_address) File "C:\Users\Jaime\Miniconda3\envs\mydjango\lib\socket.py", line 727, in create_connection raise err File "C:\Users\Jaime\Miniconda3\envs\mydjango\lib\socket.py", line 716, in create_connection sock.connect(sa) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it Here is what I've tried: 1) import socket socket.getaddrinfo('hotmail-com.olc.protection.outlook.com', 80) socket.getaddrinfo('smtp.hotmail.com', 8000) socket.getaddrinfo('smtp.hotmail.com', 587) 2) Turn off Firewall / Antivirus 3) Run the code in python shell and in Django app 4) I've got the smtp … -
How do I test whether a Django QuerySet method was called?
Say I have the following: models.py: class FooQuerySet(models.QuerySet): def bar(self): return self.filter(...) class Foo(models.Model): ... objects = models.Manager.from_queryset(FooQuerySet) views.py: class FooListView(ListView): model = Foo def get_queryset(self): qs = super().get_queryset() return qs.bar() And I wish to test that models.FooQuerySet.bar is called when the view is called. So far I have: request = RequestFactory().get('') view = FooListView.as_view() with mock.patch('<best_guess>') as mocked: mocked.return_value = Foo.objects.none() view(request) mocked.assert_called_once() Where <best_guess> has been: foo_app.models.FooQuerySet.bar foo_app.models.Foo.objects.bar foo_app.views.Foo.objects.bar None of which worked. Even if I happened upon a magic patch string that did work, I fear I simply don't understand what's going on here. What's the correct way to test that FooQuerySet.bar() is called? (There's also the added difficulty that QuerySets are chained, so I might one day need to know if FooQuerySet.any().amount().of().weird().methods().bar() is called). -
How to resolve AssertionError: .accepted_renderer not set on Response in django and ajax
While I am calling Django url in ajax, getting below error AssertionError: .accepted_renderer not set on Response. This is my code: function download(){ $.ajax({ url: "/mdm/exam_app/get_assessment_count/", dataType: 'json', data:{ }, type:'GET', success: function (data) { alert("inside the success method"); }, error: function(){ console.log("error"); } }); } -
How to upload video on S3 bucket using signed URL created by Python Boto v2.38.0?
we have one functionality where we need to create an s3 bucket signed URL for the client. the client will upload a video on that URL. we are using Boto version 2.38.0 for generating signed URL. conn = boto.connect_s3() key = "test_key" bucket = "test_bucket" signed_url = conn.generate_url( expires_in=600, method="PUT", bucket=bucket, key=key, headers={'Content-Type': 'application/octet-stream'} ) I can upload the file with binary, but I can not upload the file with form-data. I have also tried multipart/form-data for the same. So, Could you please suggest me some request with signed URL video upload using POSTMAN? Any help would be highly appreciated. Thanks. -
Django model datetimefield updates but not in db
I have the following in my Memo model times_visited = models.IntegerField(default=0) date_last_visited = models.DateTimeField(default=timezone.now()) When calling as below, only times_visited int is being updated in the database correctly, the date_visited stays the same as during initialisation. The print debug shows the correct time is stored in the model, but it seems it doesnt get pushed to the db. I did not override the save method. memo.times_visited = memo.times_visited + 1 memo.last_visited = timezone.now() memo.save() print("Last visited: " + str(memo.last_visited)) Should this not be working this way? -
Django form post keyerror
I have a Django code where i give a POST request. The POST varaible contains the data but while trying to read it from form.cleaned_data['key'] it throws a Key error stating the key is not found. form_isvalid also returns false. I am giving correct data only and it was working fine previously my code will look like this views.py def open_html(request): form = form_main.DateForm() if request.method == 'POST': form = form_main.DateForm(request.POST) #print (request.POST.get('scrap_button')) print (form.is_valid()) if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... #enter_time=form.cleaned_data['date'] #enter_mail_id=form.cleaned_data['mail_id'] #enter_timezone=form.cleaned_data['time_zone'] print (form.cleaned_data) enter_mail_id = form.cleaned_data['mail_id'] enter_date = form.cleaned_data['date'] html <form method="post"> <label >Mail ID:</label> {% csrf_token %} {{ form.mail_id}} <br></br> <div id="myOutput"></div> <label >When to send mail?</label> {% csrf_token %} {{ form.date }} <script> $(function () { $("#id_date").datetimepicker({ format: 'd/m/Y H:i:s', }); }); </script> forms.py class DateForm(forms.Form): mail_id=forms.CharField(max_length=100) date=forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M:%s']) -
Django error: OperationalError at /admin/auth/user/1/change/
I have tried to change user permission in the administration page but it actually shows me this when I save I'm using Django Version: 2.1.7 Python Version: 3.7.2 for what i saw it was an issue before Django 2.1.5 so I have no idea what to do OperationalError at /admin/auth/user/1/change/ no such table: main.auth_permission__old Request Method: POST Request URL: http://localhost:8000/admin/auth/user/1/change/ Django Version: 2.1.7 Exception Type: OperationalError Exception Value: no such table: main.auth_permission__old Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 298 Python Executable: /usr/bin/python3 Python Version: 3.7.2 Python Path: ['/home/Max/Documents/Workspace/Projet_Python/hey', '/usr/lib64/python37.zip', '/usr/lib64/python3.7', '/usr/lib64/python3.7/lib-dynload', '/home/Max/.local/lib/python3.7/site-packages', '/usr/local/lib64/python3.7/site-packages', '/usr/local/lib/python3.7/site-packages', '/usr/lib64/python3.7/site-packages', '/usr/lib/python3.7/site-packages'] Server time: Fri, 29 Mar 2019 10:12:07 +0000 -
Nginx configuration for django, react and wordpress
I have project with following stack: Django and Django rest as backend React as frontend Wordpress as content mangement Now my site routes should be mix of above and nginx should get an smart decision for each request. Assume this routing: - api.example.com: all django related requests - example.com ==> Should map to the wordpress index page - example.com/blog ==> Should map to wordpress - example.com/<staff> ==> Should map react mapper How can I implement above nginx configuration? Thanks all. -
Load data from app accros site-wide footer
I have an app called sponsors. The model contains a field gold sponsor which is a boolean. Now I want to load the gold sponsors in the site-wide footer which is included in my base.html How can I make the data from the app sponsors available in the footer? <footer> {% include "includes/footer.html" %} </footer> -
Get the order of the forms in a formset automatically, considering that the user can jump over the default order or delete/remove past forms
I'm using formset in a form, by adding it as an attribute to the form: self.whitepaper = WhitePaperFormSet( instance=self.instance, prefix=WHITEPAPER_TR, data=self.data if self.is_bound else None, files=self.files if self.is_bound else None, auto_id=False) I need to get/set and order, of the form in formsets. I know that Django use an id/index, can_order, but there are situations like: No Forms completed, the user complete forms number 1 and number 4 (from 4) Form 1 and 3 are already completed, the user deletes/clean form 1 completes 2 and 4, so now I have data in 2,3 and 4 Being documents, can_order is not visible So the index by itself doesn't help. So I need to check somehow what is completed, what was removed and number -
Model String Field name in URL instead of id - AttributeError Django
I am trying to access detail view. Previous i used id in url and it was working correctly. Now my condition has changed and instead of id, I want to add place_id in url. For that i used <str:place_id> but it is giving AttributeError. How can i add place_id in url and get correct data. And what is slug. Should i use it. But my place_id is unique. urls.py path('detail/<str:place_id>/', Detail.as_view(), name='detail'), Models.py class Map(models.Model): name = models.CharField(max_length=255, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) place_id = models.CharField(max_length=255, null=True, blank=True, unique=True) Views.py class Detail(LoginRequiredMixin, generic.DetailView): template_name = "detail.html" model = Map context_object_name = 'map' Error - Generic detail view Detail must be called with either an object pk or a slug in the URLconf. -
Generating a django sitemap without regard to models?
All the examples I have seen for generating sitemaps in Django seem to iterate over a model, to generate URLs that way. For example, from the Django documentation: class BlogSitemap(Sitemap): changefreq = "never" priority = 0.5 def items(self): return Entry.objects.filter(is_draft=False) def lastmod(self, obj): return obj.pub_date I can't do this with my web application. I have thousands of URLs that correspond to product pages, that are generated using django, based on data retrieved from an API that was directly inserted into a postgres database. So, I am using django to retrieve records from the database and shape how they are presented, but the URLs I have do not correspond to any django model (this is something that will be improved and changed in the future). Is there a way then, that I can specify specific URLs in a sitemap without iterating over a model? -
How do I recompile the pyhon files
I made some changes in my source code. But after I restart the server, Iam not able to see those changes. I'm using Django framework. How do I recompile python code in the linux (CentOS) server. I already tried restarting the server, installing django-extension. -
How to filter with enum or string and get a same result?
I have a hard time using Enums in Django. This is my Request model: class RequestStatuses(Enum): new = 'new' sent = 'sent' done = 'done' class Request(BaseModel): request_number = models.PositiveIntegerField(default=0) type = models.CharField(max_length=31, blank=True, null=True) status = models.CharField( max_length=31, choices=[(a.name, a.value) for a in RequestStatuses], default=RequestStatuses.new ) sensor = models.ForeignKey(Sensor, on_delete=models.SET_NULL, blank=True, null=True) device = models.ForeignKey(Device, on_delete=models.SET_NULL, blank=True, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) payload = models.TextField(blank=True, null=True) There is a difference whether I create the record with string, or the enum type, which is really annoying... This works just fine: device = Device.objects.create(serial_number=1) request = Request( device=self.device, status=RequestStatuses.sent ) request.save() try: request = device.request_set.filter( status=RequestStatuses.sent )[0] except IndexError: print(device.request_set.all()[0].status) pass But this throws an exception device = Device.objects.create(serial_number=1) request = Request( device=device, status='sent' ) request.save() try: request = device.request_set.filter( status=RequestStatuses.sent )[0] except IndexError: print(device.request_set.all()[0].status) pass When I try to filter with status=RequestStatuses.sent.value or just with sent string the first example throws an exception and second works. What is the point of enums, when you can't filter them by string or vice versa? How can I make it work with api - which will pass string to a filter? Or is it just some cache issue? -
Pyuploadcare ImageField upload option is not visible at useredit html page
I have integrated the Pyuploadcare module in my django App. I have added an ImageField in the models.py of my application as shown below. from pyuploadcare.dj.models import ImageField class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=False, null=True) img = models.ImageField(upload_to=upload_to, blank=True, db_index=True) slug = models.SlugField(max_length=200, blank=True) cover = ImageField(blank=True, manual_crop="") The User_edit page is shown below: <pre> {% block content %} <div class="edit-form"> <h1>Edit your account</h1> <p>You can edit your account using the following form:</p> <form action="." method="post" enctype="multipart/form-data" id="controlForm"> {{ user_form.as_p }} {% csrf_token %} {{ profile_form.as_p}} <p><input type="submit" value="Save changes"></p> </form> </div> {% endblock %} </pre> I have tried updating the form that is generated from forms.py shown below class ProfileEditForm(forms.ModelForm): cover = ImageField(label='') class Meta: model = Profile fields = ('date_of_birth', 'img', 'cover') widgets = { 'date_of_birth': DateInput(), } The form generates the cover with type hidden Expected result is <tr><th></th><td><input type="file" name="cover" value="https://ucarecdn.com/182065fa-d558-47e5-beb6-0d0c3dd8baf2/" role="uploadcare-uploader" data-public-key="bce890ec49219565dc75" data-integration="Django/2.1.7; PyUploadcare-Django/2.6.0" data-images-only="" re quired id="id_cover"></td></tr> actual result is : <tr><th></th><td><input type="hidden" name="cover" value="https://ucarecdn.com/182065fa-d558-47e5-beb6-0d0c3dd8baf2/" role="uploadcare-uploader" data-public-key="bce890ec49219565dc75" data-integration="Django/2.1.7; PyUploadcare-Django/2.6.0" data-images-only="" re quired id="id_cover"></td></tr> the result are captured from views.py where the profile form i generated