Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URL patterns not being read
So I am following a Django tutorial and I have reached the stage where I add my own URL patterns to the urls.py file. from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url((r'^webapp/', include('webapp.urls'))), url(r'^admin/', admin.site.urls), ] the problem is that when I run the server Django doesnt even search for the pattern. I'm not sure what I'm doing wrong here enter image description here -
How can I use ModelChoiceField with Filter in Django 1.11?
I have two models related, I wanna show them with a multiplechoicefield from django.forms but also I wanna that one model had assigned depends on the multiplechoicefield of the related model. class Model(models.Model): name = models....() .... class OtherModel(models.Model): name = models....() model = models.ForeignKey() In my form I have: class ModelAdminForm(forms.ModelForm): model = forms.MultipleChoiceField(queryset = model.objects.all()) other_model = forms.MultipleChoiceField(queryset = other_model.objects.all()) But I wanna do that other_model MultipleChoiceField show me objects only related with model related, how can I do that through queryset filter, or another way to do. -
Django: Context Processor Instantaneous Data Updation
In context_processors.py file I have, def notifs(request): new = Data.objects.filter(user=request.user) if new: new.update(timestamp=timezone.now()) else: Create Data for 'request.user' Everything was fine until this code was in views.py file but since i've added it to the context_processors.py file the "Data" is being updated every single moment in database for 'request.user'. I wants to update the data for every call of this view not for every instant so what should I do? -
factory_boy has no attribute 'objects'
I am trying to write Django Tests. I get this error: .../lib/python3.5/site-packages/factory/django.py", line 118, in _get_manager manager = model_class.objects AttributeError: type object 'MyClassView' has no attribute 'objects' Here is the setUp method (and imports) that fails when trying to set it up for testing. (The code running that generates the error) import django django.setup() from app_name.tests.app_name_factory import MyClassViewFactory from app_name import models class Test_MyClassView(TestCase): def setUp(self): self.MyClassView = MyClassViewFactory() Here is my model: class MyClassView(models.Model): state = models.CharField('State', max_length=2, null=True) division = models.CharField('Division', max_length=2, null=True) name = models.CharField('Name', max_length=40, null=True) choice_objects = MyClassViewManager1() Here is my Factory Class: from factory.django import DjangoModelFactory import factory.fuzzy import factory from app_name import models from faker import Factory as FakerFactory faker = FakerFactory.create() class MyClassViewFactory(DjangoModelFactory): class Meta: model = models.MyClassView state = 'WI' division = 'OP' name = factory.LazyAttribute(lambda x: faker.text(max_nb_chars=40)) My other factories seem to work okay, but MyClassViewFactory does not. I believe it is related to choice_objects = MyClassViewManager1() I've read documentation http://factoryboy.readthedocs.io/en/latest/recipes.html#custom-manager-methods for Custom managers on factory_boy but It only has a single example and I'm unsure if that is even my problem. (Spent several days on this now) Thank you in advance for your assistance. -
django 1.11.6 csrf_token value is null?
settings.py 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', ] myview.py @csrf_protect #ensure_csrf_cookie....etc i tried it. def category(request): context = RequestContext(request) dic = { 'a': 'aaaa', 'b': 'bbb' } return render_to_response('cate.html', dic, context_instance=context) cate.html <form name="cateForm" id="cateForm" method="POST"> {% csrf_token %} <input type="text" name="href" id="href" size="50"> </form> and I html view source then csrf_token value is null. -
Reorder form elements and change labels on django password change form
I'm still relatively new to Django and I've managed to set up a password change form using my template. I don't know how to change the order and labels for the elements. I have attached an image showing how the form currently looks, I would like to move the second text box (new password) underneath the explanation text and to change the first and last input labels. Could you please point me in the right direction? -
Access a model through a link filterd model
I have three models Person, User and Profile. Profile links a person to a user like this: class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE ) person = models.OneToOneField( Person, on_delete=models.CASCADE ) In my person detail view I want to get the username through the person selected. class PersonDetailView(DetailView): model = Person template_name = 'people/person_detail.html' def get_context_data(self, **kwargs): context = super(PersonDetailView, self).get_context_data(**kwargs) profile = Profile.objects.filter(person_id=Person.objects.get(pk=self.kwargs['pk'])) # this line is the problem I guess user = User.objects.get(pk=profile.user.user_id) context['user_person'] = user return context With this code I get the error 'QuerySet' object has no attribute 'user' Maybe it is a silly question but I'm lost on this. How do I get the user from The profile filtered from a person? Thanks in advance, I hope I made mydelf clear enough. -
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]