Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
After uploading Image in Django Admin panel, I am unable to see it in my template?
I have successfully uploaded image from my admin panel by using ImageField in my model.py but i am not able to see the effect in my template. please check out the below code and the screenshots. thanks in advance for help me out. I can upload image, change image ... in my admin(localhost:8000/admin) but the problem is, I can not see the image in (localhost:8000). opportunity.html {% extends "frontend/base.html" %} {% load static %} {% block title %}Opportunities{% endblock %} {% block content %} <section id="blog" class="container"> <div class="blog"> <div class="row"> <div class="col-md-10"> <div class="blog-item"> <div class="row"> <div class="col-xs-12 col-sm-2"> </div> <div class="col-xs-12 col-sm-10 blog-content"> <a href="#"><img class="img-responsive img-blog" src="{{ opportunity.image1 }}" width="100%" alt="" /></a> <h4>{{ opportunity.heading1 }}</h4> <p>{{ opportunity.subheading1 }}</p> <a class="btn btn-primary readmore">{{ opportunity.link1 }} <i class="fa fa-angle-right"></i></a> </div> </div> </div> </div> <aside class="col-md-4"> </aside> </div> </div> </section> {% endblock %} views.py def opportunities(request): navbar = get_object_or_404(Navbar, ~Q(status='draft')) opportunity = get_object_or_404(Opportunity, ~Q(status='draft')) context = { "opportunity": opportunity, "navbar": navbar, } return render(request, 'frontend/opportunities.html', context) admin.py class OpportunityAdmin(admin.ModelAdmin): list_display = ('heading1', 'author', 'published', 'status',) list_filter = ('status', 'created', 'published', 'author') admin.site.register(Opportunity, OpportunityAdmin) models.py class Opportunity(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) image1 = models.ImageField(upload_to = 'pic_folder/') heading1 … -
How to filter a foreign key field in django?
Here is my model : class Movie(models.Model): title = models.CharField(max_length=300, unique=False, default='', null=True) kind = models.ForeignKey(Kind, on_delete=models.DO_NOTHING, default='', null=True) class Kind(models.Model): kind = models.CharField(max_length=200, help_text='Enter a movie kind (e.g. serial)') def __str__(self): return "{}".format(self.kind_eng) And this the controller : def info(request, id): movie_info = Movie.objects.get(id=id) ... How to write a queryset to get each movie kind? -
Q: List of dict access with mongoengine in django
how to get particular dictionary from the list of dictionaries using mongoengine in django. As specified below data structure if I want to fetch the dictionary having the student_id as "1011". how to do and how to update that dictionary only one? Data structure like that : class studentData(Document): student_class = StringField(required=True) student_list = ListField() Data store in DB sample: { "student_class":10. "student_list":[ { "student_id" : "1011", "student_name" : "ABC" }, { "student_id" : "1045", "student_name" : "XYZ" } ] } I am try this is give me student_list but how to I get list of specific dictionary : studen_list= studentData.objects.filter(student_class=10).values_list('student_list')[0] -
How to execute python code on my website?
I am trying to build a website using Django in which I want to provide a field in which the users can type their python code and they should get the output. Can anyone help me to do this? Thanks. -
Django Rest Framework serilaizers limit the choices
choices.py from django.utils.translation import gettext as _ ACCESS_CHOICES = ( (1, _("super_admin")), (2, _("admin")), (3, _("accountant")), (4, _("consultant")) ) models.py class MyModel(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="works", on_delete = models.CASCADE) access = models.IntegerField(choices=app.choices.ACCESS_CHOICES) serializers.py class MyUPDATESerializer(serializers.ModelSerializer) class Meta: model = MyModel fields = ['access'] I would like to limit the choices shown to a user during update through the serializers. Eg: ACCESS_CHOICES = ( (3, _("accountant")), (4, _("consultant"))) or ACCESS_CHOICES = ( (2, _("admin")), (4, _("consultant"))) The choices shown depends on the user updating the access. How to achieve this? -
Authentication credentials were not provided. when deployed to AWS
I created some apis on django project using django rest framework. I set IsAdminUser to permission classes. When I run the project locally and make a request to it with auth info, it works. I deployed it to AWS server by using Elasticbeanstalk and make a request and it returns error 403 Authentication credentials were not provided Here is my API class HamListApiView(ListAPIView): queryset = Ham.objects.all() serializer_class = HamSerializer permission_classes = [permissions.IsAdminUser] What am I missing here? -
Django2 Pagination with Datatables JQuery Server Processing
I'm sock with datatables, I don't know why data always keep changing when I clicking back the pagination number that is already view. Let say Im already on page 3 when clicking back page 2 the data changed. What is wrong with the datatables? -
django Python parsing json data
parse the data from the api and then get the values id and title and put on to select menu. JSON link : https://api.myjson.com/bins/16tdlw Code in getting the data def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) stores = requests.get('https://api.myjson.com/bins/g30jo').json() context['stores'] = stores context['rules'] = json.loads(self.object.rules) context['rule_data'] = json.loads(self.object.rule_data) return context get id and title from the json and then put <select> {% for store in stores %} <option value="store.id">{{store.title}}</option> {% endfor %} </select> any problem with the code? -
Django Dir Templates not set correctly
I need help to load correctly the templates. Followed the django documentation and load my templates in the templates dir. What i need, is to change default django name to my own name. I customized my base_site.html, but still the names from my code doesn't show, therefore i think the path is broken. Can someone please help me to fix the dirs correctly? TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 'DIRS': [os.path.join(BASE_DIR,'templates')], 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, That is how my code looks like -
Django phone number field with country
How to create a phone number field in django form that would take just the phone number without international code. User should be able to choose a country first and then django should validate the number based on users country. Validation should be country specific. Eg: user would choose 'US' then django should look for numbers that are 10 digit and dont start with 0, else generate error. Django's phonenumber-field package has a mandatory requirement for international code. so if a user doesnt know her country phone code ( which is very normal) user wont be able to enter a valid phone number. Django's PhoneField package displays an extension field on the webpage which is unnecesary and I could not find any documentation showing examples using this package. Thanks -
FFmpeg in Python File already exists error
I'm working on a project using python(3.6) and Django(2.0) in which i'm converting a video to mp4 if it's in any other formate. Here's my code: from views.py: def generate_thumbnail(filename, thumb_name): print('func called') print(filename) video_input_path = os.path.join(filename) img_output_path = os.path.join(thumb_name) subprocess.call(['ffmpeg', '-i', video_input_path, '-ss', '00:00:00.000', 'vframes', '1', img_output_path]) def convert_to_mp4(video_name, only_name): os.popen( "ffmpeg -i '{input}' -ac 2 -b:v 2000k -c:a aac -c:v libx264 -b:a 160k -vprofile high -bf 0 -strict experimental -f mp4 '{output}.mp4'".format( input=video_name, output=only_name)) return True def perform_upload(video, thumbnail): print('vdieo name is: {}'.format(video)) servise = discovery.build('storage', 'v1', credentials=credentials) bucket_name = 'test_bucket004' print('Uploading the video...') media = MediaFileUpload(video, chunksize=4149304, mimetype='video/mp4', resumable=True) req = servise.objects().insert( bucket=bucket_name, name=str(video), media_body=media, body={"cacheControl": "public,max-age=31536000"}, predefinedAcl='publicRead' ) resp = None while resp is None: status, resp = req.next_chunk() print(resp) video_url = 'http://storage.googleapis.com/' + bucket_name + '/' + str(video) print('Uploading your thumbnail...') media = MediaFileUpload(thumbnail, chunksize=4149304, mimetype='image/jpeg', resumable=True) req = servise.objects().insert( bucket=bucket_name, name=str(thumbnail), media_body=media, body={"cacheControl": "public,max-age=31536000"}, predefinedAcl='publicRead' ) resp = None while resp is None: status, resp = req.next_chunk() print(resp) thumb_url = 'https://storage.googleapis.com/' + bucket_name + '/' + str(thumbnail) return video_url, thumb_url class VideoConverter(generics.ListCreateAPIView): def get(self, request, *args, **kwargs): return HttpResponse('Get request', status=200) def post(self, request, *args, **kwargs): serializer = VideoConverterSerializer(data=self.request.data) validation = serializer.is_valid() print(serializer.errors) if … -
return a different object from view set object python django
I have the following Viewset I have the following models NoteRequest and NoteInfo class NoteRequestViewSet(viewsets.ModelViewSet): queryset = NoteInfo.objects.all() serializer_class = NoteInfoSerializer pagination_class = None print(queryset) print(serializer_class) def list(self, request): try: obj = self.get_queryset().get( Q(refno=pk) | Q(client_id=pk) ) serializer = self.get_serializer(obj) return Response(serializer.data) except Exception as e: return Response(str(e)) I want to be able to return a serialized object of NoteInfo rather than NoteRequest but not sure how to do it. Thanks -
S3; Bucket that is not public doesn't work suddently
I've been working on Django project. My static files don't work suddenly yesterday both on local and production like this and I found out all most all files cannot open on S3. It shows like <AccessDenied>. I found out I can fix this by changing bucket policy. Static files do work now, but when I changed it to public, it says This bucket has public access You have provided public access to this bucket. We highly recommend that you never grant any kind of public access to your S3 bucket. So I'm wondering if there's better way to make static files work. Static files did work even if the bucket is not public but didn't work suddenly. I'm wondering why. -
Unicode Decode for Weasy Print
Trying to build a simple Weasy Print Application with Django Made a little function at views.py: def generate_pdf(request): # Model data students = Student.objects.all().order_by('last_name') context = { 'invoice_id': 18001, 'street_name': 'Rue 76', 'postal_code': '3100', 'city': 'Washington', 'customer_name': 'John Cooper', 'customer_mail': 'customer@customer.at', 'amount': 1339.99, 'today': 'Today', } # Rendered html_string = render_to_string('pdf/invoice.html', context) html = HTML(string=html_string) result = html.write_pdf() # Creating http response response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'inline; filename=list_people.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'r') response.write(output.read()) return response After running it I get a UnicodeDecodeError for the line "response.write(output.read())" This is my first time having such a problem, how can I fix that? Thanks! -
Dajngo: request.user and request.session
I am using session to Login and logout user, when user logs in it creates a session and when user logs out it deletes a that session, So, when i am typing request.user, despite of loged in and in a active session it shows Annonymous User. So, Is not request.user recognizing session? -
Django website running on Azure web app extremely slow
I have a django web app which I have deployed to an Azure web app (running on the B1 app service plan). The website works as intended, except for the loading time which can routinely take up to 10 minutes to load a single page (even with cached static files). While I have not correctly set up a web hosting platform and are instead simply running the server using the default manage.py system, the website still should not be running this slowly. Is there a simple way to fix this problem? -
Django - How to make an HTML button work with function views by using JS
I have a add_to_cart button which is expected to edit model instances when it's clicked. I have no idea how to connect an HTML button and a Django function view by using JavaScript properly. The button does nothing at the moment. Also I want to pass the quantity to the template from the view. cart/views.py: def add_books(request): response_data = {} c = Cart.objects.get(user=request.user) q = request.GET.get('quantity') book_id = request.GET.get('bookID') ............................................ response_data['quantity'] =BooksInCart.objects.filter(cart=c).aggregate(item_quantity=Sum('quantity'))['item_quantity'] return HttpResponse(json.dumps(response_data), content_type="application/json") cart/urls.py: app_name = 'cart' urlpatterns = [ path('add_books/', views.add_books, name='add_to_cart') ] cart/static/cart/add_to_cart.js: $('#add').click(function(){ $.get('cart/add_books/',function (quantity){ ("#cartButton").text("Cart" + "(" + quantity + ")"); }) }); book/templates/book/detail.html: <form method="get"> {% csrf_token %} <select name="quantity"> <option>1</option> <option>2</option> <option>3</option> </select> <input name="bookID" value=" {{ book.id }} " hidden> <button id="add" type="submit"> Add to Cart</button> </form> -
How to display markup instead of text in Form field with choices?
I am trying to display a form that uses Font Awesome icons. I have the field emotion which contains EMOTIONS as choices, and I want to display the font awesome icon related to each option. I have tried just adding the markup (see the last option of EMOTIONS). However, this is rendering exactly the markup text instead of the icon. Is it possible to display the Font Awesome icon in the way I am trying? This is my form: class PreferencesForm(forms.Form): EMOTIONS = [ ('😂', 'Joy'), ('😢', 'Sad'), ('😡', 'Angry'), ('😫', 'Tired'), ('🙂', '<i class="far fa-smile"></i>'), ] FAMOUS_PEOPLE = [ ('US', 'Abraham Lincoln'), ('MX', 'Frida Khalo'), ('IT', 'Leonardo da Vinci'), ('FR', 'Napoleon Bonaparte'), ('JP', 'Hayao Miyazaki'), ] emotion = forms.ChoiceField(choices=EMOTIONS, widget=forms.RadioSelect()) famous_person = forms.ChoiceField(choices=FAMOUS_PEOPLE, widget=forms.RadioSelect()) This is my markup: <form action="." method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> How can I display the corresponding font awesome icon instead of the markup? -
How to edit form entry in a modal
I have a form that is accessed via a modal as described in the below code. I am able to click on new-lesson-plan-modal and use the generated form to input a new post entry, which will then be displayed back on the html. My question is, how do I edit the post entries via edit-lesson-plan-modal? The buttons have been created. But i'm not sure how to hook up the button to the modal, such that it will retrieve the records for the relevant post entry, to be edited on the form. Any ideas? Views.py def home(request, pk=None): if request.user.is_authenticated: # Adding lesson plans if 'update_lesson_plan' in request.POST: lesson_plan_page_data = LessonPlans.objects.all() edited_lp = NewLessonPlansForm(request.POST) if edited_lp.is_valid(): edited_lp.save() else: # get # Lesson Plans Section lesson_plan_page_data = LessonPlans.objects.all() edited_lp = NewLessonPlansForm() args = { 'lesson_plans': lesson_plan_page_data, 'edited_lp': edited_lp, } return render(request, 'static/html/home.html', args) home.html <div class="container-fluid"> <table class="table" id="id_view_lesson_plan"> <caption><small>Lesson Plans</small></caption> <thead> <tr> <th scope="col">Level</th> <th scope="col">Lesson</th> <th scope="col">Description</th> <th scope="col"> <span data-toggle="tooltip" title="Add new Lesson Plan"> <button type="button" class="btn new-lesson-plan-modal" data-toggle="modal" data-target="#lesson-plan-modal"> <i class="fas fa-plus"></i> </button> </span> </th> </tr> </thead> <tbody> {% for lp in lesson_plans %} <tr> <td>{{ lp.level }}</td> <td>{{ lp.lesson }}</td> <td>{{ lp.description }}</td> <td> <span data-toggle="tooltip" title="Edit … -
How to extract specific data in results obtained from using Python Requests library
Please take a look at the code below: @login_required def dashboard(request): code = request.GET.get('code', '') payload = { "client_id" : settings.GITHUB_CLIENT_ID, "client_secret" : settings.GITHUB_CLIENT_SECRET, "code" : code, "state" : settings.STATE, } response = requests.post('https://github.com/login/oauth/access_token', params=payload) # final_response = requests.get('https://api.github.com/user', auth=GitHubTokenAuth(access_token)) return HttpResponse(response) # authenticated_user = final_response.json() # return render(request, 'core/dashboard.html', {'authenticated_user':authenticated_user}) The response variable is returning values similar to: access_token=eiwfbvdsvefieebrferferwfreferfersfwrb&scope=a%20list%20of%20scopes&token_type=bearer How do I access the value of access_token so I can use as seen in the value of the commented out final_response variable? Thanks in anticipation! -
Using Django validators with admin - TypeError: "object of type 'int' has no len()"
so I have an eCommerce customer-facing app with a Django Admin interface. I want employees who will be using the admin to be able to create users. The problem is the custom validation I built in applies to the customer-facing side only, and when an employee wants to create a new user using the admin, my use of Django Validators throws an error when attempting to create the user. I was wondering if (1) there was a way to reuse my UserManager class (inherited from models.Manager) which handles the customer-side validation, with Django admin also. If not, then (2) if I was to rely on Django Validators how could I clean up the code as to not throw errors like: TypeError: "object of type 'int' has no len() I've done a little homework trying to figure this out and found this thread: TypeError: object of type 'int' has no len() error assistance needed This basically explains the error being thrown for this example is because it's trying to call len() on an int instead of a list. What I don't get is why don't I get this same error on the customer-facing side when a user signs himself up? At … -
json.dump not converting python list to JS array
When I attempt to pass a python list through to JavaScript in the template it doesn't parse the list into an JS array as expected but instead returns this [&quot;Groceries&quot;, &quot;Clothing&quot;, &quot;Takeaways&quot;, &quot;Alcohol&quot;] causing the page to break. view.py def labels(): category_labels = [] for item in Purchase.objects.order_by().values_list('type', flat=True).distinct(): category_labels.append(item) return category_labels def index(request): try: purchases = Purchase.objects.all().order_by('-time') total_spending = round(Purchase.objects.aggregate(Sum('amount'))['amount__sum'], 2) except Purchase.DoesNotExist: raise Http404("Could not find any purchases.") context = { 'purchases': purchases, 'total_spending': total_spending, 'spending_by_category': prepare_total_spending(), 'total_spending_all_categories': total_spending_all_categories(), 'labels': json.dumps(labels()), } return render(request, 'main/index.html', context) index.html <script type="text/javascript"> console.log(JSON.parse("{{labels}}")) # => converts this to console.log([&quot;Groceries&quot;, &quot;Clothing&quot;, &quot;Takeaways&quot;, &quot;Alcohol&quot;]) in JS and breaks. </script> -
How do I find out why my 404 handler is generating a 500 error?
Here is my 404 view: def handler_404(request): response = render(request, '404.html') response.status_code = 404 return response It seems this code is generating a 500 error, but I'm not seeing any kind of error output in the terminal where I have the django development server running. I had to set DEBUG = False to see if my custom 404 page would be rendered, seems it isn't working but generating a 500 error. -
What specific exceptions represent a serialization failure when Django is using serializable transaction isolation level with postgresql?
Sometimes it's desirable to use a higher isolation level than the default "read committed" for database operations in Django. The docs warn that: Under higher isolation levels, your application should be prepared to handle exceptions raised on serialization failures. But which specific exceptions indicate a serialization failure, versus some other problem with the query or transaction? A simple retry mechanism after a serialization failure might look like something like this: for retries in range(0, 3): try: with transaction.atomic(): MyModel.objects.update(foo='bar') except StuffHappened: continue else: break What specific exceptions should replace StuffHappened so that only serialization failures, and not other exceptions, result in a retry? Django has a variety of Database Exceptions and Transaction Exceptions. Might one/some of those represent serialization failures? I'm specifically interested in postgresql for this. -
Django sessionid disappears from cookies, user becomes anonymous
I have developed a web application with Django, using Pyrebase as the database, and have just deployed it using Google App Engine. I am having issues with the sessionid, but only on the web server - not when I run the app locally. What happens on the web server is once the user is authenticated, the user's ID token is stored in the session dictionary via request.session['uid'] = idToken. When the user is directed to the home page, the app tries to retrieve idToken from the sessions dictionary, which sometimes works and sometimes doesn't. When it does work, it loads some user data on the home page, but when the user clicks on another page, it continues to randomly work or not. A couple things I noticed are: When I watch the storage section of the developer console, I see that the session storage and local storage remain empty, while Cookies carries the sessionid and csrftoken variables. Every time a new page is loaded, the sessionid is set to a new value - this doesn't happen when I run it locally. Eventually, the sessionid disappears from Cookies, and the error in the console reports that the user is actually anonymous. …