Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 404 error when loading <img> tag inside template
I have ~26k pictures inside my static folder that I want to load using a template that I have in Django {% for movie in movies %} <div class="col-6 col-sm-12 col-lg-6"> <div class="card card--list"> <div class="row"> <div class="col-12 col-sm-4"> <div class="card__cover"> <img src="{% static 'img/covers/{{ movie.movie_id }}.jpg' %}"> <a href="/movie/{{ movie.movie_id }}" class="card__play"> <i class="icon ion-ios-play"></i> </a> </div> </div> <div class="col-12 col-sm-8"> <div class="card__content"> <h3 class="card__title"><a href="/movie/{{ movie.movie_id }}">{{ movie.movie_title}}</a></h3> <span class="card__category"> <a href="#">Comedy</a> <a href="#">Adventure</a> </span> <div class="card__wrap"> <span class="card__rate"><i class="icon ion-ios-star"></i>{{ movie.movie_rating }}</span> <ul class="card__list"> <li>HD</li> <li>16+</li> </ul> </div> <div class="card__description"> <p>{{ movie.movie_overview }}</p> </div> </div> </div> </div> </div> </div> {% endfor %} The line <img src="{% static 'img/covers/{{ movie.movie_id }}.jpg' %}"> is where I am facing an issue, the console shows img/covers/&7B&Dmovie.movie_id&3B&D.jpg -
Summernote custom buttons in Django Admin
I want to create a preview button in a summernote editor within Django Admin UI. I put the following config in setting.py file: SUMMERNOTE_CONFIG = { 'summernote': { 'airMode': False, 'width': '100%', 'height': '600', 'lang': 'fr-FR', 'toolbar':[ ['style', ['bold', 'italic', 'underline','clear']], ['style', ['strikethrough', 'superscript', 'subscript']], ['fontname',['fontname','fontsize']], ['fontname',['color']], ['para', ['ul', 'ol', 'paragraph','height']], ['table', ['table','picture','hr']], ['undo redo', ['undo','redo']], ['fullscreen help', ['fullscreen','help']], ['preview', ['preview']], ], 'buttons': { 'preview': 'PreviewButton' }, }, 'js': ( '/static/summernote-ext-print.js', ), } in the summernote-ext-print.js file I've added the following: var PreviewButton = function (context) { var ui = $.summernote.ui; // create button var button = ui.button({ contents: '<i class="fas fa-print"/>', tooltip: 'Preview', click: function () { context.invoke('editor.insertText', 'hello'); } }); return button.render(); // return button as jquery object } But in Django Admin UI the button is not rendered. See secreenshot What's wrong in my code ? Regards. -
How can I dynamically add rows to my form?(Django)
I have a Model which connects to a Form. You can assume it is a very simple model with 1 attribute. class Past_Location(models.Model): location = models.CharField(max_length=100) I want to let the user be able to add more rows to the form via a button. So that's why I reflect this model to a formset: LocationFormSet = forms.modelformset_factory( Past_Location, fields='__all__', extra=1, widgets={ 'location': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter Location Name here' } ) } ) Here is the button creation to add more rows. <div class="input-group"> {{ form.name }} <div class="input-group-append"> <input type="text" name="name" value=""> <button id="add" type="button" class="btn btn-success add-form-row">+</button> </div> </div> I thought the class "add-form-row" would be enough to add more rows dynamically but it was not. So I wanted to follow some examples and use jquery to add more rows. However, since my form is reflected from a model, I don't know how to access and add a new row via jquery. I wanted to post a MVP however the project is too complex with too many necessary files. So I would want to know what is the standard way of interacting with modelForms through jquery? -
Python: Execute a program only file times, after that it should be expire
A program that executes the message "Hello" only 5 times after that if we execute it then it should print the message "demo expired" using file handling concepts. e.g: 1>py Hello.py Hello 2>py Hello.py Hello 3>py Hello.py Hello 4>py Hello.py Hello 5>py Hello.py Hello 5>py Hello.py Sorry, your no. of Demo is Expired -
How to display searched results content same as it is in home page. (django)
I want my search results to work same as it is working in home page.but i'm getting errors after clicking links on search results. urls.py views.py module.py search_results.html -
Django context/template : Rendering multiple results
I have this code that I want it to be able to return multiple products. Now it only return the last one. I think it is because the variables are being overwritten but I don't know other ways to fix it. def result(request): rawquery = request.GET.get('q') #gets the product name to search from a form Product_set = Product.objects.filter(name__icontains=rawquery).distinct() for product in Product_set: name = product.name id = product.id store_name = product.store_name Price_set = Scan.objects.filter(product=id) for price in Price_set: current_price = price.price context = { 'name': name, 'store_name': store_name, 'price': current_price, 'query': rawquery } return render(request, 'result.html', context) This is the template % {extends 'base.html' %} {% block content %} <h1>Results for {{ query }} </h1> <p> {% if name %} {{name}} {% else %} None {% endif %} | {% if store_name %} {{store_name}} {% endif %} | {% if price %} {{price}} {% endif %} </p> {% endblock content %} -
How to convert Django Q object to SQL String
I was working with Django Q object to compose a query. I then switched my query to raw SQL because of the complicated features it needed. I want to convert the Django query composed of Q objects to convert to SQL WHERE clause. Is there any way I could do that? -
How to build a global search option for Django website having multiple models
I have three installed apps in Django which act as three sub web pages in a website. Each app has its own model (some columns like title, pub-date, etc.) and its own search functionality (which searches through each of the column in a model). Now, I want to add a global search option to the whole website which can search through all these three models (of the three apps) via a key word. Is this possible? If so, can anyone guide me please? -
In migration: AttributeError: 'Profile' object has no attribute 'set_password', using custom UserManager
Django 3.0.3 I have app account and can create superuser by migrate.py createsuperuser Here is some content of models.py: class CustomUserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user ... def create_superuser(self, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class Profile(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='E-mail', unique=True, ) first_name = models.CharField(verbose_name='first name', max_length=30, blank=True) last_name = models.CharField(verbose_name='last name', max_length=150, blank=True) ... objects = CustomUserManager() USERNAME_FIELD = 'email' class Meta: verbose_name = 'user' verbose_name_plural = 'users' ... And I'm trying to set data migrate. Firstly I run manage.py makemigration, then create empty migration and here it is def create_admin(apps, schema_editor): Profile = apps.get_model('accounts', 'Profile') Profile.objects.create_superuser( email='admin@mail.ru', password='123' ) class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.RunPython(create_admin), ] Then running manage.py migrate and getting error: AttributeError: 'Profile' object has no attribute 'set_password'. In settings.py I also have AUTH_USER_MODEL = 'accounts.Profile' -
Removing quotation marks from date in django template
Please this is what I have ['2020-03-03', 35.83483379334211] but I wanted [2020-03-03, 35.83483379334211] in my Django template so I can render it in highchart js.Any help? -
django oauth toolkit user registration
I implemented django oauth toolkit to my project so I can handle to login a user and get the access token, but I have no idea how to register a user and then create a new access token. Can anybody help me creating the registration view? client type: confidential grant type: password serializers.py class UserRegisterSerializer(serializers.ModelSerializer): confirm_password = serializers.CharField() class Meta: model = user_models.User fields = [ 'username', 'first_name', 'last_name', 'email', 'password', 'confirm_password', ] extra_kwargs = { 'confirm_password': {'read_only': True} } def validate(self, data): try: user = user_models.User.objects.filter( username=data.get('username')) if user.exists(): raise serializers.ValidationError(_('Username already exists')) except user_models.User.DoesNotExist: pass if not data.get('password') or not data.get('confirm_password'): raise serializers.ValidationError(_('Empty password')) if data.get('password') != data.get('confirm_password'): raise serializers.ValidationError(_('Password mismatch')) return data -
Can we run a python program on clicking an HTML button in a hosted Django Website?
How to run a python program on clicking a HTML button in a hosted Django Website ? I used the command 'out = run([sys.executable,'C:\python\Python38\code10.py', str(a), str(b)], shell=False , stdout=PIPE )' to run the python program before deploying the website and it worked. Can anyone suggest a way to run a python program in clicking a HTML button after hosting the Website. -
Customizing Django Forms
I have created a Model named Attendance. class Attendance(models.Model) : course_name = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) student_name = models.ManyToManyField(Student) instructor_name = models.ForeignKey(Instructor, on_delete=models.SET_NULL, null=True) published_date = models.DateTimeField(blank=True, null=True) When I pass it as a form, after selecting a particular course, I have to select students from the entire list of students enrolled for all courses. Instead I want to customize it such that only students enrolled in that particular course is displayed. I have tried using through fields for student_name field but in that case I need to pass Attendance as a Foreign Key in Student model and I need to create an instance of attendance before creating an instance of a Student. models.py: class Course(models.Model) : name = models.CharField(max_length=20, default='') course_code = models.CharField(max_length=10, default='') class Student(models.Model) : name = models.CharField(max_length=20, default='') rollno = models.CharField(max_length=10, unique=True, default='') course_name = models.ManyToManyField(Course) email_id = models.EmailField(max_length=40, default='') class Instructor(models.Model) : name = models.OneToOneField(User, on_delete=models.CASCADE) course_name = models.ForeignKey(Course, models.SET_NULL, blank=True, null=True) Also ,this is the template which contains the link to the Attendance form . I have passed the course for which attendance has to be taken as a parameter. {% block content %} Select the course for which attendance has to be taken {{ … -
I want to get the '' Alice " value from the parsed JSON in django template
I want to print Alice from this passed JSON as dict from views to the HTML file. this is my view file result = json.loads(JSON_DATA.content) return render(request, 'home.html', {'result' : result}) here is what I tried in HTML template {{ result.children[0].firstName }} this throws an error * TemplateSyntaxError* could not parse remainder '[0].firstName' from 'result.children[0].firstName' how can I access the value in HTML template ? -
raise MigrationError(selected.column) djongo.sql2mongo.MigrationError: id not getting any fixes
raise MigrationError(selected.column) djongo.sql2mongo.MigrationError: id not getting any fixes -
apply_async not work in celery and django
i have a shared_task to sending mail @shared_task def run_auto(): # Creata context for templates display top_article = Article.objects.all()[0] article1 = Article.objects.all()[1:3] article2 = Article.objects.all()[3:5] last_article = Article.objects.all()[5:8] context = { 'top_article': top_article, 'article1': article1, 'article2': article2, 'last_article': last_article, } for x,y in zip(user_list,time_list): msg_plain = render_to_string('timeset/email_templates.txt') msg_html = render_to_string('timeset/index3.html', context) subject = "NEWS" recepient = x sending.apply_async((subject,msg_plain,EMAIL_HOST_USER,recepient,msg_html), eta=y) @shared_task def sending(subject,msg_plain,EMAIL_HOST_USER, recepient, msg_html): send_mail(subject, msg_plain, EMAIL_HOST_USER, [recepient], html_message=msg_html,fail_silently=False) and in the settings.py in django i schedule the run_auto task 'send_mail_at_spe_time': { 'task': 'crawldata.tasks.run_auto', 'schedule': crontab(hour=10,minute=28), } The task run_auto work when i run celery -beat and -worker but the run_auto not call apply_async in the function , how i can call the apply async to send mail -
Django LoginRequiredMixedIn doesnn't let users sign in
I am building an app that allows users to view posts. However, every time I try to log in if I do not set the LoginRequiredMixin the user will still be able to view posts after logging out. But when I set the LoginRequiredMixin everytime user puts info it keeps going back to main page and nothing happens. my home/views.py @login_required def home(request): posts = Post.objects.all() context = {'posts':posts} return render(request, 'home/home.html', context) class PostListView(ListView): model = Post template_name = 'home/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] my home/urls.py: path('',views.PostListView.as_view(), name='home'), my main/urls.py urlpatterns=[ path('signup/',views.signup,name='signup'), path('signin/',views.user_login, name='user_login'), path('signout/', views.user_logout, name='user_logout'), path('',views.main_page,name='main_page'), path('edit/', views.edit_profile, name='edit_profile'), path('', include('django.contrib.auth.urls')), ] my main/views.py: def main_page(request): return render(request,'main/user_login.html') @login_required def user_logout(request): logout(request) return redirect('main:main_page') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) return redirect('main:main_page') else: form = SignUpForm() return render(request, 'main/signup.html', {'form': form}) def user_login(request): if request.method == 'POST': username = request.POST.get('username', '') password = request.POST.get('password', '') user = authenticate(request, username=username, password=password) if user is not None: return redirect(reverse('home:home')) else: messages.error(request,'Sorry, the username or password you entered is not valid please try again.') return HttpResponseRedirect('/') else: form=AuthenticationForm() return render(request, 'main/user_login.html', … -
File request to open not working in Django
I am new to django-JSON-Python. Please help! the code written works perfectly fine when I run in browser, though I have left out certain parts of HTML code here(some textfields,forms etc)for better readability. It works perfectly fine in browser but when I run the HTML as part of Django project in venv it simply refuses to get the file DOC_JSON.json(already created and available in the same folder). Is there anything I need to add for XMLHttpRequest() to work in Django. It doesn't throw any error. <html lang="en" xmlns="http://www.w3.org/1999/html"> <head> <meta charset="UTF-8"> <body> <script> function myFunction() { alert("Please Fill The Mandatory Fields !"); } var xmlhttp = new XMLHttpRequest(); var file_name = "Doc_JSON.json"; xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById("fname").value= myObj.FirstName; document.getElementById("lname").value= myObj.LastName; document.getElementById("addr").value= myObj.Address; document.getElementById("phno").value= myObj.PhoneNumber; document.getElementById("email").value= myObj.EmailAddress; document.getElementById("ed").value= myObj.Education; document.getElementById("techskill").value= myObj.TechnicalSkillset; document.getElementById("wrkexp").value= myObj.WorkExperience; document.getElementById("Empauth").value= myObj.EmploymentAuthorization; //Validating Mandatory Fields if ((document.getElementById("fname").value == null) || (document.getElementById("fname").value == "") || (document.getElementById("lname").value == null) || (document.getElementById("lname").value == "") || (document.getElementById("addr").value == null) || (document.getElementById("addr").value == "" ) || (document.getElementById("phno").value == null) || (document.getElementById("phno").value == "" ) || (document.getElementById("email").value == null) || (document.getElementById("email").value == "") || (document.getElementById("ed").value== null) || (document.getElementById("ed").value=="") || (document.getElementById("techskill") == … -
Django / Python broken imports
I'm having several problems when trying to import modules across the app and project settings. This is my directory tree, 2 levels deep ``` ├── README.md ├── WAD2 │ ├── __init__.py │ ├── __pycache__ │ ├── sc.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── WAD2app │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── filters.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py ├── requirements.txt └── templates └── wad2App ``` I tried to import two variables fromsc.py into settings.py and the module imports fine. I say this because when I do print out sys.modules.keys() the following is present 'WAD2.sc' When trying to access the variables via sc.x I get a NameError stating that sc is not defined, and I can only access the variables if I import them explicitly one by one i.e from .sc import x as y Why is this happening? Also, why is it that any imports in WAD2app must be imported from .moduleName only. I have a separate project with the very same structure and I'm able to use appName.moduleName -
Django Prefetch across multiples tables
I know there are a lot of prefetch question in Stackoverflow, but I think my case is a little "weird". So I have 3 Tables with FK. So each Reservation has a Shift and a Shift has a Nurse. What I'm trying to do is a Queryset where I get the Reservation.family_name field through Nurse.Shift.Reservation but using prefetch to not hit duplicated queries. Nurse-->Shift-->Reservation Nurse.objects.prefetch_related(Prefetch('shift_set', queryset=Shift.objects.filter( start__range=dates_range).order_by('reservation_id').distinct('reservation_id')), Prefetch('shift_set__reservation', to_attr='family_name')) What I'm trying to accomplish with this Query is get the family_name in a to_attr='family_name'. I'm using distinct because we filter 10 days from today to future, so we have some reservation duplicated and I just want the family name that are 10 days on the range. Any help will be appreciated. -
Django tests are not running on a test database
After running tests where I am creating rows in the database, I noticed that the current database is used instead of a test database like I think is the default behavior of django. Unfortunately, I haven't been able to figure out how to fix this behavior. This is currently in the settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.environ["POSTGRES_NAME"], "USER": os.environ["POSTGRES_USER"], "PASSWORD": os.environ["POSTGRES_PASSWORD"], "HOST": os.environ["POSTGRES_HOST"], "PORT": os.environ["POSTGRES_PORT"], } } but when adding "TEST": {"NAME": "test_database"}, it still seems to run on the main database. DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.environ["POSTGRES_NAME"], "USER": os.environ["POSTGRES_USER"], "PASSWORD": os.environ["POSTGRES_PASSWORD"], "HOST": os.environ["POSTGRES_HOST"], "PORT": os.environ["POSTGRES_PORT"], "TEST": { "NAME": "test_database", } } } How can I get it so the tests write to a fresh test database? -
Django got MySQL exception 2014: Commands out of sync; you can't run this command now
A web application of Django on RHEL7, Gunicorn service got a MySQL exception #2014, saying "Commands out of sync; you can't run this command now". This error happens only when get one attribute element ("/api/admin/eav/attribute/24/"), and all the other elements are OK, e.g. the logs below shows "/api/admin/eav/attribute/28/" is OK. This web application has been working fine for years before, and we noticed this error only recently. The versions of Django, Python, and MySQL are pretty old now. Many thanks in advance to any suggestion on fix. I will also highly appreciate general debugging advice, on for example: how to configure Django to print SQL query statement into log? (I suspect there is something wrong with the query, and want to manually try it out in MySQL Workbench. I'm still new to Django.) Is there anything to check on MySQL side? See details below, and let me know if you need more information. Thank you for your help. Version: Python: 2.7.5; Django: django.VERSION (1, 8, 13, 'final', 0); MySQL: '10.1.9-MariaDB' ** Logs:** [2020-03-20 18:17:37 +0000] [29744] [DEBUG] GET /api/admin/eav/attribute/ - - [20/Mar/2020:18:17:38 -0600] "GET /api/admin/eav/attribute/ HTTP/1.0" 200 56843 "https://domain.under.test/api/admin/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 … -
Django Custom User Model Encrypt Email Field
I would like to encrypt a user's email every time they sign up. The error I am getting is: "Error: EncryptedEmailField 'iexact' does not support lookups". I am using django-fernet-fields which uses the SECRET_KEY for encryption and decryption symmetrically. The user gets created and the email encryption works if I add a user from admin or the command line but when I try to add it from my form, it does not work. I am using allauth for the sign up process. Is the error above a problem with the django-fernet-fields package? Or could it be this line: email = self.normalize_email(email) How would I fix this problem? Code: https://dpaste.org/ODL3 -
How to validate multiple field uniqueness constraint on field that is not in form?
I have a model which has a uniqueness constraint across two fields (each user must have distinct profile names): class Profile(Model): user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) name = CharField(max_length=50) description = TextField(blank=True) class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'name'], name='profile_unique_user_name') ] When a user adds a new Profile, I do not want to give them access to change the user, so the form only has two fields: class ProfileForm(ModelForm): class Meta: model = Profile fields = [ 'name', 'description', ] In the view, I assign the user once the form is validated: @login_required def profile_add(request): if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect('home') else: form = ProfileForm() return render(request, 'profile_add.html', {'form': form}) However, the problem seems to be that the uniqueness validation doesn't happen. Presumably because the user field is not in the form. How should I change my code so that any uniqueness errors are fed back to the form's errors? My current idea is add the user field to the form, and leave it out of the template, then manually add the value in the view. Though this seems slightly hacky. Would that even work, and is there a … -
How can I login as a specific user with Django?
I would like to login to my application as a specific user without having to ask for their username or password. I use React on the frontend, and django-rest-framework-simplejwt for authentication. I know Django has a login() function, but I'm not sure how I would use this along with JWT tokens, has someone figured out how to do this? Ideally I enter a "Master Password" along with the users email to specific what user I would like to login as.