Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template conditional statement
I have the conditional statement below {% if juice.slug != "slug-one" or "slug-two" %} rendering things if the page slug isn't slug-one or slug-two {% endif %} For some reason this conditional statement only works when it isn't "slug-one", instead of when it isn't "slug-one" or "slug-two" . -
Upgrade Ruby on Python Elastic Beanstalk instance
my ruby -v is ruby 2.0.0p648 (2015-12-16) [x86_64-linux] on my Python EB instance. I need Ruby 2.2 to install sass. How can I get ruby 2.2? My .ebextensions has this: packages: yum: ruby-devel: [] rubygems: sass: [] But I still am only getting an old version of Ruby. -
Demonstrar o nome real object (1)
Como faço para demonstrar o nome real do dado registrado na tela de administração do django. o registro na tela é demostrado object (1), sendo que deveria mostrar o texto do registro . Ainda sou leigo, não sei se me fiz entender. -
Deleting file after countdown in django
I do system file-sharing and I have date, when file must be deleted automatically. How can I do this? It`s my model: class UploadModel(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) file = models.FileField(upload_to='uploads/', blank=False, null=False) created_date = models.DateTimeField(default=timezone.now) ended_date = models.DateTimeField() is_worked = models.BooleanField(default=True) -
Nested Serializer Through Shared Foreign Key
I have three models. Two of them are connected to their "parent" via a foreign key. I need to create a serializer. Here is my models.py class Student(models.Model): first_name = models.CharField(max_length = 35, blank=True) last_name = models.CharField(max_length = 35, blank=True) class Grade(models.Model): student = models.ForeignKey( "Student", null = True, on_delete = models.PROTECT, ) grade = models.FloatField(null = True) class Attendance(models.Model): student = models.ForeignKey( "Student", null = True, on_delete = models.PROTECT, ) total_exabs = models.IntegerField(null = True) Here is my serializers.py class StudentSerializer(serializers.BaseSerializer): def to_representation(self, student_obj): return { "id": student_obj.pk, "first_name": student_obj.first_name, "last_name": student_obj.last_name, } class GradeSerializer(serializers.BaseSerializer): def to_representation(self, grade_obj): return { "Grade PK": grade_obj.id, "Student": grade_obj.student.id, "Grade Value": grade_obj.grade, } class AttendanceSerializer(serializers.BaseSerializer): def to_representation(self, attendance_obj): return { "student": attendance_obj.student.id, "total_exabs": attendance_obj.total_exabs, } How do I create a fourth serializer that has attendance nested within grade? I essentially need every grade of a student to show their attendance as well. This is what I am wanting {"grade_id": "1", "grade" : "0.73", "student_id": "1", "attendance": {"attendance_id": "1", "total_exabs": "7"}} Thank you for any help you can offer! New to Django so thanks for your patience! -
How to set priority in task in django-background-tasks?
I run django web in development mode in windows powershell on windows server. I had some issues to make different tasks with different priorities, and run them in parallel instead of one by one. Tried to include "priority=1" in @background, it reported errors about no such parameters. @background(schedule=0, queue='1-qc-queue', priority=1) I even run two queue like "1-queue" and "2-queue" in two windows powershell "python manage.py process_tasks --queue 1-queue" "python manage.py process_tasks --queue 2-queue" but I saw all tasks are always with "priority=0" in background tasks table. Tried to run multiple tasks in parallel: BACKGROUND_TASK_RUN_ASYNC = True but window powershell quit immediately -
Django is_authenticated and @login_required both not working
I tried to make some pages only visible when logged in. I tried it with: def backend(request): if request.user.is_authenticated: return render(request, 'web/backend-index.html') else: return redirect(reverse('web:login')) and also with: @login_required def backend(request): return render(request, 'web/backend-index.html') The first code does not let me log in. The second code does not let me log in but the url changes too: http://127.0.0.1:8000/login/?next=/backend/ If I just render the view without checking if logged in, the login is working fine and I´ll be passed to the backend page. The whole code is on github: https://github.com/psmaster1/BrainSystems/tree/master/smarthome/web I don't get any error messages. It's just redirecting to the login page... -
Django admin CheckboxSelectMultiple widget not working for ManyToManyField
I'm using the below model where the default django users table has a many-to-many relationship with Hotel's. Assigning multiple users to a Hotel in the django admin panel is difficult, and I want to replace the default 'ctrl-click' method to a checkbox where I can select multiple users without having to hold down ctrl. Model: from django.db import models from django.contrib.auth.models import User class Hotel(models.Model): # associate the user user = models.ManyToManyField(User) # additional fields hotel_name = models.CharField(max_length=100) hotel_id = models.CharField(max_length=100) def __str__(self): return self.hotel_id admin.py from django.contrib import admin from .models import * from django.forms import CheckboxSelectMultiple # Checkbox for many-to-many fields class HotelAdmin(admin.ModelAdmin): formfield_overrides = { models.ManyToManyField: {'widget': CheckboxSelectMultiple}, } admin.site.register(Hotel) result: The formfield_override does not work, and selecting users to a hotel is not a checkbox -
How to upgrade Ruby on an Elastic Beanstalk Python instance?
I'm running a Django application on Elastic Beanstalk, but my new instance deployments are failing with: ERROR: Error installing sass: rb-inotify requires Ruby version >= 2.2. I guess I need to upgrade Ruby in order to fix this, right? How can I do that on a Python instance? Is there a container_command I can run to upgrade Ruby? -
How to create a class-based view for multiple file uploads
I am uploading multiple files and I would like to use classes in the models.py, forms.py, and also views.py so that I the code is easily changeable in one place and reused. The issue I am having is not understanding how to implement a class-based view for file uploads that allows me to create instances for reuse. I have tried to implement a class-based view as as shown below but I believe I need to insert an init method and insert self. on the attributes but I am confused being that there are functions such as reverse_lazy in the attributes. class FileUploadView(View): form_class = DocumentForm success_url = reverse_lazy('home') # want different url for every instance template_name = 'file_upload.html' # same for template_name def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): form.save() return redirect(self.success_url) else: return render(request, self.template_name, {'form': form}) The issue is code-blocked above. I want a different URL and template name for every instance of this class. -
What is the proper way to verify if a filter was used when searching on the database in Django?
I am asking for a suggestion abount how to detect which filters are being used by the user, a filtering system can have different options to get the data, but using if statements to check if a value comes in a POST and then add it to a filters set is not really a good option specially when there a lot of them. # Some if statements detecting if a filter is used (if it is not null in the POST) # Adding the filter to filters filters = { # filters after being added '{}__{}'.format('categories', 'exact'): request.POST['category'], '{}__{}'.format('price', 'gte'): request.POST['price'], # Only an example } products = Product.objects.filter(**filters) This works, but i just want to know what would you recommend. -
Add staff user permissions in admin with custom user model
There are a number of questions about this, but they all seem slightly different to what I need. I have a custom user model in my core app in models.py in django: from django.db import models from django.contrib.auth.models import * from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user""" pl = Permission.objects.filter(codename__in=["add_user", "change_user", "delete_user"]) if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) if user.is_staff: user.user_permissions.add(*pl) user.save(using=self._db) # required for supporting multiple databases return user def create_superuser(self, email, password): """Creates and saves a new superuser""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" def get_list_display(self): return ['email'] And my admin.py is like this: from django.contrib import admin from django.contrib.auth.backends import ModelBackend from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.utils.translation import gettext as _ from .models import User class UserAdmin(BaseUserAdmin, ModelBackend): list_display = ( "name", "email", "is_active", "is_staff", ) list_display_links = ("email",) list_editable = ( "name", … -
Why can't I get radio buttons when using RadioSelect form in Django?
I am working to build a page where the user can select a month via the use of radio buttons. I also need to collect other information with this such as first name, last name, email, phone number, and company. In doing this, I figured using Django forms should get the job done. I began and implemented everything and got to the part for the radio buttons. I found out I needed to do this using the ChoiceField and that RadioSelect is a widget of it. All of my choices are showing up, but I can't click on any of them to select them. Also, this is going to be a required question, and I am not sure how to make this a required form, as it can be left blank and I see it still will POST with no issues. I googled everything under the sun. I tried to set an initial selection for it, hoping that it would display at least one radio button, but that didn't do it. I tried just doing widget=forms.Select() instead of RadioSelect() and still the months display, but I can't select any of them. Not sure what to do. This is utilizing Django … -
How to use Amazon S3 as storage tools for static files?
I can use S3 for uploading file in frontend. But I cannot transfer my static files in heroku dyno to S3. AWS_ACCESS_KEY_ID = 'my key_id' AWS_SECRET_ACCESS_KEY = 'my_key' AWS_STORAGE_BUCKET_NAME = 'ssjh' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'btre.storage_backends.MediaStorage' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) I have substituted the key_id and key.It works well for uploading but not good for static files.And here is my file-tree: Here is my Amazon S3 console: -
How to configure tinymce to remove extra spaces in Django?
Recently I started using tinymce in my project and after posting I am getting extra white space between paragraphs. If I use ctrl+enter that helps a bit. I tried p{margin:0; padding:0;} that didn't helped as well. I searched documentation, but I couldn't find anything concerning this, maybe I couldn't find it. There must be something in configuration of tinymce in settings.py, I hope you help me. Thank you very much in advance -
path to image in html file (tree of dictionaries)
I have a problem with my project. I'm working on a university project based on Django and in fact we don't know HTML, CSS at all. I have a small hierarchy of catalogs: -> Project -> LibProject -> templates -> LibProject -> main.html -> images -> logo.png There LibProject and images are in the same level. I would like to add a logo.png via inside main.html file. I've tried to get 3 directories up and then go to images/logo.png but it doesn't work. PS: It has to be static image. May you give me any sollution for this? Thanks in advance! -
How can i validate url variabel in DRF(django rest framework) generic.ListView?
i want use url variables for my queryset in DRF generic.ListView but i can validate that anyway now i want know how can validate that i write below method but its dos not work class VideoView(generics.ListAPIView): def validate(self): print("ejra") if "class" not in self.request.GET: return Response({"error": "class should exist"}, status=status.HTTP_400_BAD_REQUEST) if len(Class.objects.filter(pk=self.request.GET["class"])) < 1: return Response({"error": "class not found"}, status=status.HTTP_400_BAD_REQUEST) def get_queryset(self): self.validate() class_obj = Class.objects.get(pk=self.request.GET["class"]) queryset = Video.objects.filter(study_class=class_obj).order_by("-date") return queryset serializer_class = VideoSerializer -
How to create custom output JSON from two serializers
I'am a newbie in Rest Framework in Django, and i have an excercise. I want to create custom JSON output from two Django models. I've already created two serialized views. The output JSON should be: { "movie_id": 2, "total_comments": 4, "rank": 1 }, { "movie_id": 3, "total_comments": 2, "rank": 2 }, { "movie_id": 4, "total_comments": 2, "rank": 2 } And the GET /top url should: -Should return top movies already present in the database ranking based on a number of comments added to the movie (as in the example) in the specified date range. The response should include the ID of the movie, position in rank and total number of comments (in the specified date range). -Movies with the same number of comments should have the same position in the ranking. -Should require specifying a date range for which statistics should be generated. I have two serializers: class CommentSerializer(serializers.ModelSerializer): class Meta: model= Comment fields=('movie','user','timestamp','content','approved') class MovieSerializer(DynamicFieldsModelSerializer,serializers.HyperlinkedModelSerializer): comments=CommentSerializer(many=True) comments=None class Meta: model = Movie fields = ('id','name','description','year','released','comments','rating') This is Comment model: class Comment(models.Model): movie = models.ForeignKey(Movie, on_delete=models.DO_NOTHING,related_name='comments',blank=True,null=True) content = models.TextField() timestamp = models.DateTimeField(default=timezone.now) user=models.CharField(max_length=250) I tried to do that on my own by this trick: class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class … -
Got VariableDoesNotExist at dashboard Ranges create\update view. Reffers at {% annotate_form_field field %}
Got VariableDoesNotExist at {{url}}/shop/dashboard/ranges/2/ whyn try edit\create or do any aactions with that model. Got Failed lookup for key [field] in "[{'False': False, 'True': True, 'None': None}, {}, {}, {'title': 'Ranges', 'form': , 'range': , 'basket': >, 'object': , 'view': }]" All is stock, Aldryn-django-oscar 1.6.4.2 -
Django local server: Atomic Database from a text file
I made a Web app that takes in a text file, reads each line, takes the 11th character and saves it to SQLite3 db. How do I lock the database or have two or more separate tables while multiple requests are running? I have added adding ATOMIC_REQUESTS': True to the settings.py in Django. and I tried creating temporary tables for each request, but can't figure it out. I am pretty fresh to Django 2.2 My View.py def home(request): if request.method == 'GET': return render(request, 'home.html') if request.method == 'POST': form = DocumentForm(data=request.POST, files=request.FILES) print(form.errors) if form.is_valid(): try: f = request.FILES['fileToUpload'] except: print('\033[0;93m'+ "No File uploaded, Redirecting" +'\033[0m') return HttpResponseRedirect('/tryagain') print('\033[32m'+ "Success" +'\033[0m') print('Working...') line = f.readline() while line: #print(line) mst = message_typer.messages.create_message(str(line)[11]) line = f.readline() else: print('\033[0;91m'+ "Failed to validate Form" +'\033[0m') return HttpResponseRedirect('/output') return HttpResponse('Failure') def output(request): s = message_typer.messages.filter(message='s').count() A = message_typer.messages.filter(message='A').count() d = message_typer.messages.filter(message='d').count() E = message_typer.messages.filter(message='E').count() X = message_typer.messages.filter(message='X').count() P = message_typer.messages.filter(message='P').count() r = message_typer.messages.filter(message='r').count() B = message_typer.messages.filter(message='B').count() H = message_typer.messages.filter(message='H').count() I = message_typer.messages.filter(message='I').count() J = message_typer.messages.filter(message='J').count() R = message_typer.messages.filter(message='R').count() message_types = {'s':s, 'A':A, 'd':d, 'E':E, 'X':X, 'P':P,\ 'r':r, 'B':B, 'H':H, 'I':I, 'J':J, 'R':R } output = {'output':message_types} #return HttpResponse('Received') message_typer.messages.all().delete() return render(request, 'output.html',output) When the … -
In DJANGO, i have a function in a module that generates HTML, how can i add it to template?
I have a custom module which has a few functions in it. I've been using the functions with no issues but I have a new functions now that generates some HTML. It generates a HTML table. What's the best way to print the HTML in a template (as HTML code)? I successfully made the HTML output and tested it in raw HTML. It's formatted the way I want but I can't seem to figure out how to get it to display as HTML in the template? Can I accomplish this without using a template tag? -
How to redirect django-datatables-view to proper HTML template?
I'm setting up a web app/database with the django framework. I'm trying to view the results from a query, with user input values from a form, into a datatable on another page using django-datatables-views. My_project/search/views.py class index(View): def get(self, request): return render(request, 'search/index.html') class OrderListJson(BaseDatatableView): template_name = "search/results.html" order_columns = ['column1', 'column2'] def get_initial_queryset(self): db = Database('default', readonly=True) qs = Some_table.objects_in(db) def filter_queryset(self, qs): search_id = self.request.POST.get('textfield', None) qs = qs.filter(column1=search_id) return qs def prepare_results(self, qs): json_data = [] for item in qs: json_data.append([ escape(item.column1), escape(item.column2), ]) return json_data My_project/search/urls.py urlpatterns = [ path('', index.as_view(), name='index'), path('search/', OrderListJson.as_view(), name='order_list_json'), ] My_project/search/template/search/results.html {% extends 'layout.html' %} {% block head %} <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> <style type="text/css" class="init"> </style> <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script> <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script type="text/javascript" charset="utf8" src="../../../templates/js/datatableview.js"></script> <script type="text/javascript" class="init"> $(document).ready(function() { var oTable = $('.datatable').dataTable({ // ... "processing": true, "serverSide": true, "ajax": "{% url 'order_list_json' %}" }); // ... }); </script> {% endblock %} {% block content %} {{ datatable }} {% endblock %} I only see the json object. {"draw": 0, "recordsTotal": 168470170, "recordsFiltered": 2380, "data": [["4059", "233"], ["17099", "198"]], "result": "ok"} Instead of the datatable embedded in my formated results.html page. How do I make … -
AttributeError at /orders/create/ 'tuple' object has no attribute 'get'
I am trying to make an e-commerce website where the user submits the order and is redirected to the payment interface (Paytm ,India) . However i get this error: ERROR views.py (In my orders app) from django.shortcuts import render from .models import OrderItem , Order from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from .forms import OrderCreateForm from cart.cart import Cart from payTm import Checksum from django.http import HttpResponse MERCHANT_KEY = 'my_merchant_key'; @csrf_exempt def handlerequest(request): return HttpResponse('done') pass @login_required def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create( order=order, product=item['product'], price=item['price'], quantity=item['quantity'], total_price=item['total_price'], ) cart.clear() param_dict = { 'MID': 'my_merchant_id', 'ORDER_ID': str(order.id), 'TXN_AMOUNT': str(order.total_cost), 'CUST_ID': order.email, 'INDUSTRY_TYPE_ID': 'Retail', 'WEBSITE': 'WEBSTAGING', 'CHANNEL_ID': 'WEB', 'CALLBACK_URL': 'http://127.0.0.1:8000/handlerequest', } param_dict['CHECKSUMHASH'] = Checksum.generate_checksum(param_dict, MERCHANT_KEY) return render(request, 'paytm.html', {'order': order}, {'param_dict': param_dict}) else: form = OrderCreateForm() return render(request, 'create.html', {'form': form}) paytm.html {% extends 'base.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Paytm merchant Payment Page</title> </head> <body> <h1> Redirecting you to the merchant.....</h1> <h1> Please don't refresh this page.....</h1> <form action="https://securegw-stage.paytm.in/theia/processTransaction" method="POST" name="paytm"> {% for key,value in param_dict.items %} <input type="hidden" name="{{ key }}" value="{{ value }}"> {% endfor %} </form> … -
Disable Django admin
I'm in a selection process and I must develop a software in Django with the restriction of not being able to use the admin included in the framework. I tried removing it from the INSTALLED_APPS. But when I run a migration I get the error: 'No installed app with label 'admin' Is there any other configuration that I should do or what is the correct way to do it? -
Why TinyMCE isn't working in this project?
I followed the following steps to setup tinymce in mywebsite: python -m pip install django-tinymce4-lite added 'tinymce' in installed apps added TINYMCE_DEFAULT_CONFIG in settings.py path('tinymce/', include('tinymce.urls')), in urls.py and finally from tinymce import TinyMCE class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class BlogForm(forms.ModelForm): title = forms.CharField() content = forms.CharField( widget=TinyMCEWidget( attrs={'required': False, 'cols': 30, 'rows': 10} ) ) image = forms.ImageField() class Meta: model = BlogPost fields = [ 'title', 'content', 'image' ] after running the server it doesn't shows any error and it is not working, please help me fix it, thank you.