Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I implement the address form in django? This is what I have
Hello guys I'm trying to figure out how to add multiple addresses to a user. So the user can have shipping addresses and home addresses. I kind of guessed reading around but it's not working. I also created a simple schema: views.py # Profile page @login_required def profile(request): if request.method == 'POST': user_ProfileForm = UserProfileForm(request.POST, instance=request.user) user_BioForm = BioForm(request.POST, instance=request.user.profile) user_HomeAddressForm = HomeAddressForm(request.POST, instance=request.user.HomeAddress) if user_ProfileForm.is_valid() and user_BioForm.is_valid() and user_HomeAddressForm.is_valid(): user_HomeAddressForm.save() user_ProfileForm.save() user_BioForm.save() messages.success(request, f'Your profile has been updated successfully') return HttpResponseRedirect(request.path_info) else: messages.warning(request, f'Please correct the error below.') else: user_ProfileForm = UserProfileForm(instance=request.user) user_BioForm = BioForm(instance=request.user.profile) user_HomeAddressForm = HomeAddressForm(instance=request.Model.HomeAddress) context = { 'user_ProfileForm': user_ProfileForm, 'user_BioForm': user_BioForm } return render(request, 'users/profile.html', context) forms.py class HomeAddressForm(forms.ModelForm): class Meta: model = HomeAddress fields = ['name', 'address', 'city', 'state', 'zipcode', 'country'] def __init__(self, *args, **kwargs): super(HomeAddressForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) #Image feature upload image = models.ImageField(default='default.jpg', upload_to='profile_pics') # If we don't have this, it's going to say profile object only def __str__(self): return f'{self.user.username} Profile' # it's going to print username Profile def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: … -
How can I write to another Google App Engine app?
How can I connect multiple Google App Engine apps to my one Django app engine service so that I can write to another apps datastore? Is this even possible? -
Why can'y pytest-django find manage.py?
I have a project structure like this: setup.cfg integration_tests/ |----tests.py src/ |----manage.py |----my_django_app/ And a setup.cfg with this: [tool:pytest] addopts=--tb=short --strict -ra DJANGO_SETTINGS_MODULE = my_django_app.settings env = APP_ENV=testing USE_SQLITE_DB=True But when I navigate to the top of that directory structure and run pytest, I get the following: "pytest-django could not find a Django project (no manage.py file could be found). You must explicitly add your Django project to the Python path to have it picked up." If I instead navigate to /src/ and run pytest, the tests run without issue, though obviously since I am down a level none of the inegration tests run. According to the documentation, it seems like it should drill down from where you run pytest to attempt to find a manage.py: https://pytest-django.readthedocs.io/en/latest/managing_python_path.html#automatic-looking-for-of-django-projects If that isn't the case, then is there some way to configure a setting in setup.cfg to add src/ to the PYTHONPATH? The suggestion in the doc to install src/ in editable mode using pip isn't really tenable in our environment. -
How do I restrict foreign keys choices in admin formset to related objects only in django
How do I limit choices of a ForeignKeyField of an InlineForm in Django Admin, depended on the selected object in the AdminForm. The problem is that InlineForm does not know anything about the object from the related Admin Form. -
Add menu items to Djanog admin site
I want to do something similar to How to add report section to the Django admin? which explains how to register custom endpoints for the admin site. If I register a URL in this way, how do I add a link to that view? The only way I've found so far is something like this: class CustomAdmin(admin.ModelAdmin): def changelist_view(self, request, extra_context=None): return render(request, 'my_page.html') class ProxyModel(models.MyModel): class Meta: verbose_name = 'Report' verbose_name_plural = 'Report' proxy = True admin.site.register(ProxyModel, CustomAdmin) This seems like a code smell for at least two reasons: I'm overriding changelist_view() to render my own report template which isn't a "change list". It requires a proxy model even if the report doesn't rely on a model or relies on multiple models. Is there a better way to do this? -
Creating links to a page that displays specific rows in my database w/ django?
I created a watered down project based of my more complex project for this question to help deliver my question for effectively. I'll include the code below for future viewers of this post but for ease/convenience here is the gitlab repository url. I have a model "NotesModel" that models the architecture of a note that you might take during the day. It's quite simple there's a 'title', 'tag' and of course the main part which I call the 'content'. The tag is like a tag you link to your stack overflow post. It's just to help identify the topic that a particular note might be about. In my function based view I query every row in my database and hand it off to my render(.., .., {'notes': notes}) function as you'll see below. With some html/bootstrap styling I display every item from the 'tag' column in my database as a label which is linkable with the . {% for note in notes %} <span class="label label-primary" id="tags"> <a id="theurl" href="this is where my confusion is"> {{note.tag}} </a> </span> {% endfor %} I entered some basic notes already and taken a screen-shot to help show you what my page looks like … -
Django app on uWSGI/Nginx not redirecting after POST when using cache2
I have a mature Django app that uses Nginx proxy and a uWSGI backend. I'm trying to migrate uWSGI to use the cache2 directive, and the cache seems to be causing any forms that redirect after successful POST to not redirect - only to reload the same page. When I disable the cache (or use the Django dev server), the POST is successful and redirection occurs. I can't imagine this is the envisioned behavior for cache2 - having to exclude any pages with a POST from the cache - so I must have a mis-configuration somewhere. This same code (except for the cache2 ini directive) worked successfully with the old-style cache. Also, I can see from uwsgicachetop that the question page is successfully being retrieved from the cache, so the cache itself is working. Is there some other configuration that should be added for a POST to work successfully? Configuration: Django 1.9.13 on Python 3 django-uwsgi-cache 1.0.1 Relevant Nginx config: include uwsgi_params; uwsgi_pass unix:///opt/survey.sock; The uWSGI ini: master = true processes = 4 no-site = true vhost = true enable-threads = true vacuum = true die-on-term = true reload-mercy = 8 harakiri = 30 max-requests = 5000 procname-prefix = mysite_ … -
Django nested query for loop
I want to display a list of reviews and each review's rating on a Reviews page. My current logic is, and please correct me if this isn't the best approach, to get all of the reviews (variable reviews) and then place that query into a second query called ratings, to get the average for the values requested. Here is some info. models.py class Review(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() value1 = models.CharField(max_length=1) value2 = models.CharField(max_length=1) value3 = models.CharField(max_length=1) value4 = models.CharField(max_length=1) view.py def reviews(request): ratings=[] reviews = Employee.objects.all() for review in reviews: ratings = Employee.objects.filter(id=review.id).aggregate(rate=Avg(F('culture')+F('location')+F('salary_satis')+F('work_env')+F('communication')+F('opportunity')+F('leadership_satis')+F('fair_treatment'))/8) context = { 'reviews': reviews, 'ratings': ratings } return render(request, 'reviews/reviews.html', context) reviews.html {% extends "reviews/layout.html" %} {% block content %} {% for review in reviews %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ review.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <h4 class="mr-2">{{ review.company }} {{ ratings.rate }}</h4> <small class="text-muted">{{ review.date_posted|date:"F d, Y" }}</small> </div> <h5><a class="article-title" href="{% url 'review-detail' review.id %}">{{ review.title }}</a></h5> <p class="article-content">{{ review.content }}</p> </div> </article> {% endfor %} {% endblock content %} So far each review has the same rating result next to the company name. It isn't showing each rating respective to the review. What … -
CSS Grid auto-flow: dense; with data that is dynamically being loaded with Django
I have a Django web app that is dynamically generating columns with a varied number of items within each column. I'm trying to get CSS' grid-auto-flow: dense; to fill in the gaps, but I can't get it to work. Here is the HTML structure: <div class="container" id="app"> <div class="header">header</div> <div class="columns"> {% for color, cards in cards_dict.items %} <div class="column"> <h1>{{ color }}</h1> {% for card in cards %} <div class="card"> {% if card in card_filter.qs %} <p>{{ card.rating }}</p>{{ card.name }} {% endif %} </div> {% endfor %} </div> {% endfor %} </div> <div class="footer">footer</div> </div> Here is the CSS code I have so far: .container { display: grid; grid-gap: 20px; grid-template-rows: 50px 1fr 100px; grid-template-columns: 1fr; } .columns { display: grid; background: mistyrose; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); grid-auto-rows: minmax(150px, auto); } .column { } .card { font-size: 16px; border: 5px solid rgba(0, 0, 0, 0.03); } Here is what this currently generates: I'd like it for the columns to be right up to one another, with little/no space between. For example, in the image above, I'd like the Azorius column to be right beneath the 4.0 Tatyova, Benthic Druid card. -
Keeping a homegrown Django CMS off public domain?
I am new to Django and Google App Engine. I jumped into an existing project that uses Djangae to build a Django app as a CMS that's running on Google App Engine. The data is stored in Datastore and image uploads are stored in cloud storage. How can I keep the CMS off public domain (behind a secure firewall) while keeping it accessible to the frontend/webserver/main site? -
simple models template Access via Foreign key? What did i miss?
i am testing different views and models in django 2.1.5. I made two simple models and a simple view function to Access Albums by Artist in my template. So far i only see the last names of my artists. i tried to Access the Album model via {% for album in object_list.album_set.all %} but nothing happens, i guess i miss something. i searched online to help myself but most tutorials are only show django examples in pyhton shell. Someone mention also to give the Model with the FKey a related_name, so i named it after a datafield. every hint welcome, thanks models.py class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) person_pic = models.ImageField(upload_to='artist/', max_length=255, null=True, blank=True ) class Album(models.Model): albumname = models.CharField(max_length=255) artistkey = models.ForeignKey(Person, on_delete=models.CASCADE, null=True, related_name="albumname") views.py def artist_page(request): object_list = Person.objects.all() context = {'object_list': object_list} return render(request, 'aquaman/aquaforkey.html', context) aquaforkey.html {% block content %} <h1>HELLO</h1> {% for artist in object_list %} <h1> {{ artist.last_name }}</h1> {% for album in object_list.album_set.all %} {{ album.albumname }} {% endfor %} {% endfor %} {% endblock %} -
How to define object-level permissions for foreign-key relationships
I'm having trouble defining object-level permissions for foreign-key relationships in my ModelViewSet. I'm not sure if it's entirely possible what I'm trying to do or if there's a better solution, but any hint in the right direction would be much appreciated. I've shortened the models and serializers for the sake of brevity. I have the following models: class Team(models.Model): name = models.CharField(max_length=50) class CustomUser(AbstractUser): teams = models.ManyToManyField(Team) class Client(models.Model): name = models.CharField(max_length=50) owner = models.ForeignKey(Team, on_delete=models.CASCADE) class FinancialAccount(models.Model): account_name = models.CharField(max_length=50) client = models.ForeignKey(Client, on_delete=models.CASCADE) Then I have the following serializers: class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = ('name', 'owner') class FinancialAccountSerializer(serializers.ModelSerializer): owner = serializers.SerializerMethodField() class Meta: model = FinancialAccount fields = ('name', 'client', 'owner') def get_owner(self, obj): return client.owner.name Then I'm trying to define a permission that I can use in all of my ModelViewSets. I'd like it to be somewhat dynamic as I have many more models than the ones above that are related to Client or even below FinancialAccount. The permission and viewset are as follows: class IsOwnerTeam(permissions.BasePermission): def has_object_permission(self, request, view, obj): teams = request.user.teams.values_list('name', flat=True) return obj.owner in teams class FinancialAccountViewSet(viewsets.ModelViewSet): serializer_class = FinancialAccountSerializer permission_classes = (IsOwnerTeam, ) def get_queryset(self): teams = self.request.user.teams.all() … -
Nginx not redirecting to Django
I am setting up a production server with Angular serving the front end and Django on the back. I got Nginx serving Angular properly but any requests to the backend dont go through and just time out. I have Nginx serving Angular on port 80 and then Django on port 8800 This is the code I have in place for Django server { listen 8800; server_name ADDRESS; location = /favicon.ico {access_log off;log_not_found off;} location = /static/ { root /home/ubuntu/django/dbsystem; } location = /media/ { root /home/ubuntu/django/dbsystem; } location = / { include proxy_params; proxy_pass http://unix:/home/ubuntu/django/dbsystem/dbsystem.sock; } } This is the code I have in place for Angular server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name _; location / { try_files $uri $uri/ /index.html; } } This is the code for Gunicorn [Unit] Description=gunicorn service After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/django/dbsystem/ ExecStart=/home/ubuntu/django/bin/gunicorn --access-logfile - --workers 3 -- bind unix:/home/ubuntu/django/dbsystem/dbsystem.sock dbsystem.wsgi:application [Install] WantedBy=multi-user.target If I go to ADDRESS it pulls up Angular which is expected If I go to ADDRESS/suburl it pulls up the appropriate Angular Route as expected If I go to ADDRESS:8800 it loads up the Django (Not found) page since its in debug … -
Django form no error but nothing is happing when submitted
I couldn't figure out what is wrong with my code despite trying for two days. I have a form for user to search based on grade, subject and year. The grade fields prepopulated at initialization while subject and year are populated based on the grade selection for subject and subject selection for year. I managed to accomplish that using AJAX request and it works perfectly. index view process the form and if valid send the parameters to another view. However, nothing happens when the search button is clicked. Thanks in advance in form.py class SearchForm(forms.Form): grade = forms.ModelChoiceField( queryset =Grade.objects.all(),to_field_name="grade",required=False) subject = forms.ModelChoiceField(queryset=Subject.objects.none(), required=True ) year = forms.ModelChoiceField( queryset=Exam.objects.none(), required=True ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) index.html <form id="searchForm" action="" method="POST" data-url-types="{% url 'exam:subjects_choices' %}" data-url-years="{% url 'exam:years_choices' %}" novalidate> {% csrf_token %} <div class="row"> <div class="col-xs-6"> {{ form.grade}} </div> <div class="col-xs-12"> {{ form.subject}} </div> <div class="col-xs-6"> {{ form.year }} </div> </div> <button class=" type="submit">Search</button> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_grade").change(function () { var urlSubjects = $('#SearchForm').attr('data-url-subjects'); var gradeId = $(this).val(); console.log(urlSubjects); console.log(gradeId); $.ajax({ statusCode: { 404: function() { alert( "page not found" ); } }, url: urlSubjects, data: { grade: gradeId }, success: function(data) { $('#id_subject').html(data); } }); }); … -
Django Middleware
How can I do, whole urls for my site available only for register user. I use Middleware, but this class doesn't work I use Django==2.1.4 class MyAuthorization: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response def process_request(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') # or http response return None -
Import error when deploying Django app using Zappa?
I get the following error when instancing my Django app as a lambda function using Zappa. [1549659279288] Instancing.. [1549659279532] cannot import name 'models': ImportError Traceback (most recent call last): File "/var/task/handler.py", line 580, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 245, in lambda_handler handler = cls() File "/var/task/handler.py", line 151, in __init__ wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS) File "/var/task/zappa/ext/django_zappa.py", line 9, in get_django_wsgi from django.core.wsgi import get_wsgi_application File "/var/task/django/core/wsgi.py", line 2, in <module> from django.core.handlers.wsgi import WSGIHandler File "/var/task/django/core/handlers/wsgi.py", line 8, in <module> from django.core.handlers import base File "/var/task/django/core/handlers/base.py", line 7, in <module> from django.urls import get_resolver, set_urlconf File "/var/task/django/urls/__init__.py", line 1, in <module> from .base import ( File "/var/task/django/urls/base.py", line 8, in <module> from .exceptions import NoReverseMatch, Resolver404 File "/var/task/django/urls/exceptions.py", line 1, in <module> from django.http import Http404 File "/var/task/django/http/__init__.py", line 5, in <module> from django.http.response import ( File "/var/task/django/http/response.py", line 13, in <module> from django.core.serializers.json import DjangoJSONEncoder File "/var/task/django/core/serializers/__init__.py", line 23, in <module> from django.core.serializers.base import SerializerDoesNotExist File "/var/task/django/core/serializers/base.py", line 6, in <module> from django.db import models ImportError: cannot import name 'models' I have tried running the app locally using, python manage.py runserver and it works fine locally. However, I get the above error when the app is deployed … -
Django Queryset filter in view
{% for event in events.all %} <tr> <th>{{events.filter(date__exact = event.date)|length}}{% ifchanged event.date %}{{event.date}}{% endifchanged %}</th> I am trying to filer out the same events with the same date.Then i can use it as rowspan for my table which would make it looks nice. But django doesn't allow doing filter in the view. How should i do it? -
How can I pass a dictionary through "get_success_message" function in Django?
I'm trying to pass a dictionary through the "get_success_message" function but I just can't. I need more than a String on my message (title, color...) What am I doing wrong? My view: class PeliculasEdit(SuccessMessageMixin, UpdateView): model = Pelicula form_class = PeliculaForm template_name = "videoclub/peliculas_edit.html" success_url = reverse_lazy('peliculas_manage') message_data = { 'color':'success', 'titulo':'Película editada', 'mensaje':'La película se ha editado correctamente', } def get_success_message(self, cleaned_data): return self.message_data My template where i'm using the message: {% if messages %} {% for message in messages %} <div class="toast show" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> </div> <div class="toast-body"> <p>{{message.color}}</p> </div> </div> {% endfor %} {% endif %} I thought i had to {{message.color}} for example. But that's wrong. Thank you in advance! -
Django can't save comment to post properly
i want to save a comment for my post but for some reasone the view returns (if i enter a wrong captcha): The view MyProject.views.comment_new didn't return an HttpResponse object. It returned None instead. Any idea what could be the reason for this behaviour? Sadly this is the only place/form where it seems that my captcha simply get ignored views.py def comment_new(request, pk): if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): post = get_object_or_404(Post, pk=pk) comment = form.save(commit=False) comment.author = request.user comment.published_date = timezone.now() comment.post = post comment.save() return redirect('post_detail', pk=comment.post.pk) else: form = CommentForm() return render(request, 'MyProject/comment_new.html', {'form': form}) urls.py: url(r'^message/(?P<pk>\d+)/free/comment/new/$', auth_required(MyProject_views.comment_new), name='comment_new'), models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Post Title", max_length=40) content = models.TextField(verbose_name="Post Content", max_length=5000) .... class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=500) published_date = models.DateField(auto_now_add=True, null=True) def publish(self): self.published_date = timezone.now() self.save() ..... template.html: <body> <h1 class="center">Create new comment</h1> <hr class="hr-style"> <div> <form action="" method="post" class="class-two-box"> {% csrf_token %} <table> {{ form.as_p }} {{ field.help_text }} </table> <hr> <button class="btn btn-success" type="submit">Publish Comment</button> </form> </div> </body> forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['content'] captcha = CaptchaField() def __init__(self, *args, **kwargs): super(CommentForm, self).__init__(*args, … -
pluralization formats with django localisation
Iam just putting localization into a django project. I want to pluralize a sentence, what looks like this: {% blocktrans count count=rows.count %} in {{ count }} row {% plural %} in {{ count }} rows {% endblocktrans %} not very pretty, but ok, still usable. (That is, by the way, how its described in the django documentation) But then it turns out, that it looks like this in django.po msgid "" "\n" " in %(count)s row\n" " " msgid_plural "" "\n" " in %(count)s rows\n" " " That is really very unpretty. But I would have to change the template code to: {% blocktrans count count=rows.count %}in {{ count }} row{% plural %}in {{ count }} rows{% endblocktrans %} to make this better. That is pretty much unreadable. Is there no better way with django localization? -
Is there an alternative to using generic foreign keys to handle similar model trees?
My scenario: I'm trying to build a database to track production schedules for different types of shows. I've mapped that out with the following model structure. class Studio(models.Model): ... class Series(models.Model): studio = models.ForeignKey(Studio) ... class Season(models.Model): series = models.ForeignKey(Series) ... class Episode(models.Model): season = models.ForeignKey(Season) ... class Production(models.Model): episode = models.ForeignKey(Episode) But I'm now interested in tracking production of movies as well. This presents a challenge though, because movies don't have the same tree structure as TV. Something like this would be more fitting: class Studio(models.Model): ... class Movie(models.Model): studio = models.ForeignKey(Studio) ... class Production(models.Model): movie = models.ForeignKey(Movie) The problem here is that Production and Studio are exactly the same for both movies and TV (at least in this scenario), so I'm hesitant to have totally separate trees, because this would necessitate duplicating Production. One for TV and one for Movies, when the only difference is the foreign key. Does it make sense to use a GenericForeignKey here? Where a production can either point at an Episode or Movie? I'm hesitant to do so because it sounds like the consensus is to avoid generic foreign keys, but I'm not sure how else to do so. -
custom url patterns in Django
I have a website I am trying to build for personal use, and it possesses two id's one for a meeting (where the race is run) and one for the event (the race number). The event id is in the form of "123456_01" and is passed in the model as a primary key for the Event model, as seen below.... class Event(models.Model): meeting = models.CharField(max_length=500) meetingID = models.ForeignKey(Meeting, on_delete='CASCADE', related_name='races') eventID = models.CharField(max_length=300, primary_key=True) venue = models.CharField(max_length=600, null=True) race_no = models.CharField(max_length=2) event_time = models.TimeField() status = models.CharField(max_length=100) distance = models.CharField(max_length=600) I currently have the views file set up as follows: class EventDetailView(DetailView,LoginRequiredMixin): context_object_name = 'race_detail' template_name = 'event.html' model = models.Event slug_url_kwarg = 'eventID' I also have my front end set up so that at present when I click on a certain race, it automatically navigates to the page with the link http://127.0.0.1:8000/app/123456_01/, so that part is working through this config in the html: {% url 'bettingUI:race' eventID=events.eventID %} the problem I seem to be having is with the configuration of the urls.py file and possibly something I am missing in the views.py file. my urls.py file is set up as follows : from django.urls import path, include from . … -
Warning thrown by Python with multiple inheritance - 'Need more values to unpack' when parent and child inherit from same class
In Django unittest, I am inheriting from 'TestCase' from django.test, Im also inheriting from a custom class to provide some generic helper functions for all TestCases. Looks something like this: class APITest(TestManager, TestCase): def setUp(self): self.User, self.api_client = super(APITest, self).setUp() Test Manager looks like this: class TestManager(TestCase): def setUp(self): # do some stuff Warning is shown on the call to super(APITest, self).setUp()- Need more values to unpack The goal of having TestManager inherit from TestCase as well is to give it access to TestCase assert methods (to collect a bit more information on test results). The code still runs fine, yet this warning makes me worry if this implementation is correct or can be improved. Also i dont understand the error, since the call to super still works and returns 2 values. NOTE: Initially, TestManager did not inherit from TestCase and no warning was shown. So it's really a 2 part question: Why is this error occuring? Is there a design flaw present here which can be improved? -
Create post_save signal for foreign key fields
I have a profile model which contains experience and education as foreign key fields. When I access profile template, it throws. I tried post_save, def create_education(sender, instance, created, **kwargs): if created: Profile.objects.create(education=instance) post_save.connect(create_education, sender=CustomUser) it throws this error, How do I define a post_save signal so experience and education are created when I create a profile? Note: I double checked the error is because foreign fields are empty i.e there is no error when I add experience and education fields in django admin. models.py class Work_Experience(models.Model): job_title = models.CharField(max_length=100, null=True, blank=True) company = models.CharField(max_length=100, null=True, blank=True) description = models.CharField(max_length=300, null=True, blank=True) exp_start_date = models.DateField(null=True, blank=True) exp_end_date = models.DateField(null=True, blank=True) class Education(models.Model): degree = models.CharField(max_length=100, null=True, blank=True) school = models.CharField(max_length=100, null=True, blank=True) edu_start_date = models.DateField(null=True, blank=True) edu_end_date = models.DateField(null=True, blank=True) forms.py class ProfileSettingsForm(forms.ModelForm): job_title = forms.CharField(max_length=40, required=False) company = forms.CharField(max_length=40, required=False) description = forms.CharField(max_length=40, required=False) exp_start_date = forms.DateField(required=False) exp_end_date = forms.DateField(required=False) degree = forms.CharField(max_length=40, required=False) school = forms.CharField(max_length=40, required=False) edu_start_date = forms.DateField(required=False, input_formats=settings.DATE_INPUT_FORMATS) edu_end_date = forms.DateField(required=False, input_formats=settings.DATE_INPUT_FORMATS) def __init__(self, *args, **kwargs): instance = kwargs.get('instance', None) super(ProfileSettingsForm, self).__init__(*args, **kwargs) self.fields['job_title'].initial = self.instance.experience.job_title self.fields['company'].initial = self.instance.experience.company self.fields['description'].initial = self.instance.experience.description self.fields['exp_start_date'].initial = self.instance.experience.exp_start_date self.fields['exp_end_date'].initial = self.instance.experience.exp_end_date self.fields['degree'].initial = self.instance.education.degree self.fields['school'].initial = self.instance.education.school self.fields['edu_start_date'].initial = … -
Cannot get simple icontains to work with django-tables2
I'm new to python, django and HTML, so the mistake could be anywhere - personally I think I'm not understanding how filter works with django-tables2. I cannot seem to get icontains to work with a django-tables2. Basically, I want to do some filtering based on search results from a html POST. The POST in lookup.html gets 'search_words' which I want to use to filter the "decs_us" field of the Price model with icontains filter. Desc_us is the foreign key for the Service Model in the Price Model. This code works, just outputs the table, without any filtering. This is lookup.html <div class="container"> <h2>Price Compare Services</h2> <div id="custom-search-input"> <form action = "{% url 'results' %}" method = "POST", id = "results_out"> {% csrf_token %} <div class="input-group col-md-12" > <input type="text" class="form-control input-lg" placeholder="Enter in a service, e.g. Office Visit" name ='search_words'> <span class="input-group-btn"> <a href="{% url 'results' %}" class="btn btn-info btn-lg" type="button"> Go </a> </span> </div> </form> </form> </div> Then this is my results.html, where I want to present it. There might be numerous mistakes as I'm also new to HTML. {% load staticfiles %} {% load render_table from django_tables2 %} <div class="container"> <form action="roll.html" method="post"> <div class="container"> <h3>Price List</h3> <body> …