Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
404 error after implementing django-rest-knox
I want to implement auth using django-rest-knox. I don't know where the issue. I am new to django also. urls.py urlpatterns = [ path("", include(router.urls)), path("^auth/register/$", RegistrationAPI.as_view()) ] I can a 404 message when I go the localhost:8000/api/auth/register. I got the same error when I use curl -
Filter data over count of two ManyToMany-relations
What's the way to filter data over the count of two ManyToMany-relations ? class Pic(models.Model): size_kb = models.IntegerField(default=0,blank=True) md5 = models.CharField(max_length=128,blank=True) class Film(models.Model): content = models.CharField(max_length=4096, null=True, blank=True) duration = models.SmallIntegerField(null=True, blank=True) class Video(models.Model): md5 = models.CharField(max_length=32,blank=True) rating = models.FloatField(null=True,blank=True) year = models.SmallIntegerField(null=True,blank=True) class Person(models.Model): pics = models.ManyToManyField(Pic,related_name='persons') videos = models.ManyToManyField(Video,related_name='persons') films = models.ManyToManyField(Film, related_name='persons') Searching for Persons with 10 - 20 Pics: Person.objects.all().annotate(seek_col=Count('Pic')).filter(seek_col__range=(10,20)) Result is ok ... Searching for Persons with 10 - 20 Films: Person.objects.all().annotate(seek_col=Count('Film')).filter(seek_col__range=(10,20)) Result is ok ... Searching for Persons with 10 - 20 Films AND 10 - 20 Pics: I try the follow statements: Person.objects.all().annotate(fcol=Count('films')).filter(fcol__range=(10,20)).annotate(pcol=Count('pics').filter(pcol__range=(10,20)) Person.objects.all().annotate(fcol=Count('films')).filter( pcol=Count('pics')).filter(fcol__range=(10,20), pcol__range=(10,20)) Result is nonsens ... not really nonsens: I expect follow results ( only pics and films columns ): | pics | films | | 20 | 20 | | 10 | 20 | | 14 | 15 | | 10 | 12 | | 16 | 13 | | 12 | 17 | but I get these results (depends on range): | pics | films | | 20 | 1 | | 1 | 20 | | 4 | 5 | | 10 | 2 | | 6 | 3 | | 2 | 7 | I … -
How to load file contents to ace editor
I set up a django website allowing users upload .txt files, and I want to add editing function by integrating ACE editor (or any other editor suggestions?). I have a list of my uploaded files, and I want an edit button to redirect to editor page with loading the file content in the editor page. I am wondering how to load file content to ace editor? I found some code about uploading file and displaying them in editor directly.(https://jsfiddle.net/xlaptop2001/y70gL3kv) However, what I want is to redirect to a new editor page with loading the file that already uploaded by clicking on 'edit' button. {% extends 'base.html' %} {% block content %} <h1>Mechanism {{ object.id }} details</h1> <style> ul.b { list-style-type: square; line-height:200%; } </style> <ul class="b"> <li> {% if object.ck_mechanism_file %} <a href="{{ object.ck_mechanism_file.url }}">{{ object.ck_mechanism_file }}</a> <a href="/ace/"> <button type="button" class="btn btn-primary btn-sm">Edit</button> </a> <a href="delete_mechanism"> <button type="button" class="btn btn-danger btn-sm">Delete</button> </a> {% else %} <span class="text-muted">No Mechanism File Attached</span> {% endif %} </li> <li> {% if object.ck_thermo_file %} <a href="{{ object.ck_thermo_file.url }}">{{ object.ck_thermo_file }}</a> <a href="/ace/"> <button type="button" class="btn btn-primary btn-sm">Edit</button> </a> <a href="delete_thermo"> <button type="button" class="btn btn-danger btn-sm">Delete</button> </a> {% else %} <span class="text-muted">No Thermo File Attached</span> … -
ProxyError while using "requests.post()" in Python/Django
I try to call a java-based web-service in python code, using requests.post() as follows: endpoint = 'http://**.**.**.**:8080/MyApp/services/Services/login' def index(request): post = request.POST if request.POST.get('login_button'): qd = QueryDict(mutable=True) qd.update( inputPhoneNumber=request.POST.get('phone_num'), inputPassword=request.POST.get('password') ) messages.info(request, '{}?{}'.format(endpoint, qd.urlencode())) response = requests.post('{}?{}'.format(endpoint, qd.urlencode())) result = response.json() messages.info(request, result) return render(request, 'login/index.html') However, proxy blocks my request. I suspect that this happens because the web-service uses http protocol. After 30 hours of searcing, I could not find anything to solve this problem. I've tried changing http to https but that caused another error. For the record, I can access web-service's url by manuel on browser, but I cant, on django. The stack trace is: ProxyError at /login/ Request Method: POST Request URL: http://localhost:8000/login/ Django Version: 2.2.3 Python Version: 3.7.3 Installed Applications: ['login', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware'] Traceback: File "C:\Program Files\Python37\lib\site-packages\urllib3\connection.py" in _new_conn 160. (self._dns_host, self.port), self.timeout, **extra_kw) File "C:\Program Files\Python37\lib\site-packages\urllib3\util\connection.py" in create_connection 80. raise err File "C:\Program Files\Python37\lib\site-packages\urllib3\util\connection.py" in create_connection 70. sock.connect(sa) During handling of the above exception ([WinError 10060] Bağlanılan uygun olarak belli bir süre içinde yanıt vermediğinden veya kurulan bağlantı bağlanılan ana bilgisayar yanıt vermediğinden bir bağlantı kurulamadı), another exception occurred: File "C:\Program Files\Python37\lib\site-packages\urllib3\connectionpool.py" in … -
Django Model Type
My goal is to have a model structure like the below: Course Section Subsection For each course there can be multiple sections. And each section can have multiple subsections. class Course(models.Model): title = models.CharField(max_length=200) def __str__(self): return self.title class Section(models.Model): course = models.OneToOneField( Course, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) def __str__(self): return self.title class SubSection(models.Model): title = models.CharField(max_length=200) course = models.OneToOneField( Course, on_delete=models.CASCADE, ) def __str__(self): return self.title However, when i test this via the admin, I can create a course, but not a section? # cat course/admin.py from django.contrib import admin from .models import Course admin.site.register(Course) Any ideas on where im going wrong? -
Maximum call stack size exceeded error on JQuery Autocomplete Lookup
I have the following code: var person_names = JSON.parse(document.getElementById('person_names').textContent); $('#autocomplete_person_names').val(''); var selected_person = null; $('#autocomplete_person_names').autocomplete({ lookup: person_names, showNoSuggestionNotice:true, maxHeight:200, onSelect: function (suggestion) { selected_person = suggestion.value; } }); For some reason I get the uncaught type error Maximum call stack size exceeded in my console. When I check line by line, I found out the error is because of the following line: lookup: person_names, As far as I have found out by searches until now, the Maximum call stack size exceeded is because of recursive functions. But I cannot understand what kind of recursive behavior the lookup brings here. What could be the problem here? Another thing: the variable person_names gives an array and works fine. And I am using this inside an html template inside a Django project. The full error in console looks like this: Uncaught RangeError: Maximum call stack size exceeded at Function.map (jquery-3.3.1.js:462) at b.verifySuggestionsFormat (jquery.autocomplete.min.js:8) at b.setOptions (jquery.autocomplete.min.js:8) at new b (jquery.autocomplete.min.js:8) at HTMLInputElement.<anonymous> (jquery.autocomplete.min.js:8) at Function.each (jquery-3.3.1.js:354) at jQuery.fn.init.each (jquery-3.3.1.js:189) at jQuery.fn.init.a.fn.devbridgeAutocomplete (jquery.autocomplete.min.js:8) at HTMLDocument.<anonymous> ((index):3734) at c (jquery.min.js:4) -
Syntax Error after adding knox to urls.py
I am new to Django and django-rest-framework. I am building an API and I want to implement auth using Django-rest-Knox. I have added Knox to the installed apps in the settings.py. In the urls.py of the project, I added the path to Knox. It seems there is a syntax error. urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path("api/", include('core.urls')) path("api/auth/", include('knox.urls')), ] This is the error message : path("api/auth/", include('knox.urls')), ^ SyntaxError: invalid syntax -
Django - Retrieve Different Post Types Based On TimeStamp
I am working on a little Django project. The user can create two types of Posts: Image & Video . Here, the different classes I have created (for the sake of brevity, I excluded some fields): class VideoPost: videoData = ... class ImagePost: imageData = ... So, when I combined the project with an Android app to display the posts on the screen, then I faced the problem how to retrieve the different posts once. I could not come up with a solution. Let's say, the user has created video and image post objects with the following order: VideoPost1 -> ImagePost1 -> ImagePost2 -> VideoPost2 How can I retrieve them in that order ? So, how to get a that mix of video and image posts based on creation time ? At the moment, I can only make separate queries like: # the view responsible for listing VideoPost instances .... return VideoPost.objects.all() # the view responsible for listing ImagePost instances .... return ImagePost.objects.all() I do not want to sort the instances on the frontend (Android app). So, is there a way to sort and query the different instances on the backend (Django) -
How do I allow model serializer to set model's foreign key field to null?
I want to be able to set the borrower field (a foreign key) in my Asset model to be NULL but I can't seem to get it to work. I'm trying to send a PATCH request with JSON data that has the key borrower equal to value of NULL but the borrower field won't get updated to NULL for the model instance. Perhaps there is an issue with the serializer that is preventing the foreign key field from being able to be set to NULL? I have already tried passing in allow_null=True to BorrowSerializer class but that hasn't worked. I've searched high and low on StackOverflow for posts with similar problems and solutions but nothing I've tried has worked. Here is my models.py: from django.conf import settings from django.db import models from django.utils import timezone from datetime import date from django.contrib.auth.models import User from django.urls import reverse import uuid class Category(models.Model): """Model representing an Asset category""" name = models.CharField(max_length=128) def __str__(self): return self.name class Borrower(models.Model): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=128) associated_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return f'{self.first_name} {self.last_name}' class Asset(models.Model): """Model representing an Asset""" # Unique identifier for an instance of an asset (a barcode of sorts) … -
How to allow normal user to access port 80 and 443 on compute engine ubuntu18.04 intance?
I'm trying to host django wesite on gcp compute engine ubuntu 18.04 instance. when i'm running django development server as normal user on port 80, it show error "Error: You don't have permission to access that port." But when i run same as root user, it run successfully. I guess normal user don't have permission to access port 80 or port 443. Is there any way i can provide port access to normal user? -
Django database and migration error, ValueError: Related model 'Users.user' cannot be resolved
I am facing a very very strange situation with my Django (in general). I'm using Django 2.2 and Python 3.6.7. Every single time I create a new project, using: django-admin startproject myproject and trying to migrate it, I got this error : Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying admin.0004_auto_20190630_1438... OK Applying admin.0005_auto_20190630_1441...Traceback (most recent call last): File "C:\Dev\Django\myproject\manage.py", line 21, in <module> main() File "C:\Dev\Django\myproject\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Dev\Django\Env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Dev\Django\Env\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Dev\Django\Env\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Dev\Django\Env\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Dev\Django\Env\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Dev\Django\Env\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle fake_initial=fake_initial, File "C:\Dev\Django\Env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Dev\Django\Env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Dev\Django\Env\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Dev\Django\Env\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Dev\Django\Env\lib\site-packages\django\db\migrations\operations\fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Dev\Django\Env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 137, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File … -
How to assign object permission with override save() in model class?
I want model chapter to have two status. One is public, the other is only for permitted group. Therefore, I think I need object permission to put into practice. I also hope I can assign permission whenever I create or edit the object class Chapter(models.Model): chapter = models.PositiveSmallIntegerField() title = models.CharField(max_length=200, blank=True) content = models.TextField() book = models.ForeignKey('book', on_delete=models.CASCADE, null=True) AVAILABLE_STATUS = ( ('p', 'public'), ('l', 'login user only') ) status = models.CharField( max_length = 1, choices = AVAILABLE_STATUS, default = 'p', help_text='Chapter availability', ) class Meta: ordering = ['chapter'] unique_together = (("book", "chapter"),) permissions = (('author', "Can Create ,Edit , Delete"), ('view_private_chapter',"Can View Private Chapter") ) def save(self, *args, **kwargs): if self.status=='l': group = Group.objects.get_or_create(name='private_chap_viewer') assign_perm('view_private_chapter', group, self) super().save(*args,**kwargs) But I get Error:not all arguments converted during string formatting when i try to change chapter status in admin -
'charmap' codec can't encode characters in position 100-101: character maps to <undefined> in "requests.json()" [on hold]
Error Getting: 'charmap' codec can't encode characters in position 100-101: character maps to When Getting response from requests response = requests.post(url, data=json_data) response_json = response.json() print(response_json) Error Getting: 'charmap' codec can't encode characters in position 100-101: character maps to -
Django Heroku deployment - ! [remote rejected] master -> master (pre-receive hook declined)
There are a few posts with this particular issue however I've tried about five or six different suggestions from those posts and have had no luck. when trying git push heroku master I get the following error: (env) PS C:\Users\Shaun\Desktop\DjangoBlog\src> git push heroku master Total 0 (delta 0), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to murmuring-dusk-96030. remote: To https://git.heroku.com/murmuring-dusk-96030.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/murmuring-dusk-96030.git' From the build log on the Heroku website: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed I have a simple static website running Django 2.2.3 as back end. I've been developing in a virtual environment on my local machine and have the following project structure shown blow, where 'src' was what I renamed the folder created by the django-admin startproject command. I'd like to deploy my site on Heroku so I've signed up, installed git and the Heroku CLI. In my terminal I've logged in to Heroku … -
Python mysql client installing on Mac
I am trying to install mysqlclient in a virtual environment. Python version is 3.0 So here is what I did Created a Virtual environment, activated it from terminal Installed the below, pip install django pip install mysqlclient Both installed without any errors. So I activated the virtual environment in terminal by using this, cd users/myenv/bin/ and then source ./activate Next I navigated to my project folder using cd users/pyworkspace/project I then started the server using this and python manage.py runserver then I got this error below, Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/MySQLdb/_mysql.cpython-36m-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Users/user/Desktop/python/myenv/lib/python3.6/site-packages/MySQLdb/_mysql.cpython-36m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, … -
Django model match type
i have match table and i want to add Match type (like final. semifinal. quarter final. third place match. 1st match 2.match 3.match 4.match and more. If match in a league there may even be a 10th match What should you suggest me class MatchQuerySet(models.QuerySet): def finished(self): return self.filter(status=Match.STATUS_FINISHED) def started(self): return self.filter(status=Match.STATUS_STARTED) def playing(self): return self.filter(status=Match.STATUS_PLAYING) def cancelled(self): return self.filter(status=Match.STATUS_CANCELLED) def unknown(self): return self.filter(status=Match.STATUS_UNKNOWN) class Match(models.Model): STATUS_FINISHED = 'Bitti' STATUS_STARTED = 'Başladı' STATUS_PLAYING= 'Oynanıyor' STATUS_CANCELLED= 'İptal' STATUS_UNKNOWN= 'Bilinmiyor' STATUS_PENDING= 'Bekleniyor' STATUSES = ( (STATUS_FINISHED, 'Bitti'), (STATUS_STARTED, 'Başladı'), (STATUS_PLAYING,'Oynanıyor'), (STATUS_CANCELLED,'İptal'), (STATUS_UNKNOWN,'Bilinmiyor'), (STATUS_PENDING,'Bekleniyor'), ) name=models.CharField(max_length=255) slug=models.SlugField(unique=True,max_length=255) status = models.CharField(max_length=20,choices=STATUSES,default=STATUS_UNKNOWN) map=models.ForeignKey('GameMap',null=True,blank=True,related_name='matchmap',on_delete=models.PROTECT) league=models.ManyToManyField(League,blank=True,null=True) objects = MatchQuerySet.as_manager() -
About the Functions in Python
I was Trying to do write code related to this concept in python: We have a various list(eg:[1,2,3],[3,5,6],[5,6,7,8])like this a 1000's of set.We have forgotten to add num(10,20) which is common in all the list. We cannot add (10,20) in each list, which is a waste of time. How to append the num(10,20) in all the 1000 sets? Please, help me with this... -
Can i restrict data between staff user in same model?
I'm new in Django.I have to create staff user but distinct data between them of same model in django-admin. Can i add new permission in User model and implement in default admin? I have not idea about how to implement. i.e. i have 2 staff user, and add data in same model. If staff-user-1 is login then show only his added data only (can not see data added by staff-user-2). is possible in built-in django admin ? Thanks!!! -
Access-Control-Allow-Origin Issue in vue.js and django
I deploy my service in my own computer and it all works very well and I decided to put it on my server. But I find some request are restricted by 'CORS' and some are not. The web server is Nginx deployed on the Linux. The backend framework is Django, with DRF provided the api service.The frontend framework is Vue.js.And the Ajax request library is using 'axios'. The code runs very perfect on my own Mac and have no CORS problem. But it got problem on the server. By the way, the mode for the route in Vue.js is historymode. Here is my Nginx configure code: server { listen 80; server_name 167.179.111.96; charset utf-8; location / { root /root/blog-frontend/dist; try_files $uri $uri/ @router; index index.html; add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods *; } location @router { rewrite ^.*$ /index.html last; } } Here is my Vue.js code that has the 'CORS' problem. main.js Vue.prototype.API = api Vue.prototype.GLOBAL = global Vue.prototype.$axios = Axios; Axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded' Axios.defaults.headers.post['Content-Type'] = 'multipart/form-data' redirect.vue <template> <div id="notfound"> <div class="notfound"> <div class="notfound-404"> <h1>Redirect</h1> </div> <h2>Wait a few seconds, page is redirecting</h2> <p>You are logging...authorization code is {{code}}</p> </div> </div> </template> <script> export default { name: 'redirect', data(){ … -
Django Form doesn't get password
I'm trying to make a user registration views using django forms. I looked online, but nothing I found can help me; or probably I can't get the reasoning, so a explanation is welcome. I changed the standard user with a custom class named "Utente" (Italian name) View function is a simple one that configure "context" dict to be passed to template, so that form or confirmation or error can be notified. views.py def registrazione(request): context = {} if request.method == 'POST': context.update({ 'stato':'post'}) form = UtenteChangeForm(request.POST) if form.is_valid(): print("--FORM\n",form.cleaned_data,'\n-------') utente = Utente.objects.create_user(**form.cleaned_data) print("---UTENTE\n", utente) login(request, utente) if utente is not None: context.update({'utente':utente.username}) else: print('ERROREEEEEEEEEEEE') else: context.update({ 'stato':'errore' }) else: # GET form = UtenteCreationForm() if request.user.is_authenticated: context.update({ 'stato':'loggato' }) else: context.update({ 'stato':'anonimo'}) context.update({'form':form }) return render(request, 'profilo/registrazione.html', context) The form should extends the standard user creation form. forms.py lass UtenteCreationForm(UserCreationForm): username = forms.CharField(min_length=5) email = forms.EmailField(min_length=5) first_name = forms.CharField() last_name = forms.CharField() data_nascita = forms.DateField(input_formats=['%d/%m/%Y']) cellulare =forms.RegexField(regex=r'^\+?\d{9,15}$') residenza = forms.CharField(min_length=5) class Meta(UserCreationForm): model = Utente fields = ('username','first_name', 'last_name', 'email', 'data_nascita', 'cellulare', 'residenza') The print of form.cleaned_data put in stdout (one for all): --FORM {'username': 'thomas', 'email': 'thoma@g.com', 'cellulare': '3341193124', 'residenza': 'viq culonia', 'password': None} First Problem why password is … -
Redirecting login page to home page when user is logged in using django 2.2
I want to redirect users to the homepage when they already logged in and tried to access the login page again. I am using django 2.2. I tried to use user.is_authenticated but it didn't work {% block content %} {% if user.is_authenticated %} {% block chess_page %} {% endblock %} {% else %} <div id="logo"> <img src="../../static/img/chess-logo.jpg" name="logo-pic"> <h2>Chess</h2> </div> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endif %} {% endblock %} chess_page is the homepage I want to redirect to -
Store Uploaded CSV to Browser Storage
Any way we can store CSV file in Browser Storage and retrieve it later and process in the backend. Issue: I want to add Import Question Button to Django admin Form View. It works fine if the record is already saved. In case of the new record, if csv file selected and some of the fields are not validated, then Django auto reload while saving the record and due to that selected csv is cleared. -
Django Models not working: module 'django.contrib.admin' has no attribute 'Modeladmin'
I am making a eCommerce website from a youtube tutorial and I have an error that is really bugging me around. I tried google but it didn't work. Then I tried messing with Django but that made it worse, so I changed it back. This is the code for admin.py: from django.contrib import admin # Register your models here. from .models import profiles class profileadmin(admin.Modeladmin): class Meta: model = profiles admin.site.register(profiles, profileadmin) The full error message is this: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03ED28A0> Traceback (most recent call last): File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in … -
On Windows in the "settings.py" file not getting the environment "os.environ" variables in Django
on Windows in the settings.py file not getting the environment variables in Django but working file in Ubantu. -
Filters with Django and jQuery
I was trying to add some filters to a project that I'm currently working on to filter videos by year, genre, language, and quality: year, language and quality filters work just fine so I removed their code. When it comes to the genre I have a field in the model called tags which is a comma separated values. so for example, if the value is 'action, comedy, drama' and someone is looking for a genre of 'comedy' I want them to be able to find it from these tags. Django code: videos = Media.objects.order_by( '-date').filter(is_published=True) if 'genre' in request.GET: genre_tags = request.GET['genre'] if genre_tags: genre_tags = videos.filter(tags=genre_tags) context = { 'medias': paged_movies, 'values': request.GET } return render(request, 'media_files/listing.html', context) HTML code: <select class="filter-genre"> <option value="">All</option> <option {% if values.genre == 'action' %} selected {% endif %} value="action">Action</option> <option {% if values.genre == 'adventure' %} selected {% endif %} value="adventure" >Adventure</option> <option {% if values.genre == 'animations' %} selected {% endif %} value="animations" >Animations</option> <option {% if values.genre == 'crime' %} selected {% endif %} value="crime" >Crime</option> <option {% if values.genre == 'horror' %} selected {% endif %} value="horror" >Horror</option> <option {% if values.genre == 'documentary' %} selected {% endif %} …