Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to auto delete the expires data in the database?
If I store a row data in the database table(instance), and the table has a field names expire_time. if the time over the expire_time, I want to delete the row data. So, if I want to do that, I can every time query the table, traverse every row data, if expires, then delete. But if I don't query I can not realize the requirement. So, if there is a method to do that? I use python django, the database is mariadb. -
Programming error while saving json data to django model using amazon redshift
Got the following error while inserting data into Django model. I am storing JSON data after converting data into a string in Amazon Redshift PostgreSQL db.utils.ProgrammingError: syntax error at or near "RETURNING". -
Django - {% csrf_token %} was used in a template
After submission, I get error 400 and the following message: create_foo.html: <form class="modal-form" method="post" action="{% url 'create_foo'> %}"> {% csrf_token %} {{ forms }} </form> create_foo.py: @require_POST @login_required(login_url='/login/') def create_foo(request): # # if form.is_valid(): return HttpResponse('Success', status=201) return JsonResponse({'html': render_to_string('create_foo.html', {'forms': form), 'message': 'Failed'}, status=400) I have problem when is error 400 I have a form with a message error. I can not improve the data on the form and go on, and i have a error: /usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py:67: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. "A {% csrf_token %} was used in a template, but the context " I appreciate help -
Remove the action bar in the django template
How to remove the action bar from the top that contains the option Delete selected Users ? remove the action bar completely and leave the space lank how to do it ? -
Django-dash /account/login not found error 404
I am trying to build a dashboard using Django-dash. I have followed instructions as per the website. When i run the dashboard (localhost:8000/dashboard), my url gets redirected to localhost:8000/accounts/login/?next=/dashboard/ and i get a 404 error. I am not able to understand how the redirection to /accounts/login happens. I cannot find this in urls.py. Also is accounts/login supposed to be in-built within Django-dash? If so where should i check this? My urls.py looks like this: url(r'^dashboard/', include('dash.urls')) dash.urls looks like this: from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from .views import ( add_dashboard_entry, clone_dashboard_workspace, copy_dashboard_entry, create_dashboard_workspace, cut_dashboard_entry, dashboard, dashboard_workspaces, delete_dashboard_entry, delete_dashboard_workspace, edit_dashboard, edit_dashboard_entry, edit_dashboard_settings, edit_dashboard_workspace, paste_dashboard_entry, plugin_widgets, ) __title__ = 'dash.urls' __author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>' __copyright__ = '2013-2017 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('urlpatterns',) urlpatterns = [ # Paste dashboard entry url(_(r'^entry/paste/(?P<placeholder_uid>[\w_]+)/' r'(?P<workspace>[\w_\-]+)/pos/(?P<position>\d+)/$'), view=paste_dashboard_entry, name='dash.paste_dashboard_entry'), url(_(r'^entry/paste/(?P<placeholder_uid>[\w_]+)/pos/(? P<position>\d+)/$'), view=paste_dashboard_entry, name='dash.paste_dashboard_entry'), # Cut dashboard entry url(_(r'^entry/cut/(?P<entry_id>\d+)/$'), view=cut_dashboard_entry, name='dash.cut_dashboard_entry'), # Copy dashboard entry url(_(r'^entry/copy/(?P<entry_id>\d+)/$'), view=copy_dashboard_entry, name='dash.copy_dashboard_entry'), # Add dashboard entry. url(_(r'^entry/add/(?P<placeholder_uid>[\w_]+)/(?P<plugin_uid>[\w_\-]+)/' r'ws/(?P<workspace>[\w_\-]+)/pos/(?P<position>\d+)/$'), view=add_dashboard_entry, name='dash.add_dashboard_entry'), url(_(r'^entry/add/(?P<placeholder_uid>[\w_]+)/(?P<plugin_uid>[\w_\-]+)/' r'ws/(?P<workspace>[\w_\-]+)/$'), view=add_dashboard_entry, name='dash.add_dashboard_entry'), url(_(r'^entry/add/(?P<placeholder_uid>[\w_]+)/(?P<plugin_uid>[\w_\-]+)/' r'pos/(?P<position>\d+)/$'), view=add_dashboard_entry, name='dash.add_dashboard_entry'), url(_(r'^entry/add/(?P<placeholder_uid>[\w_]+)/' r'(?P<plugin_uid>[\w_\-]+)/$'), view=add_dashboard_entry, name='dash.add_dashboard_entry'), # Edit dashboard entry. url(_(r'^entry/edit/(?P<entry_id>\d+)/$'), view=edit_dashboard_entry, name='dash.edit_dashboard_entry'), # Delete dashboard entry. url(_(r'^entry/delete/(?P<entry_id>\d+)/$'), view=delete_dashboard_entry, name='dash.delete_dashboard_entry'), # *************************************************************** # ********************** Edit dashboard … -
How to filter object in django models?
I have write down A model to store data. like this. class Country(models.Model): Countryname = models.CharField(max_length=200) def __unicode__(self): return self.Countryname class CountryDiseases(models.Model): country = models.ForeignKey(Country,on_delete=models.CASCADE) pmid = models.CharField(default= 'No Data',max_length=254) serogroup = models.CharField(default= 'No Data', max_length=254) serotype = models.CharField(default= 'No Data', max_length=254) biotype = models.CharField(default= 'No Data',max_length=254) collection_year = models.CharField(default= 'No Data',max_length=254) NoOfStrains = models.CharField(default= 'No Data', max_length=254) def __unicode__(self): return self.NoOfStrains A url to render data like this: url(r'^DATAPLO/(?P<pk>\d)/$', views.County_Details, name='County_Details'), In short, i have a template that contains country list with a hyperlink, when some one click on a country it should produce a list of all the data associated with the particular country like the given urls, http://127.0.0.1:8000/DATAPLO/india where "India" keyword will transferred to the given views and view will extract all the object through filter method: C_Details = CountryDiseases.objects.filter(country__country=pk) A view to extract and present data like this: def County_Details(request,pk): C_Details = CountryDiseases.objects.filter(country__country=pk) #C_Details = CountryDiseases.objects.filter(country='india') return render(request, 'DATAPLO/Country_Details.html', {'C_Details': C_Details}) it produces the urld like this: http://127.0.0.1:8000/DATAPLO/india http://127.0.0.1:8000/DATAPLO/USA http://127.0.0.1:8000/DATAPLO/canada but data has not been extracted. -
extend existing django-platform (openEDX)
i'm new to django and not sure whats the best way to extend an existing platform. especially i'm talking about openedx. options: fork the edx-platform-repo and create a new django-app where i try to unregister models and register mine and try to override everything i want to customize from this app fork the edx-platform-repo and change code where it appears and create a new django-app just for completly new models what is the better option and how well does that work to override models from an other app in django? or could you maybe provide some other better solution??? thx -
create a django user while creating a records for model
py as below, from django.db import models from django.contrib.auth.models import User class members(models.Model): auto_id = models.AutoField(primary_key=True) member_name = models.OneToOneField(User) owner = models.ForeignKey('auth.User', related_name='webapi', on_delete=models.CASCADE) father_name = models.CharField(max_length=25, blank=False, default='') wife_name = models.CharField(max_length=25, blank=False, default='') number_of_child = models.IntegerField(blank=True) address_line_1 = models.CharField(max_length=40, blank=False, default='') address_line_2 = models.CharField(max_length=40, blank=True, default='') city = models.CharField(max_length=25, blank=False, default='') class Meta: ordering = ('member_name',) Now The above has been linked with django auth Users table and in steriliser it shows the existing Django users and I have to choose one during the submit. But my requirement is as a admin user I login and then provide the member_name manually which should automatically create a django user also -
'set' object has no attribute '__getitem__'
I have a dictionary name typecontext and I have a list named types. I want to take five elements of types and add it to the dict typecontext. I am getting a error that set attribute has no object getitem. try: k=0 typecontext = dict() for i in range(0, len(types), 5): print(i) if i + 5 < len(types): typecontext.update({'item_'+str(k) :types[i:i + 5]}) else: typecontext.update({'item_' + str(k): types[i:len(types)]}) k=k+1 except Exception as e: print(e) -
how can model: class1 or class2 have relation with class3 but both Simultaneous don't have relation?
I have three class: or class 1 has OneToMany relation with Class 3 or class 1 has OneToMany relation with Class 3 and both of them don't have relation Simultaneous how can model this database enter image description here -
How use suds - python
I'm trying to use stamps.com WSDL service - here is the link http://34.212.2.126:8000/api/TEST/ i'm getting this message (Server raised fault: 'Invalid SOAP message due to XML Schema validation failure. The element 'Credentials' in namespace 'http://stamps.com/xml/namespace/2017/04/swsim/swsimv62' has incomplete content. List of possible elements expected: 'IntegrationID' in namespace 'http://stamps.com/xml/namespace/2017/04/swsim/swsimv62'.') this is the python code i'm using ` client = Client(stamp_endPoint) client.set_options(port='SwsimV62Soap') response = client.service.AuthenticateUser() return HttpResponse(response)` Here is the WSDL file- https://drive.google.com/file/d/0B6Q9btduOt7AeVQtQk1mSkZ3RkU/view I have login Credentials (IntegrationID,Username,Password) but i don't know how to insert them. -
pop up dialog box instead raising form errors django
this is the pop up dialog box that i want to have this is the error message that i wish to be replaced by the pop up dialog box Right now the code is showing an error message for example "studentID: ensure this value has at least 8 characters" in the page before the field when studentID has less or more than 8 characters, the start and end date have no difference of 14 days, and when studentID and startDate is not unique. I am able to do the pop up dialog box only when student ID, student name and checkbox is not filled. How do i get the pop up dialog box being shown when start and end date field is empty, start and end date has no difference of 14 days, studentID and startDate is not unique, studentID has less/more than 8 characters ? views.py def timesheet(request): if request.method == "POST": form = TimesheetForm(request.POST) if form.is_valid(): timesheet = form.save(commit=False) timesheet.save() else: form = TimesheetForm() return render(request, 'hrfinance/timesheet.html', {'form': form}) class TimesheetForm(forms.ModelForm): checkbox = forms.BooleanField() studentName = forms.CharField() startDate = forms.DateField() endDate = forms.DateField() class Meta: model = Timesheet fields = '__all__' def clean(self): cleaned_data = super(TimesheetForm, self).clean() startDate … -
DRF request handler is throwing exception: retrieve() got an unexpected keyword argument 'pk'
I'm trying to retrieve a model instance in Django Rest Framework 3.6.3 at /path/to/API/widget/1/, 1 being the primary key of the widget. It's giving me: retrieve() got an unexpected keyword argument 'pk' From the trace I think I'm doing something to cause dispatch to throw an exception when instantiating the handler (from views.py, source here). I don't understand what I'm doing wrong through when I examine the source. Here's the trace: Traceback: File "/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/lib/python3.5/site-packages/rest_framework/viewsets.py" in view 86. return self.dispatch(request, *args, **kwargs) File "/lib/python3.5/site-packages/rest_framework/views.py" in dispatch 489. response = self.handle_exception(exc) File "/lib/python3.5/site-packages/rest_framework/views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "/lib/python3.5/site-packages/rest_framework/views.py" in dispatch 486. response = handler(request, *args, **kwargs) Exception Type: TypeError at /path/to/API/widget/1/ Exception Value: retrieve() got an unexpected keyword argument 'pk' -
Drf docs is not running on my system
Drf docs is not working. When i try to open the on local server http://127.0.0.1:8000/docs/ it is redirected to http://127.0.0.1:8000/changecity/?Next/docs/ I cannot understand why. If you could please help. -
Count objects in django subquery
count = Rate.objects.filter(obj_id=OuterRef('pk'), rated__isnull=False ).count() User.objects.filter(id=2).annotate( count=Subquery(count, output_field=IntegerField()) ) Don't work. How can I add count of some objects to User results. -
can not import patterns in django 1.11.4
My project urls.py is as follows: from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() urlpadrtterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^myapp/', include('myapp.urls')), ] My app urls.py is as follows: from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^hello/', 'myapp.views.hello', name = 'hello'),) Now , as soon as I try to run it , it gives me the following error: from django.conf.urls import patterns, include, url ImportError: cannot import name 'patterns' -
Exclude database from django migrations
Is there a way to exclude database from django migrations? I have a sphinxsearch database in my django project: DATABASES['sphinxsearch'] = { 'ENGINE': 'sphinxsearch.backend.sphinx', ... } And when I try to run manage.py makemigrations command, Django tries to run SHOW FULL TABLES query against it which leads to an error, because this is wrong syntax for sphinxql File "C:\Anaconda\lib\site-packages\django\db\backends\mysql\introspection.py", line 56, in get_table_list cursor.execute("SHOW FULL TABLES") ... django.db.utils.ProgrammingError: (1064, "sphinxql: syntax error, unexpected IDENT, expecting VARIABLES near 'FULL TABLES'") -
How to compare each field attribute in django by using additonal python library
Suppose I have following model: class Person(models.Model): user = models.ForeignKey(User, blank=False) city = models.ForeignKey(City, blank=False) def __str__(self): return self.user How to make programmatically in django/python to compare each field between each user like following: user1 = Person.objects.get(pk=1) user2 = Person.objects.get(pk=2) et seq. ... city1 = Person.objects.filter(city__name='value1') city2 = Person.objects.filter(city__name='value2') et seq. ... # Set new values from python's library outside django (I use geonames) for each user setobject1 = someGeonamesFunction(user1, city1) setobject2 = someGeonamesFunction(user2, city2) # Retrieve the values and then save into django database newfield1 = setobject1() newfield2 = setobject2() ... def save(self, *args, **kwargs) ... -
How to integrate Django form with Ajax?
I've gone through many tutorials in how to integrate ajax with django form but all were complicated. I have a Signup model with Signup form and a views like the following. models.py from django.db import models class SignUp(models.Model): name = models.CharField(max_length=120, blank=True, null=True) email = models.EmailField() def __unicode__(self): return self.email and forms.py from django import forms from .models import SignUp class SignUpForm(forms.ModelForm): class Meta: model = SignUp fields = ['name', 'email'] def clean_name(self): name = self.cleaned_data.get('name') return name def clean_email(self): email = self.cleaned_data.get('email') try: match = SignUp.objects.get(email=email) except SignUp.DoesNotExist: return email raise forms.ValidationError('This email address is already subscribed.') views.py from django.shortcuts import render from django.core.mail import send_mail from django.conf import settings from .forms import SignUpForm def index(request): form = SignUpForm(request.POST or None) if form.is_valid(): name = form.clean_name() email = form.clean_email() instance = form.save() subject = 'Bruke Church news' from_email = settings.EMAIL_HOST_USER to_email = [email] contact_message = "%s:Thank you for signing up for our newsletter via %s. we'll be in touch" %( name, email) send_mail (subject, contact_message, from_email, to_email, fail_silently=False) context = { "form": form } return render(request, "index.html",context) and my html form looks like this <form action="" method="POST"> {% csrf_token %} {{form|crispy}} <input type="submit" value="Sign up" class="btn btn-primary"> </form> This … -
Zappa Deployment error for django application
I have an application using django, django-rest framework which is running perfect local machine. Facing below error while deploying the same using zappa in both below ways. (drf-angular) E:\Projects_EDrive\AWS\Serverless\zappa\drf_sample\server>zappa deploy dev Packaging project as zip... [Error 3] The system cannot find the path specified: 'E:\\Projects_EDrive\\AWS\\Serverless\\zappa\\drf-angular\\lib\\python2.7\\site-packages/*.*' =========================================================================== (drf-angular) E:\Projects_EDrive\AWS\Serverless\zappa\drf_sample\server>python manage.py deploy dev Packaging project as zip... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "E:\Projects_EDrive\AWS\Serverless\zappa\drf-angular\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "E:\Projects_EDrive\AWS\Serverless\zappa\drf-angular\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\Projects_EDrive\AWS\Serverless\zappa\drf-angular\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "E:\Projects_EDrive\AWS\Serverless\zappa\drf-angular\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Python27\Lib\site-packages\django_zappa\management\commands\deploy.py", line 39, in handle self.create_package() File "C:\Python27\Lib\site-packages\django_zappa\management\commands\zappa_command.py", line 131, in create_package exclude=exclude File "E:\Projects_EDrive\AWS\Serverless\zappa\drf-angular\lib\site-packages\zappa\zappa.py", line 280, in create_lambda_zip shutil.copytree(site_packages, temp_package_path, symlinks=False, ignore=shutil.ignore_patterns(*excludes)) File "C:\Python27\Lib\shutil.py", line 171, in copytree names = os.listdir(src) WindowsError: [Error 3] The system cannot find the path specified: 'E:\\Projects_EDrive\\AWS\\Serverless\\zappa\\drf-angular\\lib\\python2.7\\site-packages/*.*' =========================================================================== In both the ways error would be same. I am deploying with zappa in virtualenv after installing required packages. [Error 3] The system cannot find the path specified: 'E:\\Projects_EDrive\\AWS\\Serverless\\zappa\\drf-angular\\lib\\python2.7\\site-packages/*.*' -
Django get model by querystring
I want the user to be able to pass a querystring in url like https://example.com/models?id=232. But the query string is optional. so https://example/models should work too. Im trying this: def myview(request, model): context = { 'model': model, } if request.GET.get('id', None) != None and Model.objects.get(pk=request.GET.get('id', None)).exists(): id = request.GET.get('id', None) context['id'] = id return render(request, 'tests.html', context) else: return render(request, 'tests.html', context) S what is going on in the code above: i want to check if there is a query string (which is models id) and if there exists this model. Bu tmy code does not work. If both of these requirement are not satisfied it should just load tests.html without id and without any errors. How can i do that? Also the id should just be number Looking forward for your answers :D -
Importing Bootstrap SCSS into a Django project
I do have two question related to the integration of Bootstrap into a Django project. My questions relate to the latest Bootstrap 4.x release (beta) at https://getbootstrap.com/docs/4.0/getting-started/download/. Question 1: For now, I import the CSS from the CDN via <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script> Do I assume correctly, that in my custom SCSS, I can not access the variables of Bootstrap (because it's a compiled CSS, not an SCSS)? I tried to change $spacer: 1rem !default; and it didn't work. Question 2: As I want to access the variables of the most recent Bootstrap 4 beta, I assume that I need to import the original SCSS. Now, how can I do that for a Python Django project? Or: What is the best practice to get the Git's SCSS files into my local appname/static/scss folder, where I can then compile the SCSS? Via cloning the git in that specific folder, or is there a more elegant way to solve it? Thanks for help! -
when is use django_tables2 it told me TemplateDoesNotExist
urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.people), ] views.py def people(request): return render(request, 'people.html', {'people': models.Person.objects.all()}) models.py class Person(models.Model): name = CharField(verbose_name="full name", max_length=10) people.html {% load render_table from django_tables2 %} {% load static %} {% render_table people %} when I run it it told me "TemplateDoesNotExist at /django_tables2/table.html",Idont understand why -
Django admin page adding save as pdf button
In the below code I have added a save as pdf button in admin page by customizing it.While I'm clicking the save as pdf button it should display the details of the current page in pdf format.I couldn't able to retrieve the separate data of the current page to display it in the pdf form(my_template.html).How to do it? Thanks in advance. View.py # -- coding: utf-8 -- from future import unicode_literals # Create your views here. from django.http import HttpResponse from django.views.generic import View from django.db import models from details.utils import render_to_pdf #created in step 4 from .models import UserDetails class GeneratePdf(View): def get(self, request, *args, **kwargs): #THIS IS THE PLACE WHERE I GET STRUCK all={"Name":"obj.name", "Email":"obj.email", "Address":"obj.address", "DOB":"obj.dob", "Gender":"obj.gender", } pdf = render_to_pdf('my_template.html', all) return HttpResponse(pdf, content_type='application/pdf') urls.py """myapp URL Configuration The urlpatterns list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a … -
Django: ManyToManyField.limit_choices_to seems not working properly
I have following models: ./models.py def limit_name_choices(): return {"pk__gt": Name.objects.last().pk} class Name(models.Model): name = models.CharField(max_length=100) primary = models.BooleanField() class Robject(models.Model): project = models.ForeignKey(to=Project, null=True) author = models.ForeignKey( to=User, null=True, related_name="robjects_in_which_user_is_author") create_by = models.ForeignKey( to=User, related_name="robjects_created_by_user", null=True) create_date = models.DateTimeField(null=True) modify_by = models.ForeignKey(to=User, null=True) name = models.ManyToManyField( "Name", related_name="robject_name", help_text='The name of robject', limit_choices_to= get_last_name_pk() ) view: def robject_create_view(request, *args, **kwargs): if request.method == "POST": form = RobjectForm(request.POST) if form.is_valid(): return redirect("/") else: form = RobjectForm() return render(request, 'robjects/create_robject.html', {"form":form}) and form: class RobjectForm(forms.ModelForm): class Meta: model = Robject fields = '__all__' # this comes from django-addanother (admin popup functionality) widgets = { 'name': AddAnotherWidgetWrapper( forms.SelectMultiple, reverse_lazy('add_name', args=['proj_1']), ), } I created imitation of admin Robject create form. This means I added 'plus button' next to ModelMultipleChoiceField name field, which leads to popup where I can create new Name. I intend to have empty name field (without choices) every time I open my robject create form. Unfortunately, I see previously created Names when I refresh the form page. My problem is, function limit_name_choices isn't called every time new form is instantiated. Is it a bug, or I am doing something wrong? From django documentation: https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to If a callable is used for …