Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting up front end using angular template(blurAdmin) and backend using django. How to make api calls to the backend
I'm using blurAdmin template as front end for a small web application. I want to use django framework purely for backend. I ran both the applications on different servers and tried to make an api call to backend, and get a JSON in response. However it failed. After searching for a while, I understood that I have to send CSRF token with my request header and send it over to the backend. I'm not sure how exactly to go about this. Can someone help me out on this. -
pytest-django run with migrations ignores database triggers
My Django app depends on a database with some triggers setup. I use this part of the documentation to set up the triggers in the test database for the pytest runner. @pytest.fixture(scope='session') def django_db_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): cur = connection.cursor() cur.execute([...]) # Set it up I run my tests with --nomigrations and it works as expected. Without --nomigrations (test runs migrations first), the triggers are not working. So trying to debug this, I've confirmed The fixture IS run, so the triggers SHOULD be setup Pausing execution in the debugger at the start of my tests, I can confirm that the triggers ARE created and present in the test database (by running psql test_<mydb> and looking in the pg_trigger table) Pausing execution inside my fixture, I can confirm that migrations are run before the fixture. So the migrations may setup the triggers for me, and they may do it incorrectly, but the fixture will drop all the triggers and recreate them Removing the fixture and running with migrations provide no new results. So there is no reason to think that the fixture is the problem. It seems to be only due to the migrations being run Let me just stress once … -
PyCharm Django project fails to run with debugging
For quite a while I have this weird problem on my Windows 10 machine. When trying to launch a Django server with (and sometimes even without) debugging on PyCharm, I get this error: ... pydev debugger: process 10532 is connecting Connected to pydev debugger (build 163.8233.8) Process finished with exit code -1073741819 (0xC0000005) That's how it looks without debugging: "C:\Program Files (x86)\PyCharm\bin\runnerw.exe" D:\project\env\Scripts\python.exe D:/project/manage.py runserver 80 Process finished with exit code -1073741819 (0xC0000005) The strangest thing is that if I re-run, some of the times (1 success in about 4-6 reruns) it will launch successfully. I also couldn't reproduce this problem without PyCharm. Specs: Windows 10 Pro, Pycharm (this happens on versions 5.x through 2016.3) x86 and x64 versions, Python 3.5x, Django 1.8-1.10.x. Any ideas why this happens or how to get some more detailed info about the crash? -
Showing extra filter options to further filter django haystack search results
I have implemented the default search functionality from django hastack website. I want to give filter options to the users in a sidebar. So that they can get to their desired results faster. My Doctor model has a 'location' field. I want to show distinct 'location' options in the sidebar as selectable filters for every search. How can this be achieved ? models.py class Doctor(models.Model): SPECIALTY_CHOICES = ( ... ) user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) doctorName = models.CharField(max_length=100) doctorQual = models.CharField(max_length=500) doctorSpecial = models.CharField(choices=SPECIALTY_CHOICES, null=True, blank=True, max_length=50) doctorSummary = models.CharField(max_length=1000) slug = models.SlugField(null=True, blank=True) location = models.CharField(max_length=60, null=True, blank=True) city = models.CharField(max_length = 100, null=True, blank=True) urls.py urlpatterns = [ ... url(r'^search/', include('haystack.urls')), url(r'^search/autocomplete/', autocomplete), ... ] search.html <div class="col-md-10" style="display:block;"> <div class="row"> <div class="col-md-10 col-xs-10"> <div id="custom-search-input" style="display:block;margin:0 auto;border:none;"> <form action="/search/" method="get" id="searchForm" class="autocomplete-me" autocomplete="off"> <div class="input-group col-md-12 col-xs-12" id="form_input_wrapper"> {% csrf_token %} <input type="text" id="id_q" name="q" class='form-control input-lg' style="box-shadow: 0 1px 8px 0 rgba(0,0,0,0.2);transition: 0.3s;min-height: 5%;padding: 1%;"/> </div> </form> </div> </div> <div class="col-md-2 col-xs-2" style="padding:1%"> <span class="input-group-btn"> <button type="submit" form="searchForm" class="btn btn-info btn-lg"style="border: none; background-color: white;border-left: 2px solid #ccc;"> <i class="glyphicon glyphicon-search" style="color:lightblue;"></i> </button> </span> </div> </div> <div class="row" style="padding:2%;"> {% if query %} <h3>Results</h3> {% for … -
New ubuntu user gets "mkvirtualenv: command not found" error
I was able to run a test Django application after installing all the required software. I was able to use mkvirtualenv and create two test apps that worked as required. I then decided to create another user in Ubuntu. This user does not possess Sudo privileges because I wanted to secure the environment. With this newly created user I get an error stating "mkvirtualenv: command not found". My bashrc file has the following commits:- export WORKON_HOME=$HOME/.virtualenvs export PATH=/usr/local/bin:$PATH export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv source /usr/local/bin/virtualenvwrapper.shsource /usr/local/bin/virtualenvwrapper.sh Running echo $WORKON_HOME results in the following:- /home/ubuntu/.virtualenvs I'm not particularly sure what I need to do to have the ability to use mkvirtualenv with the new user. Any help is appreciated. Thanks in advance! -
Django Static Files not Loading after deploying to heroku and while Debug = False
Well am a Django noob i built a Web Project using it now am facing some problems when am trying to turn debug to false and the other time when deploying to heroku even with debug to True the static files (css, js) doesnt load up in both the cases! So basically my Question comes in two part: Question 1 : When I turn my Debug = False in settings.py the static files i.e css, js, etc, etc. doesn't load up why is it happening ? Question 2: When i upload files to heroku with Debug = True in settings.py still doesnt load css and js why ? What am I doing wrong in both the cases ? Am using Django 1.10 With Python 3.5 Settings.py, HTML, & File Directory Settings.py import os SECRET_KEY = 'xxx' DEBUG = False ALLOWED_HOSTS = ['*'] EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail@example.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_USE_TLS = True INSTALLED_APPS = [ 'WebDev', 'Marketing', 'DataOutsourcing', 'Consultancy', 'BPO', 'Contact', 'Home', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ] SITE_ID = 1 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', ] ROOT_URLCONF = 'MegaaOpes.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
Disable foreign key constraint in Django project
For some reason, we will migrate our existed DB to another, and the new one forbid any foreign constraint key, which is a nightmare for my django project. Here is what my current django db looks like: I know db_constraint=False can disable django to create foreign key constraint, but i don't know how to deal the Django auth models. -
Django 1.9 unittest error for messages but i dont see the error for 1.10.4 and 1.8
The test fails with the error in Django 1.9 env, but tests run perfectly well in 1.10.4 and 1.8. Can someone throw some light here ! Here is the error add_message raise MessageFailure('You cannot add messages without installing ' MessageFailure: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware Check https://travis-ci.org/invaana/Hydronium/builds/182190626 for complete errors views.py def contact(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Operation Successful! This is demo. Im not sending any messages') else: form.errors messages.error(request, 'Message not sent, Please fix the errors!.' ) else: form = ContactForm() return render(request, 'pages/contact.html', {'form': form}) tests.py def test_contactform_valid(self): res = self.client.post(reverse('contact'), {'name':'Ravi','email':'rrmerugu@gmail.com', 'text': 'im good' }) self.assertIn('Operation Successful', res.content) def test_contactform_invalid(self): res = self.client.post(reverse('contact'), {'name':'Ravi','email':'rrmerugu@gmail.com', 'text': '' }) self.assertIn('Message not sent', res.content) -
Django model list order field update
I have a table, let's say Book, with the following model definition: class Book(models.Model): name = models.CharField('name of the book', max_length=10) sequence = models.IntegerField('The order for the book') I need to show the Book list order by sequence field as follow, and the sequence value would be 1, 2, 3, etc... Book.objects.all().order_by('sequence') But I am getting stuck when creating/updating a book instance in the view. I am not quite sure how to re-sequence the existing books when inserting a new book model or updating an existing one. Suppose, I already got three books in the database, let's say: BookA, sequence = 1 BookB, sequence = 2 BookC, sequence = 3 When I insert a new one, named BookD with sequence 1, I need to update the existing ones to assign a new sequence value for each book already in the database. My expected result would be: BookD, sequence = 1 BookA, sequence = 2 BookB, sequence = 3 BookC, sequence = 4 So does anyone know how to do this in django? Example code is really appreciated. Thanks in advanced. -
Django model time stamp range filter
I have a model field time_stamp = models.DateTimeField(timezone.now). Now I want to search based on date range, like 2016-11-08 to 2016-12-08. How can I do that. -
If using Django-tenat-schemas how to flush database?
I am using django-tenant-schemas app to handle tenants and database related to various tenants. Now what I want to do is flush all the database so how can this be done? -
How do authenticate using a single facebook app from a Cordova app and a django website
In the Facebook app domain for Cordova fb plugin to work i have to use localhost domain but from website i am using my own domain. Problem is that in fb we can put only one domain source. Also if i use in appbrowser fb open in a popup, and since inappbrowser supports one window at a time, during call back it returns in a blank page. Is there any way out or work around? Plz suggest. I will add info according to qs regarding my django setup(1.6, allauth, drf) -
Which framework / stack for a basic CRUD website?
I'm a java developer with an interest in web development. I can write a set of basic, static pages in HTML & CSS, with some basic javascript. Now I'd like to learn & develop a simple website with more interactivity, and add some basic server-side elements. Something like a web based / user specific todo list: user registration with user information (account, password, name, address, etc...) user login for each user, the possibility to consult, add & delete "todo" entries each of those entries can be modified / marked as "approved" or "completed" by an administrator (through another, unrelated process - that I would develop in Java and which would interact with the DB) all that in a secure & scalable manner (thousands to millions of users, hundreds of entries) I imagine I could do that with a LAMP setup, but I'd like to use a more modern framework. I've read on node.js (within MEAN), Rails, Django, and I imagine it's achievable with all of that, but is there a stack that would be more appropriate, or faster to develop, and why ? If anybody know of a specific resource or tutorial for something like that, I'm also a taker... … -
Django: How do I load models dynamically in app scripts
I have a script called helpers.py in my Django app in which I can't import models because it creates a circular reference. As a workaround to this problem, I tried loading the modules dynamically in the script, like so: from django.apps import apps MyModel=apps.get_model("mymodule", "MyModel") but this gets called before Django loads models and throws an error. Is there a way around this problem? Ideally I need to be able to create references to the model after Django has initialised the models, so that its available throughout the script, but I'm not sure if this is possible. -
Migration fails when extending Django User Model
I'm trying to extend django User model by inheriting AbstractBaseUser so i can be able to manipulate the authentication process of the project. Here is what my model looks like. class AccountManager(BaseUserManager): ... create_user ... create_superuser class Account(AbstractBaseUser): email = models.EmailField(unique=True) username = models.CharField(max_length=40, unique=True) objects = AccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] And here is my settings INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'rest_framework', 'compressor', 'authentication' ] AUTH_USER_MODEL = 'authentication.Account' The problem here i notice the migration process that django is by passing the auth.0001_initial and it step directly creating the admin.0001_initial making my migrations to fail with django.db.utils.IntegrityError: (1215, u'Cannot add foreign key constraint') -
Design of multiple tables "e.g. Post and Comment" ordered by one column "date" in both tables
I use Postgres 9.6 and Django 1.10, but this may be more generic than the software packages I am using. However due to Django ORM limitations or/and my understanding, it may be dependent on these software packages. My problem is I want to design Post and Comment tables. As easy as this seems, I will use heavily a query that fetches both Posts and Comments ordered by date which is a timestamp in both tables so I can have something like post 1hour ago, post 2 hour ago, comment 3 hour ago, post 4 hour ago Initial design can be like: Posts: `id`(serial primary key) | `author`(foreign key) | `title`(string) | `body`(string) | `created_on`(timestamp) and Comments: `id`(serial primary key) | post(foreign key to `Posts`) | `author`(foreign key) | `body`(string) | `created_on`(timestamp) I don't know if it's feasible using native SQL or something like SQLAlchemy, but I think it is impossible to merge both posts and comments ordered by created_on of both tables. I also looked into desiging posts and comments into something like this: Posts `id`(serial primary key) | `author`(foreign key) | `title`(string) | `created_on`(timestamp) and Comments: `id`(serial primary key) | post(foreign key to `Posts`) | `author`(foreign key) | `body`(string) … -
show the custom message in Django form
Sorry, I'm not good at English. I have some problem for studying Django. I wrote the below code to make a form. and I need to show the custom message when user didn't enter the value in text box. class ArticleForm(ModelForm): title = forms.CharField( error_messages={'required': 'Please enter title'}, max_length=128 , required=True, widget=forms.TextInput(attrs={'size':60})) contents = forms.CharField( required=True, widget=forms.Textarea(attrs={'cols': 160, 'rows': 20})) email = forms.CharField(max_length=128, widget=forms.TextInput(attrs={'size':60})) writed_by = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'size':60})) class Meta: model = Article fields = ["title", "writed_by", "email", "contents"] I want to show 'Please enter title' message when didn't enter the title. But form shows the default message. what is the problem in this code? Thanks. -
Right way to search the Database with optional form fields with Django Views
I have a form with multiple options, but most users will use only some of the filtering fields for the search. What is the right way to filter the results from the Database ? This is how I tried before, but something went wrong and it wont return anything. ( The simpler version of the search works, so I know the problem is in this view ) Views.py def advSearchResoults(request): searchTerms=[] pepList = [] pep = peptide.objects #data Fields try: pdb_id = request.GET['pdb_id'] if not pdb_id is "": searchTerms.append({'PDB iD': pdb_id}) pep = pep.filter(pdb_id__icontains = pdb_id) except: pass try: hfobic_area = request.GET['hfobic_area'] if not hfobic_area is "": searchTerms.append({'Hidrofobic Area':hfobic_area}) pep = pep.filter(hfobic_area__icontains = hfobic_area) except: pass # ... 14 Other fields like this for qr in pep: pepList.append(qr) return render(request, 'resoults.html', {'peptides':pepList,'searchTerms':searchTerms}) -
Django Admin on a very large database
Legacy DB with > 9mil records in a normalized DB, so multiple tables. When loading a table that has ForeignKeys to also very large tables, my newly installed (legacy DB adapted), Django admin is unusable slow - dead slow. Reason is simple, when trying to load the admin page, the ForeignKey table is being loaded to shove into a menu in the admin screen. This SQL fails to load quickly enough. Even if it did finish loading, the menu of items would be crazy huge, and not a suitable widget for the user. So ... has anyone else faced this and solved it? Perhaps there way to replace the menu with a filtered lookup? Any other clever solutions to this? Maybe a whole project could be created devoted to Django and the Admin on a large database. -
Passing parameter to Django url tag
I have a django template with a button: <form action="{{ destination }}"> <input type="submit" value="{{ button_text }}" /> </form> And I pass a url ('destination' parameter) to this template: return render_to_response('redirect_button.html', { 'button_text': 'Sign in', 'destination': reverse('myapp:signin') }) It works fine, but I would like to use url tag instead. I tried to use it the following way: <form action="{% url destination %}"> <input type="submit" value="{{ button_text }}" /> </form> return render_to_response('redirect_button.html', { 'button_text': 'Sign in', 'destination': 'myapp:signin' }) but it doesn't work this way. What can I do to pass a name of a view to url tag instead of converting view name to url in my python code and sending the result in the destination variable? And BTW, what is the best practice in this case? I mean, maybe I'm already doing it right? -
Am I use the correct freeze_time syntax?
I post https://github.com/spulec/freezegun/issues/168 But seems like everyone in there quite busy then please let me ask in here python: 3.5.1 Django: 1.9 pytest: 2.9.2 pytest-django: 2.9.1 freezegun: 0.3.8 models.py class NetworkCredential(models.Model): """ Store the zabbix username, zabbix password """ customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=False) user = models.CharField(max_length=255, null=False, blank=False) password = models.CharField(max_length=255, null=False, blank=False) enable = models.BooleanField(default=True) refresh_time = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(20)], default=3) created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True) expiry_datetime = models.DateTimeField(null=True, blank=True, default=None) class Meta: unique_together = ( ("customer", "user", "password", "enable", "refresh_time"), ) conftest.py: @pytest.fixture def prepare_network_credential(company): kwargs = { "customer": company, "user": "sivabudh.u", "password": 'codium#@!', "enable": True, "refresh_time": 2, } with freeze_time("2016-12-7 19:32:00"): return NetworkCredential.objects.create(**kwargs) tests.py def test_created_datetime(prepare_network_credential): """Test created_datetime""" prepare_network_credential.save() nc = NetworkCredential.objects.first() assert nc.created_datetime.strftime('%Y-%m-%d %H:%M:%S') == '2016-12-07 19:32:00' def test_updated_datetime(prepare_network_credential): """Test updated_datetime""" prepare_network_credential.save() nc = NetworkCredential.objects.filter(enable=True) with freeze_time("2016-12-8 20:20:00"): nc.update(user="Sarit") assert nc[0].user == "Sarit" import pdb; pdb.set_trace() assert nc[0].updated_datetime.strftime('%Y-%m-%d %H:%M:%S') == '2016-12-08 20:20:00' Terminal First one works, but 2nd does not _______________________________________________________________________________________________________ test_updated_datetime ________________________________________________________________________________________________________ prepare_network_credential = <NetworkCredential: NetworkCredential object> def test_updated_datetime(prepare_network_credential): """Test updated_datetime""" prepare_network_credential.save() nc = NetworkCredential.objects.filter(enable=True) with freeze_time("2016-12-8 20:20:00"): nc.update(user="Sarit") assert nc[0].user == "Sarit" > assert nc[0].updated_datetime.strftime('%Y-%m-%d %H:%M:%S') == '2016-12-08 20:20:00' E assert '2016-12-07 13:19:20' == '2016-12-08 20:20:00' E - 2016-12-07 13:19:20 E + 2016-12-08 … -
Django Templates: Can't access property of object present in Context
I'm confused. So I have this in a template {{ customer.email }} But nothing comes up on the rendered page. If I just do {{ customer }} This shows up on the rendered page: <EMAIL@gmail.com, email=EMAIL@gmail.com, token=IJJoif23408h> So, obviously the customer object is available. I am simply injecting the context like so: render(request, "template.html", context) Where context has a key customer What's going on? -
How to display text from a database table in a page header using django
I have 2 models, Student and Payment as such class Student(models.Model): full_name = models.CharField(max_length=255) class Payment(models.Model): id = models.AutoField(primary_key=True) student = models.ForeignKey( Student, related_name="student_payments", on_delete=models.CASCADE) payment_date=models.DateField("payment Date",blank=True,null=True) payment_amount=models.DecimalField("payment Amount",max_digits=6, decimal_places=2) check_number=models.CharField("check Number",max_length=20) VIEW class CreateListPaymentView(CreateView): form_class = CreatePaymentForm model = Payment template_name = 'createlistpaymentview.html' def form_valid(self, form): pmt = form.save(commit=False) pmt.student_id = self.kwargs['id'] pmt.save() return redirect(pmt.get_absolute_url()) def get_context_data(self, **kwargs): kwargs['object_list'] = Payment.objects.filter(student_id=self.kwargs['id']).order_by('payment_date') return super(CreateListPaymentView, self).get_context_data(**kwargs) def get_success_url(self): return reverse('createlistpaymentview',kwargs={'id':self.object.student_id}) URL url(r'^payment/(?P<id>\d+)/$', trip.views.CreateListPaymentView.as_view(),name='createlistpaymentview',), The student ID is passed to the URL like 127.0.0.1/payment/9 On this page I would like to display as part of the page header "Payments for " This would be student ID 9. I tried to use a context processor, but I cant find how to access the kwarg. Would a context processor be the way to do this, or should I include this in my view class? -
Django ChartIt Pie Chart Name Failure
I have a model that I want to use a pie chart to display the name and the numbers associated with them. I can get the pie chart to display slices with the numbers, but I cannot get it to add the name of the condition to the count, nor will it send me an email when it errors out so I can't figure out what's going on. The models are fairly simple: class TreeCondition(models.Model): name = models.CharField(max_length=256) class Tree(models.Model): condition = models.ForeignKey(TreeCondition, related_name='trees_in_this_condition') And here's the view: def uf_chart(request): condition_data = PivotDataPool( series = [ {'options': { 'source': TreeCondition.objects.all(), 'categories': ['name'] }, 'terms': {'condition_count': Count('trees_in_this_condition'),} } ] ) def condition_name(id_condition): names ={1: 'Excellent', 2: 'Very Good', 3: 'Good', 4: 'Fair', 5: 'Poor', 6: 'Critical', 7: 'Dead', 8: 'Unknown'} return names[id_condition] condition_chart = PivotChart( datasource = condition_data, series_options = [{'options':{ 'type': 'pie', 'stacking': False}, 'terms':[ 'condition_count'], }], chart_options = {'title': { 'text': 'Tree Condition' } } ) args = {'condition_data': condition_data, 'condition_chart': condition_chart} return render(request, 'uf_chart.html', args) This displays a correct pie chart with "Slice" instead of the name of the Condition. I just want to map the name to the condition count, but everything I do to add the … -
How to combine 2 django projects
I have 2 apps which i would like to combine, the first one is a login & register system and the next one is a file upload system how would i go by combining them?