Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use is_active in class based LoginView?
I am using default User model and I want check whether the user is active or not before they log in... How can I do that? -
Reverse foreign key relation in django serializers
Can I save data in django in a reverse foreign key relation. Suppose I have models, class Author(models.Model): author_id = models.SlugField(default=None, blank=True) author_name = models.CharField(max_length=200) class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) article_title = models.CharField(max_length=200) content = models.CharField(max_length=200) Suppose I want to save all articles with their author data what type of serializer should I use. I am receiving data in this form: article_data =[ { "title":"ome title", "content":"content", "author":{ "author_id":"2", "author_name":"some name", } }, { "title":"ome title", "content":"content", "author":{ "author_id":"2", "author_name":"some name", } } ] How should I write my serializer to save such data. I dont want to write my logic views file. I dont want to loop over all my articles and then save article and author separately using two serialzer. What I want is calling a single serializer and passing the entire list to it: saveArticleAndAuthor(article_data, many=True) the serialzier must save author data to author table and rest of the data to article table. -
how to use font awesome icon as file upload input field for django template as bootstrap?
I am using bootstrap as the template. The form is designed as the font awesome icon will be the file upload field in the design. Is there any way to do it? I have no idea about that. I am sharing the template code here. If anyone can help me, I will be grateful. Thanks. <form method="POST" action="{% url '' %}"> {% csrf_token %} <div class="icons"> <div class="row"> <div class="col-4"> <a href="#"> <i class="fa fa-picture-o" aria-hidden="true"></i> <p>Gallery</p> </a> </div> <div class="col-4"> <a href="#"> <i class="fa fa-camera" aria-hidden="true"></i> <p>Camera</p> </a> </div> <div class="col-4"> <a class="" href="#" > <i class="fa fa-microphone" aria-hidden="true"></i> <p>Audio</p> </a> </div> </div> </div> <div class="mb-3"> <textarea class="form-control" id="exampleFormControlTextarea1" rows="8" placeholder="Type your question here" name="description" ></textarea> </div> <button type="submit" class="btn">Submit</button> </form> -
Please any one out there how i can get pass this issue i encountered this issue most times in heroku when i push new code instead of auto migration
Operations to perform: Apply all migrations: admin, auth, authentication, contenttypes, ekzweb, sessions Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. please anyone out there how can i get pass this issue -
How to send email to admin in Django?
I'm building a web application that needs to send a notification to the admin when there is a low quantity of items in-store. Like if I have 10 pens, and someone recently buys 5 pens from my web application and I want to send a notification to admin if the quantity of pens is less than 5 or equal to 5 to notify him/her. Thanks ^^ -
Passing a variable vs a hard-coded string is not working on query search using Django shortcuts
I'm in the process of learning how to use Django. My goal is to grab an object (one hero and one villain) from the database using the names, (not id), passed in the URL as search params. I am successfully grabbing the values from the query params, however, when I try to pass the variable "hero" into the Django shortcut, (get_object_or_404(Super,name=hero)), I get a 'not found'. It works fine if I manually type out the string I'm searching for(get_object_or_404(Super,name="Bat Man")). Any ideas why this is and how I can make my query search dynamic by name? @api_view(['GET', 'POST']) def supers_list(request): type = request.query_params.get('type') hero = request.query_params.get('hero') villain = request.query_params.get('villain') if request.method == 'GET': supers = Super.objects.all() if type: supers = supers.filter(super_type_id__type = type) serializer = SuperSerializer(supers, many=True) return Response(serializer.data) elif hero and villain: # print(hero) result is "Bat Man" hero_found = get_object_or_404(Super,name=hero) # hero_found = get_object_or_404(Super,name="Bat Man") print('=====', hero_found) return Response('hello') else: heros = supers.filter(super_type_id__type = 'hero') villains = supers.filter(super_type_id__type = 'villain') heros = SuperSerializer(heros, many=True) villains = SuperSerializer(villains, many=True) result = {'heros':heros.data, 'villains':villains.data} return Response(result) -
Django form request method is always GET
This is the html code: <form method='POST'>{% csrf_token %} {{ form.as_p }} <input type='submit' value='save'/> </form> This is the path in url.py: path('student/create/', student_create_view, name='student-create') This is my code in views.py: def student_create_view(request): form = StudentForm(request.POST or None) if form.is_valid(): form.save() form = StudentForm context = { 'form': form } return render(request, "personnel/student_create.html", context) I also tried action attribute and adding or removing "/" to the end of the path. -
django UserPassesTestMixin with parameter
Here's working version with user_passes_test. But I would like to replace position > 1 with parameter. I found that, it's possible to do with UserPassesTestMixin. But I don't know how. Can anyone help? def position_check(user): position = 0 if user.is_anonymous else user_control.objects.values( 'position__rank' ).get( user = user.id ) return True if position > 1 else False @user_passes_test(position_check, login_url='loginPage') def index(request): pass @user_passes_test(position_check, login_url='loginPage') def exportReview(request): pass I was try: class PositionCheck(self): position = 0 if user.is_anonymous else user_control.objects.values( 'position__rank' ).get( user = self.request.user.id ) return True if position > (replace with parameter) else False class Review(PositionCheck, View): def index(request): pass def exportReview(request): pass -
Django - display Httpresponse in template
This is what I have in views This a function in javascript I get this message when I run the project However the responses are displayed in a blank page like this how do I get the httpsresponse to display in the same page in the chat window and not in a different page I'm completely new to Django and javascript . It would be of great help if anyone can help. Thanks in advance. -
Django-debug-toolbar not showing
I am using django 4.0.3 and django-debug-toolbar 3.2.4. For some reason, the toolbar is not showing on my server.I tried many ways but none of them worked for me. I will be very grateful for any help settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'news.apps.NewsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] WSGI_APPLICATION = 'mysite.wsgi.application' # debug_toolbar moved here. if DEBUG: MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INSTALLED_APPS += [ 'debug_toolbar', ] INTERNAL_IPS = ['127.0.0.1', ] # this is the main reason for not showing up the toolbar import mimetypes mimetypes.add_type("application/javascript", ".js", True) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, } urls.py if settings.DEBUG: import debug_toolbar urlpatterns += [ path('__debug__/', include(debug_toolbar.urls)), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Add hyperlinks from an array to elements of a table Django
I have a csv file with 3 columns. I want to display this table in a html but every element of the third column should have a hyperlink loaded from a python array in views.py. Currently, I am loading the table using pandas. My views.py: def passparam(request): data = pd.read_csv (r'/home/darkbee/django3-password-generator/media/test.csv') html_table = data.to_html(index=False) arra_containing_links["#link1","#link1",............."#link1","#link80"] context = {'loaded_data': html_table} return render(request, 'generator/password.html',context ) My password.html: {{loaded_data | safe}} Any help is very much appreciated <3 -
Apache/mod_wsgi log object issues upon importing some module
I have a Django application that runs on an Apache server, Ubuntu OS. I've recently added a new import statement of some module, that causes the following server error: File "/dataco_monitor/dataco_venv/lib/python3.7/site-packages/nebula/consts.py" in <module> 49. _is_interactive = os.isatty(sys.stdout.fileno()) Exception Type: OSError at / Exception Value: Apache/mod_wsgi log object is not associated with a file descriptor. I've tried to reproduce the issue by running the app's virtualenv (with the user that runs the server) and importing that module, but got nothing, all good. Also tried to run manually: os.isatty(sys.stdout.fileno()) , it returns 'True'. I've tried to search Google for this issue, haven't found any similar case. What can that be? Any input here will be much appreciated. Thanks -
Django digital ocean droplet isn't showing the website when connected with a namecheap domain
So I'm using a Django Digital Ocean droplet to run a website. I recently tried connecting the IP address of the droplet to a namecheap domain name, but when I connected them it only showed this on the domain: Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. However, the website was working as intended on the IP address, can anyone tell me how to fix this? my abbreviated /etc/nginx/sites-available/defaultfile server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name sanskarhandicrafts.com; location / { try_files $uri $uri/ =404; } } I'm happy to provide more details -
User Data Posted to Django User Model API Fails Authentication
I have two deployed Django projects: A and B and both have User models for user authentication. But I want users of Project B who sign up to have accounts on Project A as well. So I created an API using DRF for the user model in Project A and I was able to post user data (username and password) from Project B to the API. But when I tried to login to Project A using the newly posted user data, it failed authentication, despite the data now bring present in Project A's API. Please could anyone help me identify what's wrong? I'd love to post code snippets but, cuz of the data, can't really do that, but based on the principle, what do you guys think the problem might be? -
ModuleNotFoundError: No module named 'django-angular'
I have already installed pip3 install django-angular Requirement already satisfied: django-angular in /usr/local/lib/python3.9/site-packages (2.3) Requirement already satisfied: django>=2.1 in /usr/local/lib/python3.9/site-packages (from django-angular) (3.2.12) Requirement already satisfied: asgiref<4,>=3.3.2 in /usr/local/lib/python3.9/site-packages (from django>=2.1->django-angular) (3.4.1) Requirement already satisfied: sqlparse>=0.2.2 in /usr/local/lib/python3.9/site-packages (from django>=2.1->django-angular) (0.4.2) Requirement already satisfied: pytz in /usr/local/lib/python3.9/site-packages (from django>=2.1->django-angular) (2021.3) but on running server it says File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django-angular' I have already uninstalled & reinstalled it several times but no luck -
Subclassed form doesn't render customized input field in Django
I have a subclassed form which I want to render a custom max attribute on the input field. However, it doesn't return any form instance in the view and thus doesn't render any input field either: # views.py .. custom_max_attribute = qs_aggregates['total_equity'] print(custom_max_attribute) # prints 4000 withdraw_form = WithdrawForm(custom_max_attribute) print(withdraw_form) # prints nothing .. # template .. <div class="field-wrapper"> <div class="field-title">Set your Amount</div> <div class="withdraw-input-field">{{ withdraw_form.withdraw_amount }}</div> <!-- isnt rendered --> </div> .. # forms.py class WithdrawForm(forms.Form): """ A form to withdraw available funds from Farena to the users bank account """ def __init__(self, custom_max_attribute, *args, **kwargs): super().__init__(self, custom_max_attribute, *args, **kwargs) withdraw_amount = forms.FloatField(widget=forms.NumberInput(attrs={'min': 1, 'max': custom_max_attribute, 'step': 0.01})) -
async messages in admin
I created a task in the admin that is costly and should be carried out asynchronously. I would do something like def costly_task(**kwargs): def do_task(id): ## do stuff, you know, that is costly task = ThreadTask.objects.get(pk = id) task.is_done = True task.save() task = ThreadTask() task.save() t = threading.Thread(target = do_task, args = [task.id]) t.setDaemon(True) t.start() return {"id": task.id} With a models.py table: class ThreadTask(models.Model): task = models.CharField(max_length = 30, blank = True, null = True) is_done = models.BooleanField(blank = False, default = False) This works well, but I want to inform the admin of the runnig task, and also when it is finished. There is a very old (django 4.0 incompatible) package called django-async-messages which leverages the normal django-messages package to be used asynchronously. I googled but did not find anything of newer age ... any ideas on how to do this? Can I use djangos async processes to send out two messages: when task started (that one is easy) when task finished Django async send notifications -
I am getting soo many errors on my project please help me
This is my code: def Create_Database_Railway(): import mysql.connector mycon=mysql.connector.connect(host='localhost',user='admin',passwd='12345',port=3307) cursor=mycon.cursor() mycon.autocommit=True s1="create database railway" cursor.execute(s1) Create_Database_Railway() These are error: Create_Database_Railway() File "c:\Users\Admin\OneDrive\Desktop\New Proj\6475-DATABASE CREATION.py", line 3, in Create_Database_Railway mycon=mysql.connector.connect(host='localhost',user='admin',passwd='12345',port=3307) File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector_init_.py", line 273, in connect return MySQLConnection(*args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 114, in init self.connect(**kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\abstracts.py", line 1009, in connect self._open_connection() File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 422, in _open_connection self._ssl, self._conn_attrs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 230, in _do_auth self._auth_switch_request(username, password) File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 377, in _auth_switch_request raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'admin'@'localhost' (using password: YES) -
Django LookupError: No installed app with label 'app_name' when running tests
I am trying to set up a test database in a Django project that's a couple of years old. I'm using Postgres and the default database (non-test) works fine. I run it against a database instance in a Docker container. When try I run my tests, however, this is what happens: Got an error creating the test database: database "mytestdatabase" already exists Type 'yes' if you would like to try deleting the test database 'mytestdatabase', or 'no' to cancel: I type yes. I then get a traceback and at the bottom it says LookupError: No installed app with label 'providers'. These are my database settings: DATABASES = { 'default': { 'NAME': os.getenv('POSTGRES_NAME'), 'USER': os.getenv('POSTGRES_USER'), 'PASSWORD': os.getenv('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'TEST': { 'NAME': 'mytestdatabase', }, } } These are my installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'providers.apps.ProvidersConfig', 'storages', 'accounts', 'sso', 'rest_framework', 'widget_tweaks', 'anymail', 'mailchimp_marketing', 'mailchimp_marketing.api_client', 'analytics', ] This is the entire traceback: Creating test database for alias 'default'... Got an error creating the test database: database "mytestdatabase" already exists Type 'yes' if you would like to try deleting the test database 'mytestdatabase', or 'no' to cancel: yes Destroying old test database … -
Store list variable with Avg function in a Django aggregate
How to store and pass multiple Avg function in an aggregate the code below gives error of type views.py riasec_avg =[Avg('realistic'),Avg('investigative'),Avg('artistic'),Avg('social'),Avg('enterprising'),Avg('conventional')] context['riasec_male'] = Riasec_result.objects.filter(user__profile__gender='M').aggregate(riasec_avg) context['riasec_female'] = Riasec_result.objects.filter(user__profile__gender='F').aggregate(riasec_avg) -
Django self join with ForeignKey (ORM)
I have an Event Model: class Event(models.Model): message = models.CharField(max_length=128) timestamp = models.DateTimeField() cancels_event = models.ForeignKey('self', on_delete=models.CASCADE) I'm analysing lots of event messages, but firstly I need to check if the event has been canceled. Let's say I receive an Event_1, then I receive an Event_2 with Event_2.cancels_event=Event_1, so Event_2 cancels Event_1. I want to find out, given a subset of Events, which Events from this subset have been canceled. In SQL I'd use a join with self: SELECT * FROM Event e1 JOIN Event e2 ON e1.id = e2.cancels_event But I don't know how to do it within Django ORM. -
django 3.2 how to save multiple related model in a single model like inlineformset_factory using django-rest-framework?
I would like to store multiple checklist that belongs to a single declaration using django rest framework but i dunno how to implement it thanks for the help. Here are my models. class Question(models.Model): id = models.BigAutoField(primary_key=True) question = models.CharField(max_length=50) class Declaration(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(User, related_name='declarations', on_delete=models.CASCADE) class Checklist(models.Model): id = models.BigAutoField(primary_key=True) declaration = models.ForeignKey(Declaration, related_name='checklist_declarations', on_delete=models.CASCADE) question = models.ForeignKey(Question, related_name='checklist_questions', on_delete='models.CASCADE) is_yes = models.BooleanField() -
Sending image from front end(JavaScript) to backend(Django)
I have a image at the front end and I want to send it to the backend. I have simple JavaScript at the front end and Django-python at the backend. I have tried dozens of different methods and spent weeks but I am not able to figure this out. Can you guys suggest how can I achieve this on front end(sending part) and backend(receiving part). A piece of code with an advice would be really appreciated. I am using function based views on the backend. Can someone help me out with the backend code (if the front end code is right) to handle incoming from the front end. Because I have first converted the image file to base 64 stream in order to send it to the backend through fetch api. Front end code: const { snippet, transform } = anno.getImageSnippetById(annotation.id) //this function returns a DOM canvas element in snippet variable const base64Canvas = snippet.toDataURL("image/jpeg").split(';base64,')[1]; //converting into a base64 stream fetch(url1,{ method:'POST', headers:{ 'Content-type':'application/json', 'X-CSRFToken':csrftoken, }, body: {'snippet':base64Canvas} }) Backend code: def snippetCreate(request): serializer = Annotated_SnippetsSerializer(data=request['snippet']) image = base64_to_image(base64_string=serializer.data) img = Annotated_Snippets(asnippet=image) img.save() return Response({'success':'success'}) ``` base64_to_image: ```def base64_to_image(base64_string): format, imgstr = base64_string.split(';base64,') ext = format.split('/')[-1] return ContentFile(base64.b64decode(imgstr), name=uuid.uuid4().hex + … -
How can I set the `max` attribute of a number inout form widget within the view in Django?
so I have a form that allows the user to input a withdraw amount. I want the form to be rendered with the max attribute according to an aggregated value within a queryset in my view. But how can I actually update the form's attribute in the view before returning it to the client? # views.py def render_dashboard_overview(request): # Get the withdrawal form withdraw_form = WithdrawForm() # How to now set the `max` attr. of the number input to 500 for example? ... # forms.py class WithdrawForm(forms.Form): """ A form to withdraw available funds from Farena to the users bank account """ withdraw_amount = forms.FloatField(required=True, widget=forms.TextInput(attrs={ 'step': 0.01, 'min': 0 })) -
How convert PDF file of CSV file using python web development project
I used may ways in my knowledge to do I know to convert a pdf file to csv but I wanted to know how to do it in a website project i.e by using django framework how we can do it ...