Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.11 CreateView pass URL parameters
I am using Django 1.11 and I'm struggling to understand how I can pass URL parameters to a ModelForm using CreateView Class. I have 4 parameters in the URL (start_date, end_date, start_time, end_time) that i'm trying to pass to their relevant fields in the form. I'd really appreciate if anyone can point me in the right direction to figuring out how to solve this! The URL is created with the following function in my html file: window.location.assign("/calendar/create?start_date="+start.format("YYYY-MM-DD")+"&end_date="+end.format("YYYY-MM-DD")+"start_time="+start.format("h:mm A")+"&end_time="+end.format("h:mm A")); This opens from urls.py: url(r'^calendar/create',views.CalendarCreate.as_view(),name='calendar_create'), from views.py: class CalendarCreate(CreateView): model = Event form_class = EventForm from forms.py: class EventForm(ModelForm): class Meta: model = Event So far so good, my event_form.html opens with the form: form and an example URL generated is: http://127.0.0.1:8000/calendar/create?start_date=2017-10-25&end_date=2017-10-25start_time=4:00%20PM&end_time=5:00%20PM This is where I am stuck. From spending a number of days here in stackoverflow, googling, and trying numerous things I believe the solution involves get_form_kwargs or get_context_data or form_valid in views.py but it is possible I have just confused myself trying to work this out. Any help to get me on the right track will be greatly appreciated! -
Why isn't my javascript calculator working with the base.html?
So awhile ago I made a javascript calculator and now I'm re-using it in another project. The problem is, it doesn't even show up on the page anymore. This is the code for the calc.html file. {% extends 'base.html' %} {% block body %} <div class="text-center"> <h1>Calculator</h1> </div> <div id="JSCalc"> <form name="calculator"> <input type="text" name="answer"/> <br /> <input type="button" value=" 7" onclick="calculator.answer.value += '7'"/> <input type="button" value=" 8" onclick="calculator.answer.value += '8'"/> <input type="button" value=" 9" onclick="calculator.answer.value += '9'"/> <input type="button" value=" *" onclick="calculator.answer.value += '*'"/> <br /> <input type="button" value=" 4" onclick="calculator.answer.value += '4'"/> <input type="button" value=" 5" onclick="calculator.answer.value += '5'"/> <input type="button" value=" 6" onclick="calculator.answer.value += '6'"/> <input type="button" value=" -" onclick="calculator.answer.value += '-'"/> <br /> <input type="button" value=" 1" onclick="calculator.answer.value += '1'"/> <input type="button" value=" 2" onclick="calculator.answer.value += '2'"/> <input type="button" value=" 3" onclick="calculator.answer.value += '3'"/> <input type="button" value=" +" onclick="calculator.answer.value += '+'"/> <br /> <input type="button" value=" 0" onclick="calculator.answer.value += '0'"/> <input type="button" value=" C" onclick="calculator.answer.value = ''"/> <input type="button" value=" =" onclick="calculator.answer.value = eval(calculator.answer.value)"/> <input type="button" value=" /" onclick="calculator.answer.value += '/'"/> <br /> </form> </div> {% endblock %} And this is the base.html file it's extending from. Note that this wasn't written by me, I'm just … -
What is the proper way to login via email for custom user model?
I don't need to let users login using usernames, only email. So I have custom user model: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField('email address', unique=True) accepted = models.BooleanField('status', default=False) is_staff = models.BooleanField( 'staff status', default=False, help_text='Designates whether the user can log into this site.', ) is_active = models.BooleanField( 'active', default=True, help_text='Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.', ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = MyUserManager() class Meta: verbose_name = 'user' verbose_name_plural = 'users' def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email Custom manager: class MyUserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) And I am using auth_views.login method to render login template. In template I have two input fields named email and password. But when I submit form I got a validation error that says the username field is required. I figured … -
Django SelectDateWidget inline select (bootstrap?)
I'm using SelectDateWidget in a form in django for a birthday field. It display three selects for day, month and year. The problem is they don't display inline, but stacked vertically. I'm using a tag for each field, in this case {{ form.birthdate }} How do I display them inline? Thanks in advace. -
How to deploy django in a2hosting
I am trying to set up my django application in a2hosting, I was doing some research and It seems that i need to use wsgi but I am not able to do it. My questions are the following: Where do i need to put all my files, should be stay in the www folder? When I run the server "manage.py runserver" in order to access to the site do i need to use www.domain.com:port? Can someone give any idea to deploy, i am loosing my mind trying to deploy my site. Thanks in advance. -
Summary of data for different users using Serializer in Django
In our app, we have a back-end that runs on the Django Rest Framework. Up to this point what we have been doing is gather data for specific users, which is easy to implement using serializers. @api_view(['GET']) def user_stats(request, format=None): if request.method == 'GET': serializer = StatsSerializer(request.user, context={'request': request}) return Response(serializer.data) In this case, the StatsSerializer is a custom serializers which returns JSON like this: { "id": 2, "first_name": "John", "last_name": "Legend", "profile_photo": "http://localhost:8000/media/profile_photos/john_legend.jpg", "notification_count": 3 } The serializer contains a SerializerMethodField for handling notification_count: def get_notifications(self, obj): return obj.notifications.filter(status=Notification.UNREAD).count() The serializer's model is a simple User Model in this case (request.user). And this goes on for all our end-points (although with different models). However, for a different endpoint we would like to give an overview of data for a list of users and receive a response like this. { "notification_count" : 48, "todo_count" : 72 ... and some more } I think I can get this data in the View with filter and aggregate. However, that is just for one user and thus can I use a User model as the model for the serializer. I would like to do this for a list of users. notificationCount = Notification.objects.filter(user=request.user). … -
access /admin functionality and features for some user groups
My english is not perfect thus the title is confusing. I don't know how to really put what i want to say. Anyway, I have a django 1.11 application that is running well. Wrote admin.py for some apps and a bunch of admin forms overridden. But client said he wants a different way of doing things (instead of admin carrying out the task, everyone registered on the app can). I already have a dashboard for those users and he wants the admin forms to be in that dashboard as opposed to the /admin default dashboard. I failed to find such a thing in the documentation, I think. But basically, I want some forms to be avalibale, as they are, in the client dashboard? Is that possible? -
django-ouath-toolkit with social-auth
I'm trying to setup social-auth (python-social-auth) to talk to another Django project with django-oauth-toolkit. I want Django project A to login using OAuth2 from Django project B. Django project A uses social-auth and project B uses django-oauth-toolkit as the OAuth2 provider. Project A can successfully login to other OAuth2 providers such as Google, but I get the following error when trying to login using my custom made backend: AuthStateMissing at /sso/complete/custom-backend/ Session value state missing. This is how the custom backend has been implemented in Project A: class CustomBackend(BaseOAuth2): name = 'custom-backend' EXTRA_DATA = [ ('profile', 'org') ] def authorization_url(self): return "%s/oauth2/authorize" % self.setting("URL") def access_token_url(self): return "%s/oauth2/token" % self.setting("URL") def user_data(self, access_token, *args, **kwargs): resp = requests.get("%s/me/" % self.setting("URL"), headers={ 'Authorization': "Bearer %s" % access_token }) if resp.status_code != 200: raise Exception("Error while getting user details from auth source.") data = resp.json() return { 'username': data['email'], 'first_name': data['first_name'], 'last_name': data['last_name'], 'user_id': data['id'], 'email': data['email'] } There is a setting called SOCIAL_AUTH_CUSTOM_BACKEND_URL which is equal to the base URL of project B (http://localhost:8001 for testing). The URL when Project B redirects to Project A (when the error is raised) is: http://localhost:8000/sso/complete/custom-backend/?redirect_state=6kg4S1eitCMqTTzFGrm9uerG37UNkUPl&code=e64by72AkD2unMVVsGZCz0V2byuUyu&state=6kg4S1eitCMqTTzFGrm9uerG37UNkUPl I thought the issue might be because django-oauth-toolkit doesn't … -
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?