Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin javascript loads to move to bottom
I took this file from https://jsfiddle.net/emkey08/zgvtjc51 try with my admin. the code is if (!$) { $ = django.jQuery; } $(function($) { $.fn.inputFilter = function(inputFilter) { return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() { if (inputFilter(this.value)) { this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } else if (this.hasOwnProperty("oldValue")) { this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } }); }; }(django.jQuery)); $("#id_fin").inputFilter(function(value) { return /^\d*$/.test(value); }); Now this code loads but does not work, but works from console. There were others who faced the same issue and as the suggested answers were to move the script to end of DOM. change_form.htmlwas extended as below. {% extends "admin/change_form.html" %} {% load static %} {% block admin_change_form_document_ready %}{{ block.super }} <script type="text/javascript" src="{% static 'prop/js/number_validate.js' %}"></script> {% endblock %} Still the end result is the same. Can someone suggest something. Thanks in Advance... -
NoReverseMatch - Resetting password in Django
I have found many similar questions to this issue. This question was one of them, but it didn't solve my problem, so I will ask my own question. I'm making a password reset page on my website. But when I go to http://localhost:8000/users/reset-password and enter my email and clicks on 'Reset my password', then Django throws a NoReverseMatch error at me. The error is: NoReverseMatch at /users/reset-password/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. I believe there's something wrong with how I write my urlpatterns. I've tried: Making my own views and templates. Rewriting all my urlpatterns. My Code urls.py: """Defines URL Patterns for users.""" from django.urls import re_path from django.contrib.auth.views import ( LoginView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView ) from . import views urlpatterns = [ # Login Page. re_path(r'^login/$', LoginView.as_view(template_name='users/login.html'), name='login'), # Logout Page. re_path(r'^logout/$', views.logout_view, name='logout'), # Registration Page. re_path(r'^register/$', views.register, name='register'), # Reset password page. re_path(r'^reset-password/$', PasswordResetView.as_view(), name='reset_password'), # Password reset done page. re_path(r'^reset-password/done/$', PasswordResetDoneView.as_view(), name='password_reset_done'), # Password reset confirm page. re_path(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] -
How to fix 'No such coulomn'?
I created a human class in the models, migrated and an error appears "No such coloumn" GIT: https://github.com/YouDontDie/tododjango1 class Human(models.Model): name = models.CharField(max_length=50, verbose_name="Имя") surname = models.CharField(max_length=50, verbose_name="Фамилия") birth = models.DateField(auto_now_add=False, auto_now=False) salary = models.IntegerField() class TodoList(models.Model): #Todolist able name that inherits models.Model title = models.CharField(max_length=250) # a varchar content = models.TextField(blank=True) # a text field human = models.ForeignKey(Human, default="general", on_delete=models.CASCADE,) created = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) # a date due_date = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) # a date category = models.ForeignKey(Category, default="general", on_delete=models.CASCADE,) # a foreignkey in view def index(request): #the index view todos = TodoList.objects.all() #quering all todos with the object manager categories = Category.objects.all() #getting all categories with object manager humans = Human.objects.all() if request.method == "POST": #checking if the request method is a POS if "taskAdd" in request.POST: #checking if there is a request to add a tod title = request.POST["description"] #title date = str(request.POST["date"]) #date category = request.POST["category_select"] #category human = request.POST["human_select"] #category content = title + " -- " + date + " " + category + " " + human #content Todo = TodoList(title=title, content=content, due_date=date, category=Category.objects.get(name=category), human=Human.objects.get(name=human)) Todo.save() #saving the tod return redirect("/") #reloading the page if "taskDelete" in request.POST: #checking if there is a request to delete … -
How to deploy Django application using Django-background-tasks on AWS beanstalk?
I am using Django-background-tasks in my application, it worked fine for me on my local machine, I am trying to deploy the website to AWS elastic-beanstalk. I wanted to know how to mimic the 2 cmd prompt situation in windows( one with "python manage.py runserver" and the other with "python manage.py process_tasks") in AWS. This will be a kind of parallel situation where both commands need to run simultaneously. -
Django Rest Framework - querying only subclass instances
I have the following model inheritance structure: class ModelA(models.Model): # some fields class Type(models.Model): # fields common to all subtypes # ... # and a ForeignKey relationship modelA = models.ForeignKey(ModelA) class Subtype1(Type): # fields specific for this type class Subtype2(Type): # fields specific for this type So, as you can see. I have this inheritance structure. So far, I can list all Type instances (regardless of their subtypes) at once via the following class-based view in views.py: class TypeList(generics.ListAPIView): serializer_class = TypeSerializer def get_queryset(self): pk = self.kwargs['pk'] modelA = ModelA.objects.get(id=pk) return modelA.type_set.all() So, what I does is: The view gets the id (packed within the URL) of the ModelA instance so that it can get the right ModelA instance from the database. Later on, we return all Type instances of ModelA (because through the foreignkey relationship it can access its set of Type objects). It works very well. But I also want to query the subclass types. How I can do that ? When I replace the return statement from previous code with return modelA.subtype1_set.all(), then I get the following error: AttributeError at /modelAs/1/ 'ModelA' object has no attribute 'subtype1_set' That's clear for me because there is no relationship between … -
Django REST Framework: How to create/handle auth_token for existing and new users?
Currently working on a web-app that I'm implementing an API for. This API will be consumed by an iOS application. Django REST Framekwork provides a convenince view to create tokens for users, providing the username+password are included in the headers: from rest_framework.authtoken import views urlpatterns += [ url(r'^api-token-auth/', views.obtain_auth_token) ] Assumption is users will be registering and logging in from both web and app. What's the best way to handle this? My biggest quibble is with existing users that will be logging in from the iOS app (they already have an account, but don't have an auth token). My current plan is this: Create auth tokens for ALL existing users. Integrate token creation upon registration. This way I can cover all cases. But is there a better approach? -
foreign key assignment for child object
I have a very simple question which I am not able to get my head around. I have following models class Parent(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=64) class Child(models.Model): boardid = models.ForeignKey(Parent,on_delete=models.CASCADE,related_name="child") id = models.AutoField(primary_key=True) title = models.CharField(max_length=128) Serializers class ParentSerializer (serializers.ModelSerializer): class Meta: model = Parent fields = ('__all__') class ChildSerializer (serializers.ModelSerializer): class Meta: model = Child fields = ('id','title') and simple createAPIview for the children class ChildCreateView(CreateAPIView): queryset= Child.objects.all() serializer_class = ChildSerializer When I call this url /api/parent/1/child/create I want to pre populate the foreign key board id with the id 1 and create child object with rest of the information which I will be providing in the body . How is this possible to achieve -
Password Confirmation error not displayed in django forms
I tried to compare password and confirmpassword .if i enter different password it wil not raise error. it will redirected to loginpage. i am using pycharm software and django framework with sqlite3 database. '''models.py class reg1(models.Model): name=models.CharField(max_length=100) city=models.CharField(max_length=100) email=models.CharField(max_length=100) username=models.CharField(max_length=100) password=models.CharField(max_length=100) cpassword=models.CharField(max_length=100) class Meta: db_table='reg1' forms.py class regform(forms.Form): name = forms.CharField(max_length=100) city = forms.CharField(max_length=100) email = forms.CharField(max_length=100) username = forms.CharField(max_length=100) password = forms.CharField(max_length=100) cpassword=forms.CharField(max_length=100) def clean_password(self): if self.data['password'] != self.data['cpassword']: raise forms.Error('Passwords are not the same') return self.data['password'] views.py if myregform.is_valid(): name1 = myregform.cleaned_data['name'] city1 = myregform.cleaned_data['city'] email = myregform.cleaned_data['email'] username1 = myregform.cleaned_data['username'] password1 = myregform.cleaned_data['password'] password2=myregform.cleaned_data['cpassword'] a=reg1(name=name1,city=city1,email=email,username=username1,password=password1,cpassword=password2) a.save() ''' I expect the output as i enter a different password it will show password not matching error -
How to return int from select option value in plain html in django
I have a plain html form which contains a select option, the select option value should return an int to be stored in the database. I have tried converting the value to int in the view but it still doesnt work. This is the model from which I am populating the select options. class GoalStatus(models.Model): target = models.CharField(max_length=100, choices=target, default="Week") def __str__(self): return self.target This is the html form <form action="" method="post"> {% csrf_token %} <div class="form-group"> <label for="task">Task</label> <input type="text" class="form-control" id="task" name="task"> </div> <div class="form-group"> <label for="task">Goal</label> <select name="goal" class="form-control"> {% for goal in user %} <option value='{{goal.id | to_int }}'>{{goal.target}}</option> {% endfor %} </select> </div> <button type="submit" class="btn btn-primary">Create task</button> </form> This is the view which I am getting the post request and saving to the database. def user_add_task(request): user = GoalStatus.objects.all() if request.method == 'POST': if request.POST.get('task') and request.POST.get('goal'): task = ScrummyGoals() task.target_name = int(request.POST.get('goal')) task.user_name = request.user.scrummyuser.id task.task = request.POST.get('task') task.save() return redirect('myapp:home') return render(request, 'myapp/user_add_task.html', {'user':user}) I expect the value of the select option to be an int e.g 1 not a string e.g "1". So I get this error: Exception Type: ValueError Exception Value: Cannot assign "1": "ScrummyGoals.target_name" must be a "GoalStatus" instance. -
How to fix "ImportError: cannot import name 'safe_join' from 'storages.utils' " error while deploying web application on heroku?
I am deploying Django web application which is working on local server but after deployment to heroku it gives error. I have attached last few logs I get by running heroku logs --tail. Error Logs in Heroku 2019-06-15T10:04:39.772193+00:00 app[web.1]: from storages.utils import safe_join, setting 2019-06-15T10:04:39.772196+00:00 app[web.1]: ImportError: cannot import name 'safe_join' from 'storages.utils' (/app/.heroku/python/lib/python3.7/site-packages/storages/utils.py) 2019-06-15T10:04:39.772260+00:00 app[web.1]: [2019-06-15 10:04:39 +0000] [11] [INFO] Worker exiting (pid: 11) 2019-06-15T10:04:39.881913+00:00 app[web.1]: [2019-06-15 10:04:39 +0000] [4] [INFO] Shutting down: Master 2019-06-15T10:04:39.881994+00:00 app[web.1]: [2019-06-15 10:04:39 +0000] [4] [INFO] Reason: Worker failed to boot. 2019-06-15T10:04:39.963380+00:00 heroku[web.1]: Process exited with status 3 2019-06-15T10:05:54.887448+00:00 heroku[web.1]: State changed from crashed to starting 2019-06-15T10:15:34.031356+00:00 heroku[run.4032]: State changed from up to complete 2019-06-15T10:15:34.014580+00:00 heroku[run.4032]: Process exited with status 127 ImportError: cannot import name 'safe_join' from 'storages.utils' (/app/.heroku/python/lib/python3.7/site-packages/storages/utils.py) -
why login form and signup form doesn't show errors?
I have a simple login form and signup form which upon wrong validation it doesn't throw any error, these are respective codes: def signup_view(request): if request.method == 'POST': signup_form = UserRegistrationForm(request.POST) if signup_form.is_valid(): signup_form.save() username = signup_form.cleaned_data.get('username') messages.success(request, f'Thank you for using our website.') return redirect('user:login') signup_form = UserRegistrationForm() context = { 'form':signup_form } return render(request, 'users/signup.html', context) def login_view(request): if request.method == 'POST': login_form = AuthenticationForm(request, request.POST) if login_form.is_valid(): username = login_form.cleaned_data.get('username') user = authenticate(username=username, password=login_form.cleaned_data.get('password')) if user is not None: login(request, user) messages.success(request, f'Successfully logged in as <strong> {username} </strong> ') return redirect('blog:blogs') login_form = AuthenticationForm() context = { 'form': login_form } return render(request, 'users/login.html', context) this is login form and it looks same as signup form: <form action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <input type="submit" value="Login" class="btn btn-warning btn-block"> <hr> <small class='text-secondary'>Don't have an account? <a href="{% url 'user:signup' %}">Sign up</a> </small> <br> <small class='text-secondary'>Forgot password? <a href="{% url 'password_reset' %}">Reset</a></small> </form> These two forms work properly, it can create a new user and it log in that user, but if I make any error it doesn't throw or show that error, why? Thank you in advance -
Setting model field default to shortuuid.uuid() does not generate unique values
I have a CustomUser model that I want to generate a unique shortuuid each insert. Not sure if I'm doing this the right way because I'm running into non-unique uuids with consecutive inserts. Or am I supposed to override the create method and generate the shortuuid from there? from django_extensions.db.fields import ShortUUIDField import shortuuid class CustomUser(AbstractUser): uuid = ShortUUIDField(unique=True, blank=False, editable=False, default=shortuuid.uuid()) -
Django Rest Framework: DRYer pagination for custom actions
Suppose I need to set up several GET endpoints that look like this objects/past, objects/future. Example: @action(detail=False, methods=["GET"], name="Past Objects") def past(self, request, *args, **kwargs): startdate = datetime.datetime.now() some_user = UserProfile.objects.get(user__username="someuser") queryset = self.queryset.filter( other__attribute__profile=some_user, creation_date__lte=startdate ).order_by("-creation_date") page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Is there anyway to avoid the page = ... -> serializer part? I have specified this in my ModelViewSet: pagination_class = CustomObjectPagination But it seems this is only auto-applied to methods like get_queryset and not custom actions. Do I have to write this boilerplate every time I specify a custom action like past? page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) -
How to get "price_retail" field value in tempate?
I am trying access price_retail field in product detail page using template tag purchase_info_for_product. but am not getting the value of price_retail. {% purchase_info_for_product request product as session %} {{ session.price.price_retail|currency:session.price.currency }} but i am able to access fields like incl_tax, excl_tax -
How to solve a "Direct assignment to the forward side of a many-to-many set is prohibited. Use users_ifollow.set() instead." error?
I am trying to make a follower system using django and am getting the above mentioned error code models.py class Following(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) users_ifollow=models.ManyToManyField(User, related_name='followed_by') def __str__(self): return f'{self.user.username} following' views.py class UserFollowView(View): def get(self, request, username, *args, **kwargs): toggle_user=get_object_or_404(User,username__iexact=username) if request.user.is_authenticated: user_profile, created=Following.objects.get_or_create(user=request.user) if toggle_user in Following.objects.filter(user=request.user, users_ifollow=toggle_user): Following.objects.remove(user=request.user, users_ifollow=toggle_user) else: Following.objects.create(user=request.user, users_ifollow=toggle_user) return render(request, 'users/not_creator.html') urls.py path('user/<str:username>/follow', UserFollowView.as_view(),name='follow_user'), traceback Traceback: File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/views/generic/base.py" in dispatch 97. return handler(request, *args, **kwargs) File "/home/Grayocean/grayocean.co/blog/views.py" in get 74. Following.objects.create(user=request.user, users_ifollow=toggle_user) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/query.py" in create 420. obj = self.model(**kwargs) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/base.py" in init 496. _setattr(self, prop, kwargs[prop]) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py" in set 538. % self._get_set_deprecation_msg_params(), Exception Type: TypeError at /user/rheazes/follow Exception Value: Direct assignment to the forward side of a many-to-many set is prohibited. Use users_ifollow.set() instead. -
How to download from another server using Django?
I am using Django, and I have set up a form where a user is able to set a url from a sister website(another server) and download this resource into the django server. Upon completion of the download to the django server to show a download link to the user. Initially I made a python attempt using requests and it works correctly. Now I tried to embed that in django but it is failing. Can i use requests in Django? Is there a better/preferable way this is being done? This is the code I have used class DownloadFile: def __init__(self, user, password, location): self.location = location self.user = user self.password = password def startDownload(self, urllist): cleanList = self.cleanUrlList(urllist) filenames = [] for x in cleanList: filenames.append(self.getFilename(x)) payload = {'op': 'login', 'redirect': 'http://www.sisSite.com', 'rand': 'nqkprxqrwa', 'login': self.user, 'password': self.password} s = requests.Session() r = s.post('http://www.sisSite.com/login', data=payload) for pos in range(len(cleanList)): with open(self.location + filenames[pos], "wb") as f: response = s.get(cleanList[pos], stream=True) total_length = response.headers.get('content-length') print('\nDownloading -> ' + filenames[pos] + 'from URL >>' + cleanList[ pos] + '<< -- total length =' + total_length) if total_length is None: f.write(response.content) else: dl = 0 total_length = int(total_length) for data in response.iter_content(chunk_size=4096): dl … -
how to display the uploaded image using Django and AJAX
i am creating a form that allow user user to select image and uploaded using django and ajax. this process work fine but the problem is that the uploaded image doesn't being displayed on the screen however i did specified a for it. steps that i followed: Create a model that handle the uploaded image. Create a path for the function. Create the function that upload the selected image Create the template and ajax function models.py class photo(models.Model): title = models.CharField(max_length=100) img = models.ImageField(upload_to = 'img/') home.html <form method="POST" id="ajax" enctype="multipart/form-data"> {% csrf_token %} Img: <br /> <input type="file" name="img"> <br /> <br /> <button id="submit" type="submit">Add</button> </form> $('#ajax').submit(function(e) { e.preventDefault(); var data = new FormData($('#ajax').get(0)); console.log(data) $.ajax({ url: '/upload/', type: 'POST', data: data, contentType: 'multipart/form-data', processData: false, contentType: false, success: function(data) { // alert('gd job'); $("#photo").html('<h2> {{'+data.title+'}}</h2> <img src="{{'+data.img.url+ '}}" alt="{{ photo.title }}">') } }); return false; }); views.py def upload(request): if request.method == 'POST': if request.is_ajax(): image = request.FILES.get('img') uploaded_image = photo(img = image) uploaded_image.save() photo=photo.objects.first() # return render(request, 'home2.html') return HttpResponse(photo) i expect that after the user upload the image and the image i stored in the database, the image must be displayed on the screen. -
Django: Setting "on_delete=DO_NOTHING" on a ManyToManyField
Django's although useful ManyToManyField is highwired to kill all involved subjects when deleted... with it's internal ForeignKey on_delete=CASCADE. Why is that hard coded?! and what is the simple way to override this behavior? After considering a number of solutions, seems the most clean one is to externally handle delete signal call and set nulls on the values... Is there a cleaner/simpler way? And shouldn't it be a red flag on ManyToManyField? -
What are the most useful python libraries for creating an IPTV Panel?
I want to create an IPTV Panel like Xtream codes but in python using django and I want to know if there are any useful python libraries that may help me in this project (creating VOD, use channel links and generate m3u files from it...) -
How to call a REST API service through Vue JS
I am creating a blog website using Vue JS and Django Rest Framework. I have a submit Button in Vue JS which should pass text input to Django, How can I do that ? The POST API link is in localhost:8000/api/post -
import views.py from another section in the main section's urls.py
i can't extend blog/template/base.html in users app i use this code: {% extend "blog/base.html" %} here is my project image: Error: TemplateDoesNotExist at /register/ blog/base.html Request Method: GET Request URL: http://localhost:8000/register/ Django Version: 2.2 Exception Type: TemplateDoesNotExist Exception Value: blog/base.html -
In Django, How to display an index file not customized for django with relative links to it's own source files
Give a link on a page to an index file that works as a standalone offline app without changing the internal links and structures. I have hundreds of these. -
Integrating Django Rest Framework and Scrapy
Both Scrapy and Django Frameworks are standalone best framework of Python to build crawler and web applications with less code, Though still whenever You want to create a spider you always have to generate new code file and have to write same piece of code(though with some variation.) I was trying to integrate both. But stuck at a place where i need to send the status 200_OK that spider run successfully, and at the same time spider keep running and when it finish off it save data to database. Though i know the API are already available with scrapyd. But i Wanted to make it more versatile. That lets you create crawler without writing multiple file. I thought The Crawlrunner https://docs.scrapy.org/en/latest/topics/practices.html would help in this,therefor try this thing also t Easiest way to run scrapy crawler so it doesn't block the script but it give me error that the builtins.ValueError: signal only works in main thread Even though I get the response back from the Rest Framework. But Crawler failed to run due to this error does that mean i need to switch to main thread? I am doing this with a simple piece of code spider = GeneralSpider(pk) runner … -
Writing Django TestCase for Rest API
I am new in django and please don't feel boring with armature question. I tried to find some tutorial to write TestCase for django rest api but i couldnt find any tutorial for Api testcase but i found huge tutorial for django testcase Can anyone suggest me any tutorial how to write TestCase for Django Rest API? Thanks in Advance -
How to use math operations in django
I want to use arithmetic operations in django. {% if skipped.i-{{ pending | length }}.resource_id.resource_type == 'videos' %} i want to do i-{{pending | length }}