Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django api framework getting total pages available
Is it possible to get how many pages an API request has available? For example, this is my response: { "count": 44, "next": "http://localhost:8000/api/ingested_files/?page=2", "previous": null, "results": [ { "id": 44, .... I'm pulling 20 elements per page, so there should be 2 pages in total, but currently the way it's set up I can get next and previous, but there's no context as to what the total amount of pages is. Sure I could do some math and get how many possible pages using the count, but I imagine something like this would be native to the framework, no? This is my view: class IngestedFileView(generics.ListAPIView): queryset = IngestedFile.objects.all() serializer_class = IngestedFileSerializer This is my serializer: class IngestedFileSerializer(serializers.ModelSerializer): class Meta: model = IngestedFile fields = ('id', 'filename', 'ingested_date', 'progress', 'processed', 'processed_date', 'error') -
Django - How to add user's IP address when form is POSTed
I know that if I'm inside of a request function, I get the user's IP address using ipware.ip's get_ip(request) or other methods, but I'm using a view of (ListView, FormView) so I'm not sure how I would add the IP to the form like I normally would by using: instance = form.save(commit=False) instance.ip = get_ip(request) instance.save() -
Django Admin how to add custom form fields (not modal fields) dynamically?
I have two models - Page and PageTemplate. Page has 1-to-1 relationship with PageTemplate. PageTemplate has a fields = JSONField(default={}). An example PageTemplate is the following: name = "Contact Form" slug = "contact-form" fields = { "coords": {"type": "map-field", "title": "Coordinates"} , "address": {type: "text-field", "title": "Address"}, "phone": {"type": "text-field", "title": "Phone"} } Page also has fields = JSONField(default={}). An Example Page looks like the following: title = "Contact Page" template = 1 # ID of contact-form Page Template fields = { "coords": {"lat": 32.23, "lng": 11.11}, "address": "Test address" } I want to display the fields from PageTemplate in a Page Django Admin and populate the fields from an existing Page model's fields. I have created Page Form class and set is as the form for Page Model Admin class: class PageForm(TranslatableModelForm): """ Form for Page """ class Meta: """ Page Form Meta """ model = Page exclude = () My plan is to do the following: Read 1-to-1 relationship model (PageTemplate) from Page Form Convert JSONField to Dictionary if it doesn't do that already Loop through the Dictionary and create fields Somehow add these created fields to Page Model Admin fieldset called "Fields" Question: In what function of β¦ -
Django Atomic Query Allows Reads to Succeed
I'm building a Django / Django Rest Framework accounting app with a MySQL backend that records transactions and modifies an account balance accordingly. I've run into an issue with black-box testing where POSTing a transaction and GETting an account immediately afterwards seems to create a race--it's possible for the client to get the old balance (before the transaction has been charged.) Simplified excerpt from my Models.py: class Account(models.Model): """ An account is a bucket for credits. """ ... # The account balance. balance = models.IntegerField( validators=[MaxValueValidator(10 ** 14)], editable=False, default=0 ) pending = models.IntegerField( validators=[MaxValueValidator(10 ** 14)], editable=False, default=0 ) @transaction.atomic() def save(self, *args, **kwargs): ... class Transaction(models.Model): """ A transaction is a single (+/-) change to the balance of an account. """ summary = models.CharField(max_length=255) product = models.ForeignKey('catalog.Product') quantity = models.PositiveIntegerField() credits = models.IntegerField( editable=False, validators=[MaxValueValidator(10 ** 14)] ) created = models.DateTimeField(auto_now_add=True, editable=False) creator = models.ForeignKey( settings.AUTH_USER_MODEL, editable=False, null=False, related_name='creator', help_text='The user that incurred the charge' ) # Escrow is inferred. Since we assume a task takes some time to complete # and we don't want to charge for work we didn't do, we wait to set # `charged` until after the job is completed. charged = models.DateTimeField(blank=True, null=True) β¦ -
django- latex template rendering only one page
i'm a relatively new to python/django, and i'm making a small app to generate medical reports. I have two models Patient and consultation related by OneToMany relationship, so i made a view called consultation_pdf which has these models in the Context : def consultation_pdf(request, pk2, pk1): entry = Consultation.objects.get(pk=pk2) source = Patient.objects.get(pk=pk1) context = Context({ 'consultation': entry, 'patient': source }) template = get_template('app/consultation.tex') rendered_tpl = template.render(context, request).encode('utf-8') # Python3 only. For python2 check out the docs! with tempfile.TemporaryDirectory() as tempdir: # Create subprocess, supress output with PIPE and # run latex twice to generate the TOC properly. # Finally read the generated pdf. for i in range(2): process = Popen( ['xelatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) return r the problem is that the PDF file produced shows only the first page , and i'd appreciate any help from you guys. Thanks in advance! -
Django auto complete light outside admin - not working
I trying to set up the django auto complete light outside the admin views. I am follow this tutorial but I havent got any luck in figure out whats is wrong: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#using-autocompletes-outside-the-admin Models.py class TvShowModel(models.Model): tvs_id = models.IntegerField(primary_key=True) tvs_name = models.CharField(max_length=100) tvs_name_br = models.CharField(max_length=100, blank=True,default="") tvs_genre = models.CharField(max_length=100, blank=True,default="", null=True) tvs_language = models.CharField(max_length=100, blank=True,default="", null=True) tvs_status = models.CharField(max_length=100, null=True) tvs_runtime = models.FloatField(blank=True,default="", null=True) tvs_schedule = models.CharField(max_length=100, blank=True,default="", null=True) tvs_rating = models.CharField(max_length=100, blank=True,default="", null=True) tvs_timezone = models.CharField(max_length=100, blank=True,default="", null=True) tvs_imdb_id = models.CharField(max_length=100, null=True, blank=True,default="") tvs_img_m_url = models.CharField(max_length=100, null=True, blank=True,default="") tvs_summary = models.TextField(max_length=100, null=True, blank=True,default="") tvs_summary_br = models.TextField(max_length=100, null=True, blank=True,default="") tvs_likes = models.FloatField() def __str__(self): return self.tvs_name views.py class TvAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): #if not self.request.user.is_authenticated(): # return Doctor.objects.none() qs = TvShowModel.objects.all() if self.q: qs = qs.filter(name__icontains=self.q) return qs class TvShowForm(autocomplete.FutureModelForm): class Meta: model = TvShowModel fields = ('tvs_name',) widgets = { 'TvShowModel': autocomplete.ModelSelect2(url='select2_outside_admin') } class sss(UpdateView): model = TvShowModel form_class = TvShowForm template_name = 'webapp/select2_outside_admin.html' success_url = reverse_lazy('select2_outside_admin') def get_object(self): return TvShowModel.objects.first() Forms.py class TvShowForm(autocomplete.FutureModelForm): class Meta: model = TvShowModel fields = ('tvs_name',) widgets = { 'tvshow': autocomplete.ModelSelect2(url='select2_outside_admin', attrs={ 'data-html' : 'true' })} #Tried this way also: #widgets = { #'TvShowModel': autocomplete.ModelSelect2(url='select2_outside_admin') #} urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^showlist', views.showlist, β¦ -
Django Exception : AppRegistryNotReady("Models aren't loaded yet.")
I found a lot of content on the AppRegistryNotReady Exception, but none of them seem defenitive. I just wanted my 2 cents of info on the topic. My django project was working fine. I created a new app, and created the following model. No view, no urls nothing. Just a model. from __future__ import unicode_literals from django.db import models # Create your models here. from django.conf import settings from django.core.exceptions import ValidationError from django.contrib.auth import get_user_model User = get_user_model() class File(models.Model): path = models.TextField() #The path does not include MEDIA_ROOT, obviously filename = models.CharField(max_length=500) # file = models.FileField(upload_to=upload_to) file = models.FileField(upload_to=path+filename) user = models.ForeignKey(settings.AUTH_USER_MODEL, models.PROTECT) #Protects User from being deleted when there are files left def clean(self): #Check if path has a trailing '/' if self.path[-1]!='/': self.path = self.path+"/" if self.filename[0]=='/': self.filename = self.filename[1:] #Get the full path username = self.user.__dict__[User.USERNAME_FIELD] #Need to do this the roundabout way to make sure that this works with CUSTOM USER MODELS. Else, we could have simply went for self.user.username self.path = "tau/"+username+"/"+self.path def save(self, *args, **kwargs): self.full_clean() return super(File, self).save(*args, **kwargs) def __str__(self): if path[-1]=='/': text = "\n"+str(path)+str(filename) else: text = "\n"+str(path)+"/"+str(filename) return text Then I tried to makemigrations on the model. And β¦ -
django reasonable use with generic templates
Generic templates and other built in features in Django I feel are great, but I worry using these features too much to "have to code less" is a problem. I for one refuse to use generic templates as they take too much of the responsibility away from you as the developer to know what you are doing. What are your thoughts? Am I wrong to think this way? -
Django restframework send post data is broken from test APIClient
request.data.get('answers_ids') returned str '2' instead of array ['1', '2'] when send from APIClient data But when i send data from rest framework web-gui all works. :( django==1.10.4 djangorestframework==3.5.3 tests.py class ApiCompletePoll(APITestCase): def setUp(self): self.user = User.objects.create( username='123', password='123', email='123@123.ru' ) self.client = APIClient() self.client.credentials( HTTP_AUTHORIZATION='Token ' + self.user.auth_token.key ) def test_complete_poll(self): data = {'poll_id': 1, 'answers_ids': [1, 2]} # SENDED DATA self.client.post(reverse('complete-poll'), data) self.assertTrue( CompletedPoll.objects.filter( user=self.user, poll__id=data['poll_id'] ) ) views.py @api_view(http_method_names=['post', ]) def update_or_create_user_answers(request): user = request.user poll_id = request.data.get('poll_id', 0) answers_ids = request.data.get('answers_ids', []) print(list(request.data.items()), request.data, answers_ids) # GETTING DATA OUTPUT: [('answers_ids', '2'), ('poll_id', '1')] <QueryDict: {'answers_ids': ['1', '2'], 'poll_id': ['1']}> 2 -
Detail/Edit Form For Class-Based Views in Django
I am trying to build a basic Details form for one of the Django Models. However, when I click on an entry, all it gives me is just an empty form. What am I missing? What's more, is there a better way to create basic Detail/Edit forms for existing models? View code: class ProjectView(generic.FormView): model = Project form_class = ProjectForm initial = {'key': 'value'} template_name = 'steps/project-detail.html' def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): # <process form cleaned data> return HttpResponseRedirect('/success/') return render(request, self.template_name, {'form': form}) Form: from django.forms import ModelForm from .models import Project class ProjectForm(ModelForm): class Meta: model=Project fields = ['project_title','project_description'] Template: {% load staticfiles %} <link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet" media="screen"> <h1>Project:</h1> <h1>{{ project.project_title }}</h1> {{ form }} -
Django unable to show webpage
Trying to use Django 1.10 to create a file upload system (simular to this example here , my main problem is no matter how hard i try Django is unable to show my webpage (404 error) I have no idea why im following the 1.9 example and it should be working as far as i can tell. I've attached the error and my data tree [D:. β db.sqlite3 β manage.py β ββββ.idea β courseworkupload.iml β misc.xml β modules.xml β workspace.xml β ββββcourseworkupload β β settings.py β β urls.py β β wsgi.py β β __init__.py β β β ββββ__pycache__ β settings.cpython-35.pyc β urls.cpython-35.pyc β wsgi.cpython-35.pyc β __init__.cpython-35.pyc β ββββupload β β admin.py β β apps.py β β forms.py β β models.py β β tests.py β β urls.py β β views.py β β __init__.py β β β ββββmigrations β β β 0001_initial.py β β β __init__.py β β β β β ββββ__pycache__ β β 0001_initial.cpython-35.pyc β β __init__.cpython-35.pyc β β β ββββtemplates β β Final.html β β upload.html β β β ββββuploadedfiles β ββββ__pycache__ β admin.cpython-35.pyc β forms.cpython-35.pyc β models.cpython-35.pyc β urls.cpython-35.pyc β views.cpython-35.pyc β __init__.cpython-35.pyc β ββββUploadedfiles ββββ__pycache__ manage.cpython-35.pyc][2] -
Django: How to create a simple view to display current object of a model?
models.py: class User(models.Model): sex_choices=(('M', 'Male'), ('F', 'Female')) category_choices=(('S', 'Student'),('T', 'Teacher'),('G', 'Guardian')) qual_choices = (('a', 'Secondary'),('b', 'Senior Secondary'),('c', 'Undergraduate'),('d', 'Postgraduate')) area_choices = (('CS', 'Computer Science'),('Maths', 'Mathematics'),('Phy', 'Physics'),('Chem','Chemistry'),('Bio', 'Biology')) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) age = models.PositiveSmallIntegerField() sex = models.CharField(max_length=1, choices=sex_choices) contact = models.CharField(max_length=10) email = models.EmailField(unique=True) category = models.CharField(max_length=1, choices=category_choices) qualification = models.CharField(max_length=1, choices=qual_choices) area = models.CharField(max_length=5, choices=area_choices, null=True) current_institution = models.CharField(max_length=30) about = models.TextField(null=True) password = models.CharField(max_length=20) views.py: class UserDetailView(DetailView): model = User def get_context_data(self, **kwargs): context = super(UserDetailView, self).get_context_data(**kwargs) return context urls.py: urlpatterns = [ url(r'^profile/(?P<slug>[-\w]+)/$', views.UserDetailView.as_view(), name='profile')] templates/profile.html: <font size="6" color="white">Name: {{object.first_name}} {{object.last_name}}</font> I simply want to display the details of the current user i.e. display the fields of an object of class User. I can't figure out how to create a view for the same. Please help. -
Best approach DB-Schema for hierarchical data without duplicates Django
For a project, I'm trying to create a DB of associative words. So my user gets a word, and writes the first 5 words he associates with it. The system chooses one from those 5, and the user chooses another 5 for that one, etc. The ultimate goal here is irrelevant for the question. Now, a Hierarchical DB usually means a FK (and I can use Django-mptt for extra easiness). But here's the catch - i'd like to avoid duplicated data. Say I have a word "x", which brands words "a-e", then "b" branches into "a" & "f-i". Visually, something like this: As you can see, the word "a" repeats twice. That's a likely scenario considering the basic setup (if you're going by association, words are bound to repeat). The way I see it: I can use an FK to preserve hierarchy, then work a little harder to deal with duplications (I'm not expecting a huge DB anyway, so optimization is not going to be an issue). It'll be easier to implament with django-mptt as well. However. since the relationship of the table is to itself, I'm also losing the column's ability to be unique. I can use a M2M, β¦ -
Get_Next_by_Date() gives back the name of the Post instead of it's url
I have a blog like application where I am trying to implement a NEXT button for each post of the Blog. I am currently using Detail_View to display each individual post. In the template, I am using {{post.get_next_by_date}} but instead of the link to the next post, what I am having displayed is the name of the next post. suggestions on how to solve the issue? Best regards. -
django-rest-auth logout failure
I am using django-rest-auth for authentication. Login and Registration is working fine, however logout method gives me an error. I had used this same library in previous projects but never faced this issue, so I am not sure if anything has changed since then. It asks me to fill in some data, which was not the case before. My settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'allauth', 'allauth.account', 'rest_auth.registration', 'corsheaders', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'optional' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' -
Django unused variables
What to do with unused variables in Django (I speak mostly about class based views)? def post(self, request, *args, **kwargs): # request, args, kwargs are not used in this post method .. return .. Is it safe to del them ? In here I also see, that *_ can be used for things I don't care. Why? For the sake of cleaning the code and avoiding IDE warnings. I can safely del *args and **kwargs, but how about request? request I can acces it later using self.request, when using a class based view - actually I do that, but can I be sure that I will have no problem? I see here that django request is immutable, but no in all cases. -
Django override ASCIIUsernameValidator
Using Django 1.10 I'd like to allow the \ character in a username because I'm working in a Windows environment utilizing 'django.contrib.auth.middleware.RemoteUserMiddleware', and the remote user comes in as domain\username (I have no desire to drop the domain as it is used in some business logic). I can change django\contrib\auth\validators.py easily enough and have the desired affect by amending the line regex = r'^[\w.@+-]+$' to be regex = r'^[\w.@+-\\]+$' however, I thought one could override this class easily but I failed. I've found some useful links (and many other similar here on SO): http://stackoverflow.com/a/39820162/4872140 http://stackoverflow.com/a/1214660/4872140 https://docs.djangoproject.com/en/1.10/releases/1.10/#official-support-for-unicode-usernames https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#django.contrib.auth.models.User.username_validator But the info is dated, or doesn't quite show exactly/completely how to solve my issue (in the case of the last two). I'm well into the app so changing the AUTH_USER_MODEL is not attractive. settings.py: AUTH_USER_MODEL = 'myapp.MyUser' I tried anyway, thinking I may be able to use proxy on the User model like the following which results in the error "cannot proxy the swapped model 'myapp.DomainUser'": class DomainASCIIUsernameValidator(ASCIIUsernameValidator): regex = r'^[\w.@+-\\]+$' class DomainUser(User): username_validator = DomainASCIIUsernameValidator() class Meta: proxy = True Is there a way to replace the regex in ASCIIUsernameValidator (and UnicodeUsernameValidator) in a way that the User model stays as β¦ -
Django ForeignKey Constraint
I'm having a problem migrating a model change. Does anyone know why I'm getting this? I've removed the model all together and am now trying to recreate it with the customer_id column set up as a foreignkey to the TblCompanies model. Migrations for 'customers': customers/migrations/0004_tblservicerecords.py: - Create model TblServiceRecords (serviceenv) addohm@LevenServer:/var/www/rtservice/servicesite$ ./manage.py migrate customers Operations to perform: Apply all migrations: customers Running migrations: Applying customers.0004_tblservicerecords...Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/mysql/base.py", line 110, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py", line 166, in execute result = self._query(query) File "/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py", line 322, in _query conn.query(q) File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 835, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 1019, in _read_query_result result.read() File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 1302, in read first_packet = self.connection._read_packet() File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 981, in _read_packet packet.check_error() File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 393, in check_error err.raise_mysql_exception(self._data) File "/usr/local/lib/python3.5/dist-packages/pymysql/err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.IntegrityError: (1215, 'Cannot add foreign key constraint') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 294, in β¦ -
django many to many relation
I have two models named Event and EventUser. class EventUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): u = User.objects.get(pk=self.user_id) return u.username class Event(models.Model): EVENT_TYPE_CHOICES = ( (1, 'Food & Beverage'), (2, 'Party'), (3, 'Natural'), (4, 'Historical'), (5, 'Educational'), (6, 'Sportive'), ) name = models.CharField(max_length=50) event_type = models.IntegerField(choices=EVENT_TYPE_CHOICES) date_time = models.DateTimeField() location = models.CharField(max_length=255) creator = models.ManyToManyField(User, related_name='event_creator') info = models.CharField(max_length=255, default='') users = models.ManyToManyField(EventUser, blank=True) def __str__(self): return self.name So, naturally ManyToManyField is creating new table using event_id and eventuser_id however, I want to use the username instead of eventuser_id. Or, it can stay like that if I can receive usernames instead of id's when I requested it. What I'm trying to tell is that; When I got users field I want to see usernames on response instead of ids like the above image. -
How to retrieve a cookie in Django/Wagtail to set Python variable
I am building a website that will have some different content depending on what province a user is coming from. I have set up a modal window using jQuery/Bootstrap to pop up when the user lands on the site if there is no cookie set: <script type="text/javascript"> $(document).ready(function() { if (Cookies.get('province') == null) { $('#provinceModal').modal('show'); } $('button#ontario').click(function() { Cookies.set('province', 'ontario'); $('#provinceModal').modal('hide'); }); $('button#alberta').click(function() { Cookies.set('province', 'alberta'); $('#provinceModal').modal('hide'); }); $('button#quebec').click(function() { Cookies.set('province', 'quebec'); $('#provinceModal').modal('hide'); }); }); </script> The cookies are being set correctly, as I can see them in the browser after one of the buttons is clicked. The problem I'm having is with retrieving the cookie using Python. I want to save the province variable and then display certain content using if statements (depending on what the province is equal to). I've tried this and I keep getting the error message: import Cookie import os try: cookies = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"]) print cookies["province"].value except (Cookie.CookieError, KeyError): print "ERROR! Cookie not set!" It doesn't seem to be grabbing any of the cookies saved in the browser. I want to grab that value and then save it into a variable to use in my templates for displaying the province-specific content. Any ideas? What am β¦ -
django rest framework pagination
I'm pretty new to Django, and am trying to make use of view sets and pagination. I've got the following classes, as per the documentation: class StandardResultsSetPagination(PageNumberPagination): page_size = 5 page_size_query_param = 'ps' max_page_size = 1000 class SequenceViewSet(viewsets.ModelViewSet): serializer_class = SequenceSerializer queryset = Sequence.objects.all() pagination_class = StandardResultsSetPagination Routing is set up so that /sequences routes to the view set, and that all works great. Furthermore either of these works great: /sequences?page=4 /sequences?ps=3 However, combining the two parameters seems not to work. If I do, the ps parameter is ignored. I have scoured the web for a bug report or indication of what I might be doing incorrectly to no avail. Does anyone know if I'm missing something crucial? Am I supposed to be able to specify both the page size and the page simultaneously? For reference I'm using Django 1.10.3, and DRF 3.5.3. Thanks for any help or insight you can provide! -
Why does the Django Behave test runner say "ignoring label with dot" when I run a single unit test?
I have Behave acceptance tests and unittest/django.test unit tests. I have TEST_RUNNER = 'django_behave.runner.DjangoBehaveTestSuiteRunner' in settings.py. I have multiple files of unit tests: myapp/tests __init.py__ # empty tests_a.py tests_b.py I want to run one file of unit tests. (Not one feature; I know how to do that.) When I do python manage.py test myapp.tests.tests_a I get Ignoring label with dot in: myapp.tests.tests_a and then tests_a.py runs. Great! Only the tests I wanted to run ran. But what is the test runner talking about ignoring? I haven't found another invocation that runs the tests I want but doesn't emit the warning. What's going on here? Django 1.10.2, django-behave 0.1.5. -
Django new database setup
I messed something up with my autogenerated database by Django. So, I deleted the databse, migrations folders and pycache wherever I could find it and made a new datasource (using pycharm), changed the path to this database (settings.py) but still I am getting django.db.utils.OperationalError: no such table: <table_name>. How can I fix this? -
Django Ajax-Select - having selected value appear in text box, not on-deck area
For the excellent library https://github.com/crucialfelix/django-ajax-selects I've implemented the ajax-selects library and it works great - except I'm unable to figure out how to have the selected value (I only need a single-select value) to stay in the text box (which is pretty common for auto-complete solutions), not move into the "on-deck" area below. I've created separate template files as the docs suggest, and even split the javascript into a custom file to allow it to be overridden - but to no avail. Are there any examples out there that have the value stay bound to the type-in box? Thanks! Peter -
How to use select_related() for INNER JOIN in Django?
I want to write following INNER JOIN SQL query using Django select_related(). I have checked the QuerySet manual from the Django website but have not got the solution for my case yet. SELECT * FROM B as b INNER JOIN Q as q on q.id = b.temp_id WHERE b.perm_id='9a26b3e5-1892-439b-b392-1779a043ca1a'; I am using PostgreSQL. Hoping to get some expert advise about converting the SQL in Django way. Thanks in advance!