Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
whenever i click outside the element it should close
I am trying to hide the notification list whenever I click outside but I didn't succeed. I tried different codes. class="notifications" should be seen when I click on class="notification" and should be hidden when I click outside. This code hide class="notification" (the main div) when i click outside. Js: $('.notification').on('click', function(event){ $(this).find('.counter').hide(); $(this).find('.notifications').toggleClass('hidden'); }); $(document).on('click', function(e) { if (e.target !== 'notification') { $('.notifications').hide(); } }); HTML: <div class="notification hide-on-med-and-down"> <span><img src="{% static 'img/notification2.png' %}" alt="Notification" title="Notification"></span> {% if unread_notifications_count %} <div class="counter">{{unread_notifications_count}}</div> {% endif %} <ul class="notifications hidden"> {% for n in notifications %} <li class="{% if not n.read %} new {% endif %}"> <div class="icon"><img src="/static/img/icon-popup.svg"></div> <a href="{{n|notification_url}}"> {{n.text}} <div class="date" data-date="{{n.date.ctime}}">{{n.get_date}}</div> </a> <div class="clearfix"></div> </li> {% endfor %} <a href="{% url 'notification_list' %}"><div class="see-all">See all</div></a> </ul> </div> -
How to update multiple tables in database(Django) using single .csv file?
Table Image. I want to distribute the data of above table into multiple tables. Say :- Product name and Company goes into 1st table. Barcode and Price goes into 2nd table. Category and Subcategory goes into 3rdtable. -
Postman post for creating a user via API results in a CSRF error - Why is that?
I am currently experimenting with Postman. I currently have a view that basically creates a user via a REST call as such I am using django rest for that class EmployerLogin_CreateAPIView(CreateAPIView): serializer_class = Serializer_EmployerLogin permission_classes = (permissions.AllowAny,)#permissions.IsAuthenticated def post(self, request, format=None): serializer = Serializer_EmployerLogin(data=request.data) if serializer.is_valid(): #populate the validated data modelUser = serializer.save() .... This is in urls.py url(r"^create/$", CreateEmployer_CreateAPIView.as_view(),name="Create_Employer"), When I attempt to call this api via Postman I get the error Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. My question is why am I getting this error and how can I resolve it ? From what I have read abut CSRF is that when a form is loaded in a webpage a cookie with a CSRF value is sent along with the form and then on submitting the form the values of the CSRF token are compared to make sure it was sent by the same form that was rendered by the view.Now in my case there is no form and the authentication on … -
Best Practice to deploy Django with celery apps
I'm developing the application that can broadcast messages periodically, and I have successfully developed and implemented it using django and celery locally using virtual environment. So right now I'm going to deploy it in my production. My questions are : How can I set configuration for production using script ? I've configured it one time but it was at laravel and using deploy-er. But this time, my application is using django. So I don't get any idea about it. How can I make the celery run in background service together and running well with my application when I deploy it ? If you have any references about it, do you mind to share it with me ? so I can learn about it because I'm still confused on how to implement it. Thank you for your answer. -
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'mysite.routing'
i want to use websockets in django... so i install channels with this command pip install channels then i set channels in installed app.. then i set channel layer CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgi_redis.RedisChannelLayer', "CONFIG": { "hosts": [('localhost', 6379)], }, 'ROUTING': 'mysite.routing.channel_routing', }, } then i set ASGI_APPLICATION = "mysite.routing.application" when i run this command manage.py runserver i get error: django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'mysite.routing' why i am getting this error?? -
Time-driven code in Django
I have a time driven code in my project. Lets assume that at 6pm (i.e. Mon to Fri) the code must automatically send an email to the user. I've written the code and it works fine, my problem is triggering the code automatically at a chosen time. Thanking you in advance. -
Installation error in uwsgi in cygwin64 in window
I am going to install uwsgi using cygwin64 pip3 install uwsgi after running its show me error plugins/router_basicauth/router_basicauth.c:9:10: fatal error: crypt.h: No such file or directory #include ^~~~~~~~~ compilation terminated. Failed building wheel for uwsgi Running setup.py clean for uwsgi Failed to build uwsgi plugins/router_basicauth/router_basicauth.c:9:10: fatal error: crypt.h: No such file or directory #include ^~~~~~~~~ compilation terminated. ---------------------------------------- Command "/usr/bin/python3 -u -c "import setuptools, tokenize;file='/tmp/pip-install-quuqvtp0/uwsgi/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-record-rf2m_6y8/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-quuqvtp0/uwsgi/ Please help me how can i solve this issue? -
can we store mails after restarting mailcatcher server?
I already tried this "SQLite3::Database.new(":memory:", :type_translation => true).tap do |db| in mail.rb." but still after restarting mailcatcher server it not gives me an old mails -
File not found in Javascript
I'm using Javascript, where I need to read a file. I run it locally and it works perfectly, but when I try to do it running Django server, it fails because it doesn't find the file. Does anybody know how to solve this? Here it is the error that Django gives [12/Jul/2018 12:37:36] "GET /ListadoCanciones/jugar/ HTTP/1.1" 200 7265 Not Found: /ListadoCanciones/jugar/DrumsInfo.csv [12/Jul/2018 12:37:36] "GET /ListadoCanciones/jugar/DrumsInfo.csv TTP/1.1" 404 3842 -
DJANGO Form inserts null for ModelMultipleChoiceField with model-manyTomany
I am new in learning python,i have 2 tables called Roles-id,role_name(values are-Guest,Admin,User) SignInView- id,username,password,role_id(where role_id is m2m field) When i try to login into page Roles gets poulated from database in select box which has muliple select option: enter image description here After entering username,password,and selecting 2 roles and submit gets submitted into "SignInView"-model tabe but third column role_id is null. enter image description here Forms.Py: class SignInForm(forms.ModelForm): role = forms.ModelMultipleChoiceField(queryset=Roles.objects.all(),widget=forms.SelectMultiple) password=forms.CharField(widget=forms.PasswordInput) class Meta: model=SignInView fields = '__all__' Models.py class Roles(models.Model): role_name=models.CharField(db_column='role_name', max_length=200) class Meta: db_table='Roles' def __str__(self): return self.role_name class SignInView(models.Model): username=models.CharField(db_column='username',max_length=200) password=models.CharField(db_column='password',max_length=200) role=models.ManyToManyField(Roles,blank=True) class Meta: db_table='signinview' views.py class SignInView(TemplateView): template_name='signin.html' def get(self,request): signform=SignInForm() return render(request, self.template_name, {'signform':signform}) def post(self,request): if request.method == 'POST': signform=SignInForm(request.POST or None) if signform.is_valid(): print(signform.cleaned_data['role'])#value is available instance=signform.save(commit=False) #instance.save() if this line is uncommented it inserts all values with role_id as null for roles in signform.cleaned_data['role']: instance.role.add(roles) #instance.save()if this line is uncommented getting error signform._save_m2m() return render(request, self.template_name, {'signform':signform}) else: signform = SignInForm() return render(request, self.template_name, {'signform':signform}) Request: I need 2 records to be inserted in SignInView model if i select 2 roles in dropdown like [Guest(id=10,Admin[id=20].can anyone please help.enter image description here -
Django REST framework use AJAX url to point api detail url
I'm working on database program using Django. The program appends the database from user's forms/imported files, allows listing of data per category, and inline editing per category. I did a lot of research (since i'm new in django), and so far I've been successful in generating forms, and and customized tables by combining rest framework and datatables. The problem occurs when I tried to implement inline editing to my tables. I using the plugin datatables editor. My views and serializer seem to work since i can POST, PUT and DELETE in the Api Root. But then I can't make the ajax url point to the methods api detail views, I need the pkin the url to be variable to match the selection: my serializer.py class TankSerializer(serializers.ModelSerializer): modified_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M', input_formats=None) updated_by = serializers.SlugRelatedField(slug_field='last_name', queryset=User.objects.all()) pid = serializers.SlugRelatedField(slug_field='number', queryset=PID.objects.all()) zone = serializers.SlugRelatedField(slug_field='number', queryset=ProcessZone.objects.all()) medium = serializers.SlugRelatedField(slug_field='code', queryset=Medium.objects.all()) revision = serializers.SlugRelatedField(slug_field='code', queryset=Revision.objects.all()) supplier = serializers.SlugRelatedField(slug_field='name', queryset=Supplier.objects.all()) po = serializers.SlugRelatedField(slug_field='number', queryset=PO.objects.all()) material = serializers.SlugRelatedField(slug_field='name', queryset=Material.objects.all()) DT_RowId = serializers.SerializerMethodField() def get_DT_RowId(self, tank): return 'row_%d' % tank.pk class Meta: model = Tank fields = ( 'DT_RowId', 'tag', 'description', 'pid', 'zone', 'medium', 'revision', 'supplier', 'po', 'material', 'volume', 'hight','modified_date','updated_by', 'created_by' ) my views.py @login_required @ensure_csrf_cookie def … -
dictionary key and value in combine with django query
I have a very complicated case for me that I couldn't solve related dictionary function in django. Here is my data output that I am retrieving via html post messages.add_message(request, messages.INFO, data) function: {'id_370': '370', '350_370': 'try_1', '450_370': 'try_2', 'id_397': '397', '350_397': 'try_3', '450_397': 'try_4'} try-1 try-2 try-3 try-4 are the input that I would like to update in my database. Basically what I want to do is that look for id_ and filter that object with this command qs = RFP.objects.filter(id=i.lstrip('id_') Till here (first for loop)it works fine. What I couldn't do is that another for "for x in val" loop where I am checking the id at the end of the key like _370 and _397 and if that fits that key, I would like to retrieve it's value and update my database if it's length more than 1. I am trying to do since 2 weeks and read lots of documents but my skills is not enough for solution but I think I am on right path am I not ? I would be very happy if someone enlightens me. :) Here is my view.py as per below where I am having logic problem else: if request.method … -
Unable to run django server using command prompt in windows 7
Below are the error logs "MyFirstProject" is the name of my project Any clue about D:\DjangoProject\MyFirstProject>django-admin-script.py startproject MyFirstProject'django-admin-script.py' is not recognized as an internal or external command, operable program or batch file.D:\DjangoProject\MyFirstProject>python manage.py startproject MyFirstProject Traceback (most recent call last):File "manage.py", line 15, in <module> execute_from_command_line(sys.arg)File "C:\Users\Naqvi\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute()File "C:\Users\Naqvi\AppData\Local\Programs\Python\Python37\lib\site-packages\ django\core\management\__init__.py", line 347, in execute django.setup()File "C:\Users\Naqvi\AppData\Local\Programs\Python\Python37\lib\site-packages\ django\__init__.py", line 24, in setupapps.populate(settings.INSTALLED_APPS)File "C:\Users\Naqvi\AppData\Local\Programs\Python\Python37\lib\site-packages\ django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\Naqvi\AppData\Local\Programs\Python\Python37\lib\site-packages\ django\apps\config.py", line 90, in createmodule = import_module(entry)File "C:\Users\Naqvi\AppData\Local\Programs\Python\Python37\lib\importlib\__in it__.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_loadFile "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'import_export D:\DjangoProject\MyFirstProject> this? Why I am getting this error I have reinstalled python, Django through pip command and also the enviroment variables seems to be fine. -
Using Python,how to Display the googlesheet Excel data in frontend without the connection between database
Please Help Me over this! I have Using the Pycharm IDE. I need to view the particular excel file data in the Front End. -
SECURE_SSL_REDIRECT does nothing
I have set SECURE_SSL_REDIRECT in my settings to True. If True, the SecurityMiddleware redirects all non-HTTPS requests to HTTPS (except for those URLs matching a regular expression listed in SECURE_REDIRECT_EXEMPT). I've also set PREPEND_WWW = True and BASE_URL = "https://www.******.com" My site is usually HTTPS: But I've purposely embedded a HTTP image in a page which has turned it to this: However when I go on that page, it doesn't redirect to HTTPS. Why is this and how can I fix it? PS: Here is my middleware if that matters: 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', ] -
jQuery: add table row using Django forms tag
I want to dynamically create new table row using Django forms tag inside the .html file. Why this code doesn't work? The code works when I try to add new table row using hard code input tag. How to fix this? jQuery //Add option row-- QCM $("#add_option").click(function(){ $('.option-list tr:nth-last-child(2)').after('<tr class="option_row"><td>{{optionForm.option_name}}</td><td>{{optionForm.answer}}</td><td><i class="material-icons option-delete">delete</i></td></tr>'); }); .html <table id="fresh-table" class="table table-striped option-list table-hover table-sm"> <thead class="thead-table-list"> <tr> <th scope="col">Option</th> <th scope="col">Answer</th> <th></th> </tr> </thead> <tbody> <tr class="option_row"> <td>{{optionForm.option_name}}</td> <td>{{optionForm.answer}}</td> <td><i class="material-icons option-delete">delete</i></td> </tr> <tr class="option_row"> <td>{{optionForm.option_name}}</td> <td>{{optionForm.answer}}</td> <td><i class="material-icons option-delete">delete</i></td> </tr> <tr class="option_row"> <td>{{optionForm.option_name}}</td> <td>{{optionForm.answer}}</td> <td><i class="material-icons option-delete">delete</i></td> </tr> <tr class="option_row"> <td>{{optionForm.option_name}}</td> <td>{{optionForm.answer}}</td> <td><i class="material-icons option-delete">delete</i></td> </tr> <tr> <td colspan="3"><u id="add_option">Add New</u></td> </tr> </tbody> </table> -
error in going to admin superuser
i write this from django doc and when i run python manage.py runserver in windows commandline and when go to the http://127.0.0.1:8000/admin/ i see this error TypeError at /admin/ 'set' object is not reversible Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 2.0.7 Exception Type: TypeError Exception Value: 'set' object is not reversible Exception Location: C:\Users\Muhammad\DOCUME~1\PYTHON~2\env\lib\site-packages\django\urls\resolvers.py in _populate, line 418 Python Executable: C:\Users\Muhammad\DOCUME~1\PYTHON~2\env\Scripts\python.exe Python Version: 3.7.0 Python Path: ['C:\\Users\\Muhammad\\Documents\\Python Projects\\env\\mysite', 'C:\\Users\\Muhammad\\DOCUME~1\\PYTHON~2\\env\\Scripts\\python37.zip', 'C:\\Users\\Muhammad\\DOCUME~1\\PYTHON~2\\env\\DLLs', 'C:\\Users\\Muhammad\\DOCUME~1\\PYTHON~2\\env\\lib', 'C:\\Users\\Muhammad\\DOCUME~1\\PYTHON~2\\env\\Scripts', 'C:\\Users\\Muhammad\\AppData\\Local\\Programs\\Python\\Python37\\Lib', 'C:\\Users\\Muhammad\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\Muhammad\\DOCUME~1\\PYTHON~2\\env', 'C:\\Users\\Muhammad\\DOCUME~1\\PYTHON~2\\env\\lib\\site-packages'] Server time: Thu, 12 Jul 2018 09:24:54 +0000 and this is my urls.py -
UnboundLocalError at /index/signup/ local variable 'verification' referenced before assignment
dont know what is wrong with my code here is my views.py section def signup(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) verification=VerificationForm(request.POST) if form.is_valid(): userObj = form.cleaned_data username = userObj['username'] email = userObj['email'] password = userObj['password'] return HttpResponseRedirect('/index/verification/') # if if not (User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists()): User.objects.create_user(username, email, password) user = authenticate(username = username, password = password) login(request, user) return HttpResponseRedirect('/') else: raise forms.ValidationError('Looks like a username with that email or password already exists') else: raise forms.ValidationError('a valid') else: form = UserRegistrationForm() return render(request, 'question/signup.html',context= {'verification':verification,'form' : form}) but this is the error i have been facing while i run the code UnboundLocalError at /index/signup/ local variable 'verification' referenced before assignment and the exact line where the issue occurs is return render(request, 'question/signup.html',context= {'verification':verification,'form' : form}) any kind of help is appreciated -
django - last() and first() return the same object
I have two objects in a queryset which is ordered by the created date. I am trying to get the first and last element out of there: ordered = self.get_queryset().order_by('created') print(ordered) print(ordered.first(), ordered.last()) When running the code, this is the output: <QuerySet [<Item: itemone>, <Item: itemtwo>]> itemone itemone There are clearly two objects, but for some reason, its giving me the same one. Btw: I am using SQLite3. Thanks! -
Django InlineFormSet Validation does not raise ValidationError
I'm having trouble validating the data of my InlineFormSet. What I want is to require at least one Qualification inputted in the formset. But everytime I hit the submit button with an empty Qualification, it does not raise a ValidationError. Here's my code: forms.py class QualificationForm(forms.ModelForm): class Meta: model = Qualification fields = ['qualification'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.disable_csrf = True self.helper.help_text_inline = True self.helper.label_class = 'col-sm-4' self.helper.field_class = 'col-sm-8' self.helper.layout = Layout( Field('qualification') ) class QualificationCustomInlineFormSet(forms.BaseInlineFormSet): def clean(self): cleaned_data = super().clean() for form in self.forms: qualification = cleaned_data.get('qualification', '').strip() if not qualification: msg = "Please enter qualification." self.add_error('qualification', msg) raise forms.ValidationError(msg, "error") return cleaned_data views.py class JobAddView(LoginRequiredMixin, SuccessMessageMixin, FormView): template_name = 'cepalco_website_admin/job_form.html' form_class = forms.JobForm success_url = reverse_lazy('cepalco_website_admin:home') success_message = "Successfully added %(job_title)s!" head_title = "Add new job" title_text = head_title description = "Enter the following job information" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['head_title'] = self.head_title context['title_text'] = self.title_text context['description'] = self.description QualificationInlineFormSet = inlineformset_factory( Job, Qualification, form=forms.QualificationForm, formset=forms.QualificationCustomInlineFormSet, extra=0, can_delete=False, min_num=1 ) WorkAssignmentInlineFormSet = inlineformset_factory( Job, WorkAssignment, form=forms.WorkAssignmentForm, extra=0, can_delete=False, min_num=1 ) context['qualification_inlineformset'] = QualificationInlineFormSet context['work_assignment_inlineformset'] = WorkAssignmentInlineFormSet return context template {% extends 'cepalco_website_admin/base_admin_main.html' %} {% load static %} … -
Pass python object to views Django
I have a first view in my application that display a form, a second one get the form answer, compute some operations and display the results in a table. I want the user able to save those results by downloading a csv file which is generated on the flow (I don't want to create and store the file in the server side, it have to be generated like a steaming file). Furthemore, I don't want to put data on the url or store it in database. I don't really know how to do that, I wanted to add the python object to the request.POST QueryDict but it's an unmutable one. Maybe it doesn't need a specific view and just have to launch a python function when user click on dl button. If you have any suggestion or hint, let me know ! Thanks. -
psql granting admin privileges not showing up in \du
I am trying to grant admin privileges to the user myappadmin but when I do \du it shows nothing. Here are the results raj=# GRANT ALL PRIVILEGES ON DATABASE myapp TO myappadmin; GRANT raj=# \du List of roles Role name | Attributes | Member of ------------+------------------------------------------------------------+----------- raj | Superuser, Create role, Create DB, Replication, Bypass RLS | {} myappadmin | | {} raj=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+------------+----------+-------------+-------------+--------------------------- raj | raj | UTF8 | en_US.UTF-8 | en_US.UTF-8 | postgres | raj | UTF8 | en_US.UTF-8 | en_US.UTF-8 | myapp | myappadmin | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =Tc/myappadmin + | | | | | myappadmin=CTc/myappadmin template0 | raj | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/raj + | | | | | raj=CTc/raj template1 | raj | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/raj + | | | | | raj=CTc/raj (5 rows) raj=# however when I do a makemigrations I get the error django.db.utils.OperationalError: FATAL: role "myappAdmin" does not exist I believe that has to do with privileges assigned to myappAdmin. Any suggestions ? -
TypeError when make migration with django and cassandra
when I execute python manage.py migrate I get the following TypeError: TypeError: Unknown option(s) for sync_cassandra command: app_label, fake, fake_initial, interactive, migration_name, run_syncdb. Valid options are: database, help, no_color, pythonpath, settings, skip_checks, stderr, stdout, traceback, verbosity, version. I'm using Cassandra 3.11.2, Python 3.5.2 and django 2.0.7. All run in Ubuntu Server 16.04 Thanks! -
Django: filter_horizontal alternative for foreign key
I've got a foreign key object with hundreds of values, which makes it very hard to select from the default dropdown UI. I also tried using raw_id_fields which is closer to what I want. But ideally I'm looking for something more intuitive, that provide key-to-key searching to expedite data entry. I found quite a few options for many-to-many fields, but none for ForeignKey. Has anyone come across any native or third party tool to improve this functionality? -
Deploy Django Application HTTPD
I wanted to deploy my Django Application and tried to achieve that with Whitenoise , but this last one only serves my static files, now I need to serve my media files. I want to use Apache ( HTTPD in Manjaro/Arch) to do that but couldn't figure it out, after trying several tutos. Here's my config : httpd.conf: LoadModule wsgi_module modules/mod_wsgi.so WSGIScriptAlias / /home/chemsouh/dev/rci/rci/wsgi.py WSGIPythonHome /home/chemsouh/dev/rci WSGIPythonPath /home/chemsouh/dev/rci/rci <Directory /home/chemsouh/dev/rci/rci> <Files wsgi.py> Require all granted </Files> </Directory> settings.py: MEDIA_URL = '/media-directory/' MEDIA_ROOT=os.path.join(os.path.dirname(BASE_DIR), "media-serve/") I also tried this: in my httpd-vhosts.conf: <VirtualHost 127.0.0.1:80> ServerAdmin RCI DocumentRoot "/home/chemsouh/dev/rci/media-serve" ServerName rci.co ServerAlias www.rci.co ErrorLog "/var/log/httpd/dummy-host.example.com-error_log" CustomLog "/var/log/httpd/dummy-host.example.com-access_log" common </VirtualHost> in my httpd.conf: DocumentRoot "/home/chemsouh/dev/rci/media-serve" <Directory "/home/chemsouh/dev/rci/media-serve"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> And I got this My media directory that I want to serve