Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django user model relationship to a foreign key
I have my default user model using ldap authentication. The unique field that is populated when a user logins with his network username/password is username. How can I associate the following model's field Employee_NTName with the username in my Users model. The class AllEeActive is an existing table, which is not to be modified. class AllEeActive(models.Model): employee_last_name = models.CharField(db_column='Employee_Last_Name', max_length=50, blank=True, null=True) # Field name made lowercase. employee_first_name = models.CharField(db_column='Employee_First_Name', max_length=50, blank=True, null=True) # Field name made lowercase. employee_ntname = models.CharField(db_column='Employee_NTName',primary_key=True, serialize=False, max_length=50) # Field name made lowercase. -
Django Query: Group by field and get the latest entry per group
I have the following table in Django-1.11: class Market(models.Model): slug = models.SlugField(...) active = models.DateTimeField(...) It would be great if the slug was a foreign key to avoid duplicate values but this is not the case, I am coping with a third party app. data = [ {'id': 1, 'slug': 'test-1', 'active': 'datetime.datetime(2017, 9, 18, 10, 43, 8, 581046, tzinfo=<UTC>)'}, {'id': 2, 'slug': 'test-1', 'active': 'datetime.datetime(2017, 9, 20, 10, 43, 8, 581046, tzinfo=<UTC>)'}, {'id': 3, 'slug': 'test-2', 'active': 'datetime.datetime(2017, 9, 10, 10, 43, 8, 581046, tzinfo=<UTC>)'}, {'id': 4, 'slug': 'test-2', 'active': 'datetime.datetime(2017, 9, 19, 10, 43, 8, 581046, tzinfo=<UTC>)'}, ] I am looking for a query which will return the latest entry with slug test-1 and the latest entry with slug test-2. Using annotate I just receive the results with their datetime: Market.objects.values('slug').annotate(Max('active')) Out[11]: <QuerySet [{'active__max': datetime.datetime(2017, 9, 18, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-1'}, {'active__max': datetime.datetime(2017, 9, 20, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-1'}, {'active__max': datetime.datetime(2017, 9, 10, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-2'}, {'active__max': datetime.datetime(2017, 9, 19, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-2'}]> This result does not seem to follow the docs. What am I doing wrong? Is it the SlugField that does not … -
adding to a many to many relation django
Lets look at the django documentation code for adding members of the bettles. First we have our models: from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): # __unicode__ on Python 2 return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): # __unicode__ on Python 2 return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) now we have the code to add to the many to many relation: # create a person named ringo ringo = Person.objects.create(name="Ringo Starr") # create a group named the beatles (terrible band so boring) beatles = Group.objects.create(name="The Beatles") >>> m1 = Membership(person=ringo, group=beatles, ... date_joined=date(1962, 8, 16), ... invite_reason="Needed a new drummer.") >>> m1.save() >>> beatles.members.all() <QuerySet [<Person: Ringo Starr>]> # what is this doing tho? ringo.group_set.all() <QuerySet [<Group: The Beatles>]> as well do we need to just set the many to many relation like is done in the Group model? class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): # __unicode__ on Python 2 return self.name then go to the table that is holding all the foreign keys for the many to many relation and just add … -
NodeNotFoundError when migrate but can't find the corresponding migration
I am getting this error on migrate. django.db.migrations.exceptions.NodeNotFoundError: Migration basket.0002_auto_20140827_1705 dependencies reference nonexistent parent node (u'partner', u'0001_initial') I have two subapps - one oscar, the other mysub. In mysub migration folder, my migration folder doesn't even have a basket.0002_auto_20140827_1705. In the oscar folder, there isn't a migration folder. What would cause this error? I tried creating a basket folder under oscar to see if there is migration folder popping up, nothing. -
Return extra fields of many-to-many relationship instead of another
My question is based on this example given in the Django documentation. My models.py looks like this: class Wrestler(models.Model): name = CharField(max_length=255) class AlterEgo(models.Model): name = CharField(max_length=255) person = ForeignKey('someapp.Person', ) class Group(models.Model): name = CharField(max_length=255) members = models.ManyToManyField('someapp.Person', through='Membership') class Membership(models.Model): person= models.ForeignKey('someapp.Person',) alter_ego = models.ForeignKey('someapp.AlterEgo', blank=True, null=True) group = models.ForeignKey('someap.Group',) My group list template looks like this: {% for object in object_list %}<tbody> <tr> <td><a href="{{object.get_absolute_url}}">{{ object.name }}</a></td> <td>{{ object.members.all|join:" & " }}</td> </tr> </tbody>{% endfor %} As you can see, my extra field is the "alter_ego" one. Every person can have an alter ego, e. g. Chris Jericho used to perform as Moongoose McQueen. With this template, members would be listed as "Chris Jericho & Richard Ward & ...". My problem is I don't want Jericho to be listed as Jericho but as McQueen if an alter ego is given. I guess there should me a custom function replacing my person FK if an alter ego is given but I'm still trying to wrap my head around it as I'm really a noob regarding all this. If someone could point me in the right direction I'd greatly appreciate it. Thanks in advance. -
Add Image to Part with inline in admin
I'm trying to add an item and at the same time add images to this item under the same form. I have these model classes in my models.py class Part(models.Model): name = models.CharField(max_length=550) class Image(models.Model): image = models.FileField() part = models.ManyToManyField(Part, related_name='image_part') And I tried to do this is in admin.py class PartAdmin(admin.ModelAdmin): inlines = [ ImageInline, ] class ImageInline(admin.TabularInline): model = Image.part.through admin.site.register(Part, PartAdmin) I get the option to choose image. But it's three dropdowns with images already added to other Parts. I have the add sign. When clicking that, I get to upload images, but with option to choose already added Parts. Any idea how to add images to a part when creating a new part? Is it even possible? -
Added another column to a model in Django, how do I update database?
So I changed the names and added a column to a model in django. Before: class MyApp(models.Model): id = models.AutoField(primary_key=True) aaa = models.CharField(max_length=100) bbb = models.CharField(max_length=100) After: class MyApp(models.Model): id = models.AutoField(primary_key=True) first = models.CharField(max_length=100) second = models.CharField(max_length=100) third = models.CharField(max_length=100) I made these changes in the MyApp's view, model, and serializer, however when I try to access my new API endpoint, it fails because the database doesn't contain the new column names. How can I update the database to reflect my new model? (I don't care about any of the data for this model, so I can wipe it). No idea how to do this -
Tornado server caused Django unable to handle concurrent requests
I wrote a Django website that handles concurrent database requests and subprocess calls perfectly fine, if I just run "python manage.py runserver" This is my model class MyModel: ... def foo(self): args = [......] pipe = subprocess.Popen(args, stdout=subproccess.PIPE, stderr=subprocess.PIPE) In my view: def call_foo(request): my_model = MyModel() my_model.foo() However, after I wrap it using Tornado server, it's no longer able to handle concurrent request. When I click my website where it sends async get request to this call_foo() function, it seems like my app is not able to handle other requests. For example, if I open the home page url, it keeps waiting and won't display until the above subprocess call in foo() has finished. If I do not use Tornado, everything works fine. Below is my code to start the tornado server. Is there anything that I did wrong? MAX_WAIT_SECONDS_BEFORE_SHUTDOWN = 5 def sig_handler(sig, frame): logging.warning('Caught signal: %s', sig) tornado.ioloop.IOLoop.instance().add_callback(force_shutdown) def force_shutdown(): logging.info("Stopping tornado server") server.stop() logging.info('Will shutdown in %s seconds ...', MAX_WAIT_SECONDS_BEFORE_SHUTDOWN) io_loop = tornado.ioloop.IOLoop.instance() deadline = time.time() + MAX_WAIT_SECONDS_BEFORE_SHUTDOWN def stop_loop(): now = time.time() if now < deadline and (io_loop._callbacks or io_loop._timeouts): io_loop.add_timeout(now + 1, stop_loop) else: io_loop.stop() logging.info('Force Shutdown') stop_loop() def main(): parse_command_line() logging.info("starting tornado web … -
AWS Lambda flooding RDS MySQL connections during spikes
I have Django running on AWS Lambda connecting to MySQL on RDS. Everything works great most of the time. However, if a spike executes 10000 concurrent requests this spawns many Lambda containers and each opens a database connection which will eventually exceed RDS connection limits. (as per https://serverfault.com/questions/862387/aws-rds-connection-limits) What is the best strategy (if any) to get this to web-ish scale without losing SQL. Some ideas: Is there a way to limit the number of AWS containers to encourage/force re-use rather than spawning more? (e.g. Set max lambda containers as some proportion of db connection limit). If container limit is reached the connection could wait until a hot aws container is available. Can API Gateway detect a spike and delay putting the connections through to Lambda? This would allow most to be fulfilled by re-used hot containers which would not create excessive db connections. I know API Gateway allows throttling but this is very coarse and can't do anything other than drops connections that exceed the limit. Liberal use of MySQL/RDS read-replicas -
Is there any solution for delayed python debugging?
I have floating error on Django server in production, it does not causes exceptions, only some wrong behaviour. But I can't reproduce it on my locale machine; So I need to debug it on server side. Are there any tools, that can log all states of all variables so then I could replay problematic requests and figure out what behaves wrong? -
AttributeError: type object 'BdsStatusStep' has no attribute '_default_manager'
Trying to write some simple unit tests and getting this error, which I'm totally stuck on: Traceback (most recent call last): File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/django.py", line 140, in _get_manager manager = model_class.objects AttributeError: type object 'BdsStatusStep' has no attribute 'objects' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/loc/tnt/leg_apps/etl/transfers/tests/test_action.py", line 37, in setUp self.first_session_bds_step = BdsStatusStepFactory(action_date_1=datetime.date(2000, 1, 3)) File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/base.py", line 67, in __call__ return cls.create(**kwargs) File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/base.py", line 594, in create return cls._generate(True, attrs) File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/base.py", line 519, in _generate obj = cls._prepare(create, **attrs) File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/base.py", line 494, in _prepare return cls._create(model_class, *args, **kwargs) File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/django.py", line 176, in _create manager = cls._get_manager(model_class) File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/django.py", line 144, in _get_manager manager = model_class._default_manager AttributeError: type object 'BdsStatusStep' has no attribute '_default_manager' The line generating the error is a simple instantiation of a BdsStatusStepFactory: self.first_session_bds_step = BdsStatusStepFactory(action_date_1=datetime.date(2000, 1, 3)) which is defined as: class BdsStatusStepFactory(factory.django.DjangoModelFactory): class Meta: model = BdsStatusStep I'm not sure what else I should be looking for. The BdsStatusStep model is quite large and I hesitate to post the whole thing, although I can if it's helpful (or maybe there's something specific I should look for?) Other SO questions about this error seem … -
Calling local api on a server from a hosted website
I'm currently hosting a website and I'm trying to call an API on a remote server. This remote server has a website running locally, and I'm trying to call a certain API from my website to the remote server's localhost. Is something like this possible, or would I have to host the website on the remote server so it isn't locally hosted. For instance, would something like http://IP_address_of_server_goes_here:8000/get_matching_data/?XXXX be possible to get some data from this localhost? -
django.db.migrations.exceptions.NodeNotFoundError: But migration doesn't exists
I am getting this error but my migration folder doesn't even have what it says basket.0002_auto20140827_1705`. The error django.db.migrations.exceptions.NodeNotFoundError: Migration basket.0002_auto20140827_1705 dependencies referene nonexistent parent node (u'partner', u'0001_initial') I do have two subapp - one is oscar, the other is myapp. In myapp, there is migrations folder but nowhere has this basket.0002_auto20140827_1705. I tried looking at oscar's subapp and I don't see any migrations folder anywhere. Where is this error referencing to? -
Django REST: Clear way to serialize two or more levels of nested elements
I have an endpoint, that must return the body, that you can see below: { "item": { "id": 25, "title": "icecream", "description": null, "image_link": null, "measure_units": [ { "id": 67, "unit": { "id": 1, "code": "BX", "title": "Box" }, "quantity": 1000 } ], "created_at": "2017-10-23T11:28:35.534670Z", "updated_at": "2017-10-23T18:28:34.754016Z", "deleted_at": null } } As you can see, I have a separate model mesure_unit, that connects to item with additional Many-to-Many model MeasureItem, where I can define item, measure_unit and set quantity. And as you can see in example body, that makes two level nested objects in measure_units. Below you can see, how I serializing and return all that funny staff. And my question is: is that code optimal? Or I can do something better? Cause I think that my code is not so good as it can be... Serializer: from rest_framework import serializers from .models import Item, MeasureItem from measure_unit.models import MeasureUnit from supplier.models import Supplier class MeasureUnitSerializer(serializers.ModelSerializer): class Meta: model = MeasureUnit fields = ('id', 'code', 'title') class MeasureItemSerializer(serializers.ModelSerializer): class Meta: model = MeasureItem fields = ('id', 'unit', 'quantity') class ItemSerializer(serializers.ModelSerializer): measure_units = MeasureItemSerializer(source='measureitem_set', many=True) supplier = SupplierSerializer() class Meta: model = Item fields = ( 'id', 'title', 'description', 'image_link', 'measure_units', … -
displaying image using django and html
I'm not sure what I'm doing wrong, but my image won't display HTML: {% load static %} <img src="{% static 'images/IMG_0096.JPG' %}" alt="Mountain View"/> settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) Thanks -
Mofidy createView so as to post to two different forms from same template?
I have two models which have common fields, say class model1(models.Model): commonfield1 = ... commonfield2 = ... class model2(models.Model): commonfield1 = ... commonfield2 = ... extrafields=.. .... Now i have two different create forms for these both models using forms.ModelForm. Now, my requirement is that when I create a new object for model2, I also want to save an object in model1. As of now I am using CreateView to save the form for model2. I want to give user an option such that if he presses that save two objects button both the models should be updated accordingly. Is there anyway I can do this using CreateView. -
Calculate due date in django
I am creating a "library" website using django. Once a user has issued a book, I want to calculate a due date for it, 3 months after the issue/present date. How do I do it? -
Django how to see urls.py and settings.py changes without apache restart
I am setting up a django project on an apache server. I have access to the .htaccess and index.fcgi files, but no sudo access. When I make changes to urls.py or settings.py, the changes don´t come through. Is there a way to see changes come through without restarting apache? For example by adding a configuration to the .htaccess file? Here https://stackoverflow.com/a/6282363/5881884 is recommended doing touch on the .wsgi file, but I don´t have any file ending with .wsgi and neither is there a file including the string django.core.handlers.wsgi.WSGIHandler() .htaccess file: AddHandler fcgid-script .fcgi RewriteEngine On RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$ RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$ RewriteRule /static/ /home/myusername/public_html/static RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$ RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$ RewriteRule ^(.*)$ index.fcgi/$1 [L] RewriteCond %{HTTPS} !=on RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$ RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$ RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] -
Migration not working Django, Heroku
I have run locally make migrations and I got my migrations files in my folder. Then I pushed it live to heroku. But heroku didn't apply the changes to my database which is causing now an error. One column does not exist because of the missing migration. Locally everything works fine. I checked via heroku bash if the migration files exist and they do. Then I tried to run manage.py migrate. The output was: No migrations to apply. Also having release: python manage.py migrate in my procfile didn't help either. Any ideas what I can try to do else or why heroku is not migrating? -
how to find result with any word in list in django
I would like to find a list of results that are contained that match any word in a list. For example if company have different inputs it could still find them: company_name = 'awesome blossom' I would like to search for companies with 'awesome' and 'blossom' in the name. I tried something like this: companies = Company.objects.filter(company_name__icontains__in=company_name.split(' ') but this didn't work. How can I accomplish this? -
How to handle a form not tied to a specific URL with a view in Django?
I am creating a job board site and I have the following urls.py (not that important just included them to make the question clearer) : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name = "index"), url(r'^job_info/(?P<job_id>[0-9]+)/$', views.job_info , name = "job_info"), url(r'^employer_signup', views.employer_signup, name="employer_signup"), url(r'^employer_home', views.employer_home, name = "employer_home"), url(r'^login/$', login, {'template_name':'core/employer_login.html'}, name = 'employer_login'), ] I have a base.html that is included in all of the HTML files. This includes a Navbar with an inline search bar: <form class="form-inline my-2 my-lg-0 navbar-toggler-right" method = "post" > {% csrf_token %} <input class="form-control mr-sm-2" type="text" placeholder="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> Is there a way to handle this form with a View? As it is not directly tied to any specific URL? -
Bootstrap Snippet does not look like it has to in Django
Heyho, i'm new to Django and i have a problem including a template to my view. I want to use the following snippet from Bootstrap "https://bootsnipp.com/snippets/Nj4gp", but it just look like on the picture below. I took the same Code and just changed the Content of the table. Can somebody tell me what could be wrong, i checked, that bootstrap is in the right static folder. I do not understand why some parts work and others not.enter image description here Thanks in advance! Magda -
DetailView Shows Same Page Doesnt Return Detail page
models.py from django.db import models class india(models.Model): name = models.CharField(max_length=50) body_1 = models.TextField() body_2 = models.TextField() title_img = models.ImageField(upload_to="images/") img_1 = models.ImageField(upload_to="images/") img_2 = models.ImageField(upload_to="images/") img_3 = models.ImageField(upload_to="images/",blank=True) img_4 = models.ImageField(upload_to="images/",blank=True) Date_of_Publishing = models.DateField() Author = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = "Indians" class Australia(models.Model): name = models.CharField(max_length=50) body_1 = models.TextField() body_2 = models.TextField() title_img = models.ImageField(upload_to="images/") img_1 = models.ImageField(upload_to="images/") img_2 = models.ImageField(upload_to="images/") img_3 = models.ImageField(upload_to="images/",blank=True) img_4 = models.ImageField(upload_to="images/",blank=True) Date_of_Publishing = models.DateField() Author = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = "Australians" class South_Africa(models.Model): name = models.CharField(max_length=50) body_1 = models.TextField() body_2 = models.TextField() title_img = models.ImageField(upload_to="images/") img_1 = models.ImageField(upload_to="images/") img_2 = models.ImageField(upload_to="images/") img_3 = models.ImageField(upload_to="images/",blank=True) img_4 = models.ImageField(upload_to="images/",blank=True) Date_of_Publishing = models.DateField() Author = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = "South_Africans" class England(models.Model): name = models.CharField(max_length=50) body_1 = models.TextField() body_2 = models.TextField() title_img = models.ImageField(upload_to="images/") img_1 = models.ImageField(upload_to="images/") img_2 = models.ImageField(upload_to="images/") img_3 = models.ImageField(upload_to="images/",blank=True) img_4 = models.ImageField(upload_to="images/",blank=True) Date_of_Publishing = models.DateField() Author = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = "England's" views.py from django.shortcuts import render from .models import india,Australia,South_Africa,England def index(request): return render(request, "index.html") def india_v(request): rec_posts1 = india.objects.order_by('-Date_of_Publishing')[0:1] rec_posts2 = india.objects.order_by('-Date_of_Publishing')[1:2] rec_posts3 = india.objects.order_by('-Date_of_Publishing')[2:3] post = india.objects.all() context = {'rec_posts1':rec_posts1,'rec_posts2':rec_posts2,'rec_posts3':rec_posts3,'post':post} … -
One form for all classes in a model
I have a parts app where my model looks like this class Part(models.Model): name = models.CharField(max_length=550) def __str__(self): return self.name class Image(models.Model): image = models.FileField() part = models.ManyToManyField(Part, related_name='image_part') class IDNum(models.Model): IDNum = models.CharField(max_length=50) part = models.ForeignKey('Part', related_name='ID') def __str__(self): return self.IdNum class Stock(models.Model): quantity = models.DecimalField(max_digits=10, decimal_places=2) unit = models.ForeignKey('Unit') part = models.ForeignKey('Part', related_name='stock') stockarea = models.ForeignKey('StockArea') class Warehouse(models.Model): name = models.CharField(max_length=550) address = models.TextField() def __str__(self): return self.name class StockArea(models.Model): area = models.CharField(max_length=550) warehouse = models.ForeignKey('Warehouse') def __str__(self): return '%s %s' % (self.warehouse, self.area) class Unit(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=550) abbreviation = models.CharField(max_length=10) def __str__(self): return self.abbreviation In the admin page I have a form for each class. I really want to add a Part and choose Images, set a IDNum, Choose Warehouse to get list of StockArea's for that Warehouse and set Stock Quantity and choose Abbreviation in one form. Is it possible to create a custom form for the admin pages, so that I can manage this for all classes in a model. They are all related somehow. I would like some tips on how, if it's possible =) -
Django using .get fails on model which uses content types
My .get method is failing. From the django documentation on a model implementing content types / generic foreign key you cannot use: TaggedItem.objects.filter(content_object=guido) # This will also fail >>> TaggedItem.objects.get(content_object=guido) So, do I pass in the content_type and object_id instead? I am using get_object_or_404(TaggedItem, content_type__pk=ct_pk, object_id=pk) and this raises a 404 despite these values beign correct in the database.