Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When should I validate an object using Model.clean() instead of )Form.clean()
Both the Model and Form class have clean() methods for object validation. It is unclear from the docs when one should use one over the other. I understand that Form may be used to validate an object even when it is not displayed to a user and that clean() is intended to validate the class as a whole. So why does Model have the same method as well? -
How to pass values from django template to a javascript function?
I'm trying to send the values from checked radio buttons in django template and get an alert message when the form is submitted.How do use the javascript function to do alert the user? This is the django template <form name="taketest"> <ul> {% for q, opts in quesBank.items %} {{ forloop.counter }}{{q}} <ol> <label class='radiocontainer'><input type="radio" name="q{{forloop.counter}}" value="{{opts.0}}">{{opts.0}}</input></label><span class='checkmark'> <label class='radiocontainer'><input type="radio" name="q{{forloop.counter}}" value="{{opts.1}}">{{opts.1}}</input></label><span class='checkmark'> <label class='radiocontainer'><input type="radio" name="q{{forloop.counter}}"value="{{opts.2}}">{{opts.2}}</input></label><span class='checkmark'> <label class='radiocontainer'><input type="radio" name="q{{forloop.counter}}" value="{{opts.3}}">{{opts.3}}</input></label><span class='checkmark'> </ol> {% endfor %} </ul> <div class="text-right"> <button class="btn btn-outline-info" type="submit" onsubmit="return submitAnswers(JSON.parse('answers=[{% for a in correctAnswer %}'{{a|safe}}',{% endfor %}])')">Submit</button> </div> </form> This is the javascript file function submitAnswers(answers){ var total = answers.length; var score = 0; var choice = [] //new dynamic method 1 for(var i = 1; i <= total; i++){ choice[i] = document.forms["taketest"]["q"+i].value; } // new dynamic method 1 for checking answer for(i = 1; i <= total; i++){ if(choice[i] == answers[i]){ score++; } } //Display Result window.alert("You scored " + score + " out of " + total); return false; } Is there anything wrong with this? -
how to crop and save cropped coordinates along with original image?
I am building a Django web app where the user can upload an image and crop it at the client side. The original image(path) will be saved along with its cropped coordinates(x,y.width, height) in the database. What is the preferred way to do that? Thanks. -
How to get the next and previous post from my blog in django
am building a blog, my issue is that am trying to get the next and the prev post in the database but i could do so, i searched online, but the solutions i saw was not working here is my code view.py def PostDetail(request, pk): obj = get_object_or_404(Posts, id=pk) nextPost = obj.get_next_by_id() prevPost = obj.get_prev_by_id() context={ 'object':obj, 'title': obj.title, 'latests': Posts.objects.all().order_by('-id')[:5] } return render(request, 'blog/details.html', context) model.py class Posts(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, default="1", on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='blog_pics') def __str__(self): return self.title when i ran the code, it gave me this error return view_func(request, *args, **kwargs) File "C:\Users\De Stone Of David\Desktop\python\second\projects\eblog\blog\views.py", line 124, in PostDetail nextPost = obj.get_next_by_title.pk AttributeError: 'Posts' object has no attribute 'get_next_by_title' pls how can i solve this issue so that i can get the title and the id of the next post -
Problem in doing database backup for users
I am using django version 2.0.6 and using db.sqlite3 for my database. I want to give a functionality to the user to keep a backup of the model objects they have created and load the data whenever needed. Any idea anyone how to do it in django? Thank you. -
How to align the contents of the login form horizontally?
I have made a login form in which the contents are aligned vertically. What should i do to arrange it horizontally just like how facebook login page is? login.html <div class="login-form"> <form method="POST" class="post-form"> {% csrf_token %} <h2 class="text-center">Log in</h2> <div class="form-group"> {{ form | crispy }} <div id='form-errors'>{{ form_errors }}</div> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-block">Log in</button> </div> <div class="clearfix"> <label class="pull-left checkbox-inline"><input type="checkbox"> Remember me</label> <a href="#" class="pull-right">Forgot Password?</a> </div> </form> <p class="text-center"><a href="{% url 'register' %}">Create an Account</a></p> </div> forms.py class LoginForm(forms.ModelForm): class Meta: model = User fields = ("username", "password") labels = { 'username': 'Username', 'password': 'Password' } And here is my CSS file login_style.css .login-form { width: 340px; margin: 50px auto; } .login-form form { margin-bottom: 15px; background: #f7f7f7; box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); padding: 30px; } .login-form h2 { margin: 0 0 15px; } .form-control, .btn { min-height: 38px; border-radius: 2px; } .btn { font-size: 15px; font-weight: bold; } Contents i.e the username and the password text fields are aligned vertically but I want to align them horizontally rather than vertically. How should i do that? Thank you in advance! -
The `.create()` method does not support writable nested fields by default. How do to solve this?
I have a big problem regarding the serialization of a Many to Many relationship with intermediate model in DRF: If the request method is get everything works perfectly. But as soon as i try to POST or PUT Data to the API I get the following Error: Internal Server Error: /api/ordering/ Traceback (most recent call last): File "/home/neha/.local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/neha/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/neha/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/neha/.local/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/neha/.local/lib/python3.5/site-packages/rest_framework/viewsets.py", line 116, in view return self.dispatch(request, *args, **kwargs) File "/home/neha/.local/lib/python3.5/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/home/neha/.local/lib/python3.5/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/home/neha/.local/lib/python3.5/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "/home/neha/.local/lib/python3.5/site-packages/rest_framework/mixins.py", line 21, in create self.perform_create(serializer) File "/home/neha/.local/lib/python3.5/site-packages/rest_framework/mixins.py", line 26, in perform_create serializer.save() File "/home/neha/.local/lib/python3.5/site-packages/rest_framework/serializers.py", line 214, in save self.instance = self.create(validated_data) File "/home/neha/.local/lib/python3.5/site-packages/rest_framework/serializers.py", line 929, in create raise_errors_on_nested_writes('create', self, validated_data) File "/home/neha/.local/lib/python3.5/site-packages/rest_framework/serializers.py", line 823, in raise_errors_on_nested_writes class_name=serializer.class.name AssertionError: The .create() method does not support writable nested fields by default. Write an explicit .create() method for serializer ordering.serializers.CustOrderSerializer, or set read_only=True on nested serializer fields. enter code … -
python not reading the entire file
I am building a web application which will analyse the apache log file. When I tried to read each line from the log file by using the for loop it skips so many log entries and prints only some of them. I am using python 3.7.2 ,django 2+ and pycharm to build the project so far i have tried on a access log file from this site https://bureau-ehe.ch/logs/access.log. i have tried with so many other logs also but it also skipping lines. with open('access.log', "r") as f: for line in f: print(line) f.close() expected result is to print all the lines but am getting 9 thousand something -
Django-Rest-Framework Could not resolve URL for hyperlinked relationship
I am trying to create an API for custom user model to add a new user using generic views. I am getting an error and not able to identify the root cause of it. Though the user gets added successfully. But I still recieves a HTTP 500 error in my response. ImproperlyConfigured at /api/new_user Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. My apiView class is as follows. class CreateUserView(CreateAPIView): """ This view creates a new user """ serializer_class = UserSerializer def perform_create(self, serializer: UserSerializer): try: serializer.save( email=serializer._validated_data['email'], first_name=serializer._validated_data['first_name'], last_name=serializer._validated_data['last_name'], password=make_password(serializer._validated_data['password']) ) except Exception as exception: return JsonResponse({ 'success': False, 'error': 'Error occured in registering user!' }, status=500) return JsonResponse({'success': True}) and my serializer class is as below. class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=128, min_length=8, style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ('url', 'id', 'email', 'first_name', 'last_name', 'password',) and my url patterns file is as follows urlpatterns = [ path('api/new_user', CreateUserView.as_view()), path('api/login/', obtain_auth_token, name='api-token-auth') ] Please help me resolving this. -
How to deploy django on AWS elastic beanstalk with postgresql
I tried a lot of tutorials including aws beanstalk official django deployment document. There is always some kind of error. eg: none of my requirements.txt packages get installed on ec2. When i ssh to ec2 I see that Django==2.1.1 is not an available option that for installation. Unable to connect to postgresql DB from ec2, but could connect from my local machine, inspite of having added ec2 public IP4 to the security group. It connects when I add ec2 security group ID to rds inbound though. I spent many days trying to fix individual problem but still the overall attempt has been a frustrating failure. I know there must be lot of rookie aspiring django+AWS developers like me who would greatly appreciate a comprehensive tutorial that just works with python 3.6 instead of having to put pieces together or use third party services. Thanks -
How to setup ftp in django
Rightnow i am storing the uploaded images in local path, so i want to create one ftp server where i can store all my images so that others who are accessing my api can access the uploaded images also I am not understanding where to start and how to create ftp server my model : class Resized_image(models.Model): image=models.ImageField(upload_to=datetime.strftime(datetime.now(),"photos/%Y/%m/%d"),width_field='width', height_field='height',) here i am specifying local path to store uploaded images I want to create an ftp server with uploads/ folder so that whatever the images i have uploaded using any server will be stored inside that uploads/ folder in ftp server -
I am adding location field in my django model Its showing an error
I am trying to add a location field to my django model with the help of postgis extension when I am trying to migrate it the error is showing: django.db.utils.OperationalError: could not open extension control file "/usr/share/postgresql/10/extension/postgis.control": No such file or directory I've updated my settings.py INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'meenfee', 'accounts', 'rest_framework', 'rest_auth', 'rest_auth.registration', 'django.contrib.sites', 'allauth', 'django.contrib.gis', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'django.contrib.admin', ] DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'meenfeefinal', 'USER': 'meenfeefinaluser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } here is my models.py. Take a look at location field from django.contrib.gis.db import models as gis_models class Service(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) service_name = models.CharField(max_length=200,null=True,default="sample service") category = models.ForeignKey(Category, on_delete=models.CASCADE) subcategory = models.ForeignKey(SubCategory,on_delete=models.CASCADE) experience = models.TextField(blank=True,null=True) levelskill = models.CharField(max_length=120, choices=LEVELSKILLS) service_place = models.CharField(max_length=120, choices=LOCATION) location = gis_models.PointField(u'longitude/latitude',geography=True, blank=True, null=True) city = models.ForeignKey(City,blank=True,null=True,on_delete=models.DO_NOTHING) distance_limit = models.CharField(max_length=100, choices=DISTANCE) service_pricing = models.PositiveIntegerField(help_text='in Jordanian dinar') pricing_timing_unit = models.CharField(max_length=30,choices=PRICINGUNIT) quote_at_request = models.BooleanField(default=False, help_text='This will create popup when they accept a requester request') provide_tools = models.BooleanField(default=True) tool_specify = models.TextField(blank =True, null=True) instant_booking = models.BooleanField(default =True) avg_rating = models.FloatField(default=0.0) created = models.DateTimeField(auto_now_add=True) def __int__(self): return self.id class Meta: verbose_name_plural = "Services" I just want to succesfully add the location field … -
Unable to Open base64 decoded '.jpg' image due to 'Source Missing'?
I am trying to send a .jpg file using request and trying to decode it in django server side. CODE: This is the sending side code: import requests import os import base64 fPath = os.getcwd() url = 'http://127.0.0.1:8000/submitcausedata/' headers = {'content-type': 'application/x-www-form-urlencoded'} path_img = fPath + '/image13.jpg' data = open(path_img,'rb').read() encoded_image = base64.encodestring(data) print(encoded_image[:10]) r = requests.post(url,data=encoded_image,headers=headers) On receiving end Code: @csrf_exempt def submitCauseData(request): response_data = {} if request.method == 'POST': data = request.POST myDict = dict(data) imageStr = list(myDict.keys()) imageStr = imageStr[0] print(imageStr[:10]) image_result = open('image.jpg', 'wb') image_result.write(base64.b64decode(imageStr)) return HttpResponse("Page Exists") So, the code is executing but when I try to Open the saved Image it shows the error Photo Source File missing? Thanks in advance -
Django with python ayncio to perform background task
I have two servers, A primary server that provide REST API to accept data from user and maintain a product details list. This server is also responsible to share product list (a subset of product data) with secondary server as soon as product is updated/created. Primary server written in Django. I have used django model db signal as product update, create and delete event. Now problem is that I don’t want to bock my primary server REST call until it populates detail to secondary server. I need some scheduler stuff to do that, i.e. create a task to populate data in background without blocking my current thread. I found python asyncio module comes with a function 'run_in_executor', and its working till now, But I don’t have a knowledge of the side effect over django run in wsgi server, can anyone explain ? or any other alternate ? I found django channel, but it need extra stuff like run worker thread separately, redis cache. -
How to add multiple images to a django form asynchronously before form submit
Intro: I have a python Django web app where users are allowed to create posts. Each post has 1 main image and followed by extra images (max 12 & min 2) that are associated with that post. I want to let users add a total of 13 images. 1 main image and 12 extra images. The issue: Usually users take photos with their smart phones. which makes image size upto 10MB . with 13 images that can become 130MB form. My django server is can accept only 10MB form. So I cannot reduce the images ServerSide What I want to do: I want such that when the user uploads each image to a form. The size of that image is reduced on client side and it is asynchronously saved in a temporary place on my server using Ajax. When the post is created all these images are linked to the post. So basically when the user hits submit on the post create form. Its a super light form with no images. Sounds too ambitious.. ha ha maybe What I have so far: I have the models/views (all django parts that create a post) without the asynchronous part. As in, if … -
How to properly handle getting value of html input into view and url pattern in Django?
I can not figure out why I'm getting a MultiValueDictKeyError when redirecting to a page trying to access data from an input in an html file to views.py. It appears that the view cannot find "main_search" in my html file. Basically what I'm trying to do is get the value from an input in an html file and use it for the url pattern and in views.py to display on that page. I have a feeling it's something painfully obvious, but I've had no luck figuring out the issue. Here is the error: Traceback: File "C:\Users\stovi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py" in getitem 77. list_ = super().getitem(key) During handling of the above exception ('main_search'), another exception occurred: File "C:\Users\stovi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\stovi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\stovi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\stovi\Desktop\simple_search\simple_search_site\main\views.py" in search_page 31. search = request.POST["main_search"] File "C:\Users\stovi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py" in getitem 79. raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /search=testing/ Exception Value: 'main_search' views.py: from django.shortcuts import render from django.http import HttpResponse import wikipedia def homepage(request): return render(request=request,template_name="main/search.html") def wiki_page(request): return render(request=request,template_name="main/wikis.html") def map_page(request): return render(request=request,template_name="main/maps.html") def video_page(request): return render(request=request,template_name="main/videos.html") def book_page(request): return render(request=request,template_name="main/books.html") def game_page(request): return render(request=request,template_name="main/games.html") def movie_page(request): return … -
Django two for Compare Values list update?
I would like to compare the values in the two statements and update them if there are any other values. @csrf_exempt def recommend_add(request): if request.is_ajax() and request.method == "POST": print(request.POST) category_list = request.POST.getlist('arr_category[]') lawyer_list = request.POST.getlist('arr_lawyer[]') print("category_list1=====", category_list) print("lawyer_list2=====", lawyer_list) for lawyer in lawyer_list: for lawyer in lawyer_list: ?????????????????????????? code = 0 msg = "TEST." data = json.dumps({ 'code': code, 'msg': msg, #'retURL': retURL }) return HttpResponse(data, content_type='application/json') console print..... category_list1===== ['1', '2', '3', '4', '5', '6', '7', '8', '9'] lawyer_list2===== ['65', '37', '57', '58', '130', '62', '38', '51', '110'] The value of category_list1 is fixed. 1=65 2=37 3=57 4=58 .......... When the value of lawyer_list2 is changed, I want to update. -
How to make a query with a custom order by parameter using array?
I have an algorithm that outputs an array in a particular order. Example: arr = [0, 1, 21, 2, 22, 23, 24, 25, 3, 27, 35, 36, 28, 37, 38, 4, 29, 5, 34, 6, 7, 8, 9, 10, 11, 12] The array will be different depending on the user's input so the example above is only one of many undefined amount of possibilities; longer, shorter or different values (all values will be integers). So I wont be able to use case in my query. I want to produce an SQL-Server query in my views.py to display all objects in my model in that exact order. Here is my "query" at the moment but obviously it doesn't work. test = QuoteAssemblies.objects.raw("""SELECT qmaQuoteAssemblyID, qmaPartID, qmaLevel, qmaPartShortDescription, qmaQuantityPerParent FROM QuoteAssemblies WHERE qmaQuoteAssemblyID IN arr ORDER BY qmaQuoteAssemblyID = arr""") In essence I want the query to be ordered by qmaQuoteAssemblyID as long as it is in the same order of the array (not ASC, DESC etc). qmaQuoteAssemblyID = 0 qmaQuoteAssemblyID = 1 qmaQuoteAssemblyID = 21 qmaQuoteAssemblyID = 2 etc... There is a similar example for MySQL Here. I just need something like that but for MSSQL. Cheers. -
How do I set query limit in template 'for post in user.post_set.all' ? (without using views)
I want to basically do something like this: {% for post in user.post_set.all[:3] %} But I do not know how to go about this. At the moment it is getting all the posts by the user, which is not what I want. Any way to do this without using views? -
Why is my Django server still serving old files after changing filenames and clearing cache?
I have made some changes to my Ubuntu server running Django with Apache. I modified some HTML, JS and CSS files, but nothing has changed. Things I have tried: -Clearing browser cache -Renaming files to try and circumvent cache. -Ran manage.py collectstatic -Restarted Apache -Rebooted server I was under the impression that changes to HTML files were reflected immediately in Django, so I am really baffled as to how it could still be serving the old version of the file. I have already checked that there are no duplicated files. I must be forgetting something. Any ideas, anyone? -
Celery not spawning task after changing time in crontab
I have a celery task that looks like this: 'spawner_for_tasks': { 'task': 'spawners_for_tasks', 'schedule': crontab( hour='17', minute='30' ) } This successfully spawned the task at 17:30 like I expected, but then I wanted to test it again and changed the minute to something else, but the task is not running again. Is this intended? I don't see anything in the documentation that says that. Here's the signature of the task itself: @celery_app.task() def spawners_for_tasks_due_notification_tasks(): pass -
Do I need to use virtual environment while using docker?
I didn't know what is the benefit of Docker over virtual environment. Is it necessary to use virtual environment and docker at the same time. Before today, Basically I used virtual environment to crate Django project. But today My friend recommended me to use docker. I'm confused what should i use ? I used this command to create virtual environment python3 -m venv virtual_environment_name Is this is best way to create virtual environment or should i use another way to create virtual environment -
What do you think of Django? in 2019
It's a beginner studying Django. Django + jquery, Django + react + redux, Django + graphql, etc I am confused because the range of choices is too great. First question Can you tell us what you need to study? Second question Is restframework almost essential when using Django + react? The third question The Python Django combination Is it bad for performance and stability compared to node js, java, go? Fourth question Is Python a promising language in the future? Is node js or go an alternative in the near future? -
Creating Page object programmatically got error ValidationError path and depth fields cannot be blank/null
I am trying to programmatically create a PostPage object. This class inherits from wagtail's Page model: post = PostPage.objects.create( title='Dummy', intro='This is just for testing dummy', body='Lorem ipsum dolor...', date=datetime.strptime(f'2019-01-01', '%Y-%m-%d') ) However, I am getting the following error: ValidationError: {'path': ['This field cannot be blank.'], 'depth': ['This field cannot be null.']} I need to create some dummy Page objects, so I wonder how I can solve this problem. -
On Circle Ci - selenium test case timeout issue with celery
On Circle Ci - selenium test case timeout issue with celery Problem- Can not open the browser to test the selenium test case using celery and circle ci. Without circle ci on local environment test case is executed successfully. Code- self.web_driver.get('%s%s' % (self.live_server_url, reverse('login'))) Error- raise exception_class(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: timeout (Session info: chrome=67.0.3396.99) (Driver info: chromedriver=2.40.565383 (76257d1ab79276b2d53ee976b2c3e3b9f335cde7),platform=Linux 4.4.0-141-generic x86_64) Description - Facing time out error while running the selenium test case with circle ci and celery. http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html Following standard live test case - https://docs.djangoproject.com/en/2.1/topics/testing/tools/#liveservertestcase @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() def test_login(self): ////////////////////error cause line//////////////////////// self.selenium.get('%s%s' % (self.live_server_url, '/login/')) username_input = self.selenium.find_element_by_name("username") username_input.send_keys('myuser') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('secret') self.selenium.find_element_by_xpath('//input[@value="Log in"]').click() Actually circle ci should run the selenium test case successfully with celery. I can run the same code on local machine but it is not running on circle ci server.