Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a maximum length for django request URL?
I was trying to send a get request to django beackend which encodes a list of ids that I need. I noticed that when this list of id(string) goes too long, the django will not handle this request. I can see the request in the django test server, but it never actually enter any view. In the browser, nginx gives me 404. URL: "/xxx/xxx/xxx?type=xxx&ids=4918230_25808605%2C4996758_49144848%2C5121093_43940616%2C56944804_40780188...." I know I can maybe use post to encode params in the body instead, but I just want to find out the reason behind this. -
Is Celery needed for asynchronous file writing functionality in Django?
I'm planning to add some functionality to my Django app that will write a row of data to a csv file when certain views are called: session_dict = collectUserDataFromRequest(request) #....collect parameters from request if os.path.isfile(filename): with open(filename, 'a') as csv_file: a = csv.DictWriter(csv_file,session_dict.keys()) a.writerow(session_dict) csv_file.close() else: with open(filename, 'w') as csv_file: w = csv.DictWriter(csv_file,session_dict.keys()) w.writeheader() w.writerow(session_dict) csv_file.close() # then proceed to render the html A problem I am facing is dealing with potential race conditions when multiple users are accessing my app at the same time. While the data can be added to the csv file in any order, I don't want some user's to wait longer for a view to load while waiting for a lock to be released on the csv file. As such, I think an Asynchronous queue of string data to be written to the file that can run in the background sounds like a good workaround. I have been told that Celery is a good framework for adding asynchronous processes to my Django app. But looking through several tutorials, I am seeing that additional frameworks such as Redis are usually required. I worry that this may be overkill for what I aim to accomplish. Will … -
Solr nested documents vs. grouping/field collapse (via Django Haystack)
I'm working on a website that's running Django with Solr as it search backend. Haystack functions as Django's interface to Solr. I currently have one Solr collection, Apps. Apps each have multiple releases, but in Solr they manifest as one (most recent) release per app. I've come up against a limitation for that architecture: I need to be able to search all of an app's releases and return the most relevant one. Example data in Django ORM: App Foo - Release A - released Nov 2017, compatible with Linux - Release B - released April 2017, compatible with Windows Example search in Solr: Give me all the apps with a release that's compatible with Windows Expected: App Foo is returned. Actual: App Foo is not returned because we're only storing Release A's metadata in the App Foo document in Solr. A solution I'm pursuing is to index Solr based on Release rather than App. But when we do that, how do we use Solr/Haystack to return only the most recent release that matches the query? It seems like Result Grouping / Field Collapsing might solve the problem: http://yonik.com/solr-result-grouping-field-collapsing/ But does Haystack support it? If not, is there a way to … -
Is there a better way to make this queryset using Q? django
I have a query which uses filter but I know there is this thing called Q but trying to play around with it, I am not sure how I can use Q. I am not sure which one would be better but trying to know another way to do the query. What I actually want to do is... for my queryset return I have a default field and two input fields which are options. let's say, language in default is english, there is a location and title field. If location and title fields are available, make a query to query location, title, and language. If only location then only query location and language, if only title then only query title and language. I have done it two ways, one with filter only which has less code... postings = Posting.objects.filter(language='EN') if kwargs.get('title'): postings = postings.filter(title__icontains=kwargs.get('title')) if kwargs.get('location'): postings = postings.filter(location__icontains=kwargs.get('location')) the above does work with using only filter I am trying to see if I can do it with using Q but cannot seem to make it work I have something like this at the moment if title and location: postings = Posting.objects.filter(title__icontains=title, location__icontains=location, language='EN') else: queryQ = Q(posting_language='EN') if title: … -
Django - Trying to a field that is not in the form but is in the model
Right now I have a model.form with one field nothing more, but the model has 3 fields(see reference down below) and 1 of them set by the form, one has a default to false as it should be and the last one I will set in the view but it won't correctly do it and idk why. Model & Form. class TeamMembership(models.Model): user = models.ForeignKey(User) team = models.ForeignKey(Team) leader = models.BooleanField(default=False) class TeamSettings_acceptForm(forms.ModelForm): class Meta: model = TeamMembership fields = ('user',) View @login_required def teamsettings_accept_applications(request, team_pk): if request.method == 'POST': logged_in_user = get_object_or_404(User, pk=request.user.pk) requested_team = get_object_or_404(Team, pk=team_pk) for member in requested_team.teammembership_set.all().order_by('-leader'): if member.user.pk == request.user.pk and member.leader: formaccept = TeamSettings_acceptForm(request.POST) accepteduserid = formaccept.data['user'] teamapplications = TeamApplication.objects.all().filter(from_user=accepteduserid).count() if teamapplications > 1: messages.success(request, "Error") return redirect('teamsettings_applications', team_pk=team_pk) else: if formaccept.is_valid(): teamapplications = TeamApplication.objects.all().filter(from_user=accepteduserid) teamapplications.update(accepted=True) formaccept.team = requested_team.pk formaccept.save() messages.success(request, "User has now been added to your team!") return redirect('teamsettings_applications', team_pk=team_pk) it should create a new row with that data and update the others. All I get in return from Django is staff_teammembership.team_id may not be NULL -
Test results of POST in django custom admin actions django 1.11
I am still very, very new to python and django, so please forgive my ignorance: I am trying to write a test for my custom admin action and the custom action appears to be working, but the test is still failing. I am missing something. I tried to apply the answers from this post: Testing custom admin actions in django The objects are being created correctly, and they have primary keys, but the changes are still not being reflected after I post to the action. If I run the tests I get a test failed: AssertionError: Response should not contain 'unable to find match for' Despite this, when I run the code and manually test it, the changes all work perfectly. Thanks in advance! admin.py def autodetect_manager(modeladmin, request, queryset): employees_to_update = queryset message_container = 'Manager auto-detection results: ' for e in employees_to_update: new_manager = get_manager_from_manager_email(e.manager_email) if new_manager is not None: Employee.objects.filter(pk=e.pk).update(manager=new_manager, manager_email='') else: message_container += 'unable to find match for: ' + e.first_name + ' ' + e.last_name + ' ** ' messages.add_message(request, messages.INFO, message_container) autodetect_manager.short_description = "attempt to automatically detect manager based on email address entered" def get_manager_from_manager_email(manager_email): return Employee.objects.filter(email_address=manager_email).filter(is_manager=True).filter(is_active=True).first() tests.py def test_autodetect_manager(self): # Test manager auto detect """ … -
CSRF token missing or incorrect when trying to upload a file with ajax
I have a file upload form in html with which I'm trying to upload a file(and file size to display) via ajax call. I'm using django. Here's the upload form: <form class="uploadForm" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="uploadFile"> <input type="submit" class="button" id="uploadButton" value="Upload"> </form> Here's my Jquery + Ajax: $('.uploadForm').on('submit', function(event){ event.preventDefault(); var fileSize = ($('#uploadFile')[0].files[0].size/1024); var fileName = $('#uploadFile')[0].files[0].name; var realSize = sizeConverter(fileSize); var fileData = new FormData($('#uploadFile').get(0)); $.ajax({ url: '{% url 'project:uploadFile' %}', type: 'post', data: { 'uploadedFile': fileData, 'fileSize': realSize, csrfmiddlewaretoken: '{{ csrf_token }}' }, cache: false, processData: false, contentType: false, success: function(data){ alert(data); } }); }); And in views.py I have this: class uploadFile(TemplateView): template_name = "project/uploadFile.html" def post(self, request): fileSize = request.POST.get('fileSize') return JsonResponse(fileSize, safe=False) With the above code I get Forbidden (CSRF token missing or incorrect.) error. I googled this and someone here suggested removing processData and ProcessType. When I remove those two parameters absolutely nothing happens when I submit the form(nothing in the console neither). What could be wrong with this? Thanks. -
Django can't find settings module
I'm trying to migrate my Django project "Sales Tracker", but python manage.py migrate, but when I do I get this error message: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) When I looked in the Sales Tracker folder though, the settings.py file is there. Why isn't it being recognized? -
How to create users with different fields?
Currently using the custom created user as its Django recommended way to handle users for projects. class CustomUser(AbstractUser): pass -
Save calculated value as a model field
As a follow up to my eariler question I have a new one. How can I save this calculated value as a model field. I would like to use it in my views and templates to order list by this field. My models: class Tournament(models.Model): name = models.CharField(max_length=100) date = models.DateTimeField('date') player_num = models.IntegerField(verbose_name="") points = models.FloatField(default=1000.00) def get_rating(self): return self.points / 1000.00 class TournamentStandings(models.Model): tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) player = models.ForeignKey(Player, on_delete=models.CASCADE) player_place = models.FloatField(verbose_name=u"") player_points = models.FloatField(verbose_name="", blank=True) #added for testing to save the calculated value in it @property def player_points(self, obj): return obj.tournament.player_num * obj.tournament.get_rating() - obj.tournament.get_rating()*(obj.player_place - 1.00) def save(self, *args, **kwargs): self.player_points = self.get_player_points super(TournamentStandings, self).save(*args, **kwargs) def __float__(self): return self.player_points Funny as on the admin list I have a column where player_points are calculated correctly but when I add a new model instance and try to save it I get this error : 'TournamentStandings' object has no attribute 'get_player_points'. Is it bacause I am trying to do a "self" save and my calculation is (self, obj) ?? Any hints are wellcome. -
Override django change_form.html template when a third app is overriding it
I am trying to override change_form.html only for one model, so I did as explained in the django documentation and created /templates/my_app_name/my_model_name/change_form.html. The problem is, it is not working and I am not seeing the extra features that I have added to the change_form template. I am using django_guardian, which also overrides the same template, so my assumption is that this is causing the issue. It is worth mentioning, that before placing the template in the my_app_name/my_model_name/ folder, the features of both templates were visible in the admin interface. Is there a way to apply this only for 1 model? -
How validate initial values in a Django formset
I am developing an application which where the user to uploads a text based data file (CSV), validates the data file, and displays the data in a form with any error messages so that the user can correct the errors and then commit the data to the DB. I'd like to have the Formset (which displays the records) validate the initial data but I can't seem to get the formset to indicate that it is bound and thus validate (everything displays OK just can't get it to validate). Any advice on how I can pull this off? I've poked around this site and seen a lot of discussion that comes close to answering my question but haven't quite found the solution yet. Thanks in advance! Here's my form code: class BasePITReleaseFormset(BaseFormSet): def clean(): #haven't gotten to coding this part yet return super().clean() class PITReleaseFormsetHelper(FormHelper): def __init__(self, *args, **kwargs): super(PITReleaseFormsetHelper, self).__init__(*args, **kwargs) self.form_method= 'post' self.layout = Layout( 'field1', 'field2', ... 'field9') self.render_required_fields = True Here's my view: class ReleaseGroupLoaderView(View): file_upload_action = #some action template_name = #some template PITReleaseFormset = formset_factory(PITReleaseForm, BasePITReleaseFormset, extra=0) rel_formset_helper = PITReleaseFormsetHelper() rel_formset_helper.template = 'bootstrap/table_inline_formset.html' #this post is called when the user uploads the data file def post(self, … -
Django Formview Won't Validate
Django newbie here. I recently implemented a simple search with Django. I user specifies data in search bar, search is executed. I was able to determine today how to get the search to be null if user clicks on empty search bar. What I'm really trying to accomplish is to implement error logic so that the user has to specify data in the search bar. This has been very straight forward with all of the other views, but the search is a bit trickier, for me anyway. I have done several SO searches today, and determined that my HTML get method is ok for a search, but it may be causing some problems with the FORMVIEW that I am using. I have also tried to override POST and GET for the FORMVIEW, but can't seem to get it to work. I want to stick with CLASS BASED VIEWS, so I am using FORMVIEW. Here is my code.... My HTML <form method="GET" autocomplete=off action="{% url 'Book:book_request_search_results' %}" > <div> <h1 class="title">Book Request Search</h1> </div> {{ form.non_field.errors }} <div class="section"> <input type="search" class="name2" name="q"> </div> <div class="section"> <input type="submit" id="" class="submit6" value="Search"> </div> My VIEWS.PY class BookRequestSearchView(LoginRequiredMixin,FormView): form_class = BookRequestSearch template_name = … -
Correct structure for a Django application and handling the views and sub views
I struggle a bit in order to understand how a Django Application should be properly structured. In particular, I struggle to get my head around the views. So I have this file base.html And I know that this file will have common elements of the whole application such as footer, navbar, head etc. So far so good. Inside my base.html file I will have the tag: {% block content %} {% endblock %} Which handles the dynamic content of the application. Now I create a static page called home.html and inside that file I put {% extends 'base.html' %} ... Whatever I want {% block content %} And now comes the part that I really struggle to understand how it works. I create a new app called dashboard. I create a dashboard.html file and similarly to home.html I extend the base, and but elements inside the content block. In the views.py of the generated application I define: @login_required(login_url="login/") def dashboard(request): return render(request, "dashboard.html") and the dashboard.html {% extends 'base.html' %} {% block content %} <div class="dashboard-page"> <div class="row equal-sides"> <div class="col-sm-2 trim-right"> {% include 'dashboard_navigation.html' %} </div> <div class="col-sm-10 trim-left"> <div class="dashboard-main card"> <h3>Welcome to your dashboard</h3> </div> </div> </div> … -
Django - ValueError: too many values to unpack (expected 2)
I try to use make a droplist from model. USER_TYPE = { 'admin': "Admin", 'patient': "Patient", 'helper': "Helper", 'therapist': "Therapist", } class User(AbstractBaseUser): user_type = models.CharField(max_length=10, choices=USER_TYPE, default="patient") However, I get this error: ValueError: too many values to unpack (expected 2) Thanks in advance! -
I can't set labels in Django forms fields
This is my model: class CalEvents(models.Model): user = models.ForeignKey(User) activity_name = models.CharField(max_length=256, unique=False, blank=True) activity_type = models.CharField(max_length=30, unique=False, blank=True) activity_code = models.CharField(max_length=30, unique=False, blank=True) def __str__(self): return "Activity: '{}' - @{}".format(self.activity_name, self.user.username) This is my forms.py (with my attempted solutions to define the labels): from django.forms import ModelForm from gCalData.models import CalEvents from accounts.models import User class CalEventsForm(ModelForm): class Meta: model = CalEvents fields = ['activity_name','activity_type','activity_code'] labels = {"actiity_name": "Activity name", "activity_type": "Activity type", "activity_code": "Activity code"} def __init__(self, *args, **kwargs): super(CalEventsForm, self).__init__(*args, **kwargs) self.fields['activity_name'].label = "Activity name" self.fields['activity_type'].label = "Activity type" self.fields['activity_code'].label = "Activity code" This is the part of my template where I put the form: <tr> <form method="POST"> {% csrf_token %} {% for field in form %} <td>{{ field }}</td> {% endfor %} <td><input type="submit" name="new_record" class="btn btn-primary" value="Add Activity"></td> </form> </tr> What am I doing wrong? -
Detect table cell change on user edit
I'm trying to detect html table cell change on user input. When I click on table cell I can type text in it, but my .change function is not triggered. However on page load when data are populated from database, for every table cell change change function is fired. I can not figure why. Can you help. My code below: <div id="table" class="table-editable"> <table id="myTable" style="width:100%" class="table"> <tr> <th>Id</th> <th>Link</th> <th>Naslov</th> <th>Lokacija</th> <th>Cijena</th> <th>Telefon</th> <th>Posjet</th> <th>Opis</th> <th>Prednosti</th> <th>Nedostaci</th> <th>Slike</th> <th>Select</th> {% for entry in entries %} </tr> <tr> <td>{{ forloop.counter }}</td> <td><a id="linkHouse_{{ forloop.counter }}" href="{{ entry.link }}">Link na oglas</a></td> <td contenteditable="true">{{ entry.header }}</td> <td contenteditable="true">{{ entry.location }}</td> <td id="priceHouse_{{ forloop.counter }}" contenteditable="true">{{ entry.price }}</td> <td id="contactHouse_{{ forloop.counter }}" contenteditable="true">{{ entry.contacts }}</td> <td id="visitedHouse_{{ forloop.counter }}" contenteditable="true">{{ entry.visited }}</td> <td id="descriptionHouse_{{ forloop.counter }}" contenteditable="true">{% for line in entry.description.splitlines %} {{line}}<br> {% endfor %}</td> <td id="prosHouse_{{ forloop.counter }}" contenteditable="true" >{% for line in entry.pros.splitlines %} {{line}}<br> {% endfor %}</td> <td id="consHouse_{{ forloop.counter }}"contenteditable="true">{% for line in entry.cons.splitlines %} {{line}}<br> {% endfor %}</td> <td > <a class="fancybox" target="_blank" data-fancybox="images" href="{% static "Pic/img_fjords_wide.jpg" %}"><img src="{% static "Pic/img_fjords_wide.jpg" %}" alt="" style="width:150px"></a> <a class="hide fancybox" target="_blank" data-fancybox="images" href="{% static "Pic/img_lights_wide.jpg" %}"><img src="{% static "Pic/img_lights_wide.jpg" %}" … -
How to solve this `ImportError: Cannot import name url` in Django 2.0?
Okay I am following this https://tutorial.djangogirls.org/en/django_urls/ tutorial. And when I run the code python manage.py runserver I get the following error: Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7faf45be1d08> Traceback (most recent call last): File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check for pattern in self.url_patterns: File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/piyush/Desktop/Djangosite/mysite/urls.py", line … -
Django issuing extra GET request
I recently noticed that every page I navigate to in my app automatically issues a second GET request. Doesn't matter if the initial request is GET or POST. I've spent all day digging around the web, and came across this question. It's the same issue, but I've done all of the solutions suggested in the responses (make a blank template, APPEND_SLASH=False, take out all tags to load resources, no link rel="shortcut icon" in my templates), and I still get the double request. Here is the output from my log with the requests for a page that is just a blank template: "GET /app/norepeat/ HTTP/1.1" 200 89 Not Found: /favicon.ico "GET /favicon.ico HTTP/1.1" 404 4719 "GET /app/norepeat/ HTTP/1.1" 200 89 And here is the view for that URL: def norepeat(request): return render(request, 'norepeat.html') And norepeat.html is a blank html file. Any ideas what is going on here? I know that this doesn't really affect my app's functionality, but I would rather that my server doesn't get hit with double the requests when my app is in production. Thanks! -
What's the most effective way to update my remote repository after changing it locally?
So I've pushed my Django project to Bitbucket. However after I make changes to it offline, I want to update the remote repo. How would I go about this? -
django setting initial value on form for DateTimeField to '--------'
I want the expire date to remain required, so I don't want to use Required=False. However, I want it to initially show as '-------' for each of the three dropdowns (month, day, year) instead of January 1 2017 for the dropdowns. from django import forms class LicenseCreateForm(forms.ModelForm): expire= forms.DateTimeField(widget=forms.SelectDateWidget(),) -
Model in header doesn't appear in views that use the header
Model defined in the header of my pages appears on page load and refresh on the main page, but when I navigate to another view the model doesn't appear there. The rest of the header is there, just the dynamic data that isn't. Where am I going wrong? New to both Python and Django, so if anyone can help, please don't be afraid to patronize and Eli5 :) Model defined in models.py: from django.db import models from django.utils import timezone # Create your models here. class Propaganda(models.Model): slogan = models.CharField(max_length=140, blank=True, null=True) def __str__(self): return self.slogan header.html <!DOCTYPE html> <html lang="en"> <head> <title>Christopher's weblog</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Blog site."> <!-- Let's get the static files where we use them, but this could be before the html tag --> {% load staticfiles %} <link rel="stylesheet" href="{% static 'blog/css/bulma.css' %}" type="text/css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- <link rel="stylesheet" href="{% static 'blog/css/cupar.css' %}" type="text/css" /> --> </head> <body> <section class="hero is-success is-bold"> <div class="hero-body"> <div class="container"> {% block slogan %} {% for propaganda in propagandas %} <h6>{{ propaganda.slogan }} it's</h6> {% endfor %} {% endblock %} <h1 class="title" style="display: inline-block;"> <span class="icon"> <i class="fa fa-home"></i> </span> <a href="{% … -
CreateView - Getting a TypeError when trying to save an image upload
I'm trying to wrap my head around images and Form handling with class-based views. So i'm playing with this simple model. When using CreateView do I have to overwrite it with a custom form using form_class in order to successfully upload/save and image? I can't figure out why I'm getting this: Exception Type: TypeError Exception Value: expected str, bytes or os.PathLike object, not tuple The whole thing is barebones, right out of stock. models.py class Post(models.Model): cover_image = models.ImageField('hero image', upload_to='buildings/', blank=True, null=True) def get_absolute_url(self): return reverse('details', args=[str(self.slug)]) views.py from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import CreateView class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['cover_image'] news/templates/news/post_form.py <form enctype="multipart/form-data" method="post" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"/> </form> Can anyone help me understand? -
Django: Clean based on the name of the potential relation
Is there a way to know during the clean operation if the instance is about to be related to a certain model? I understand that since nothing has been saved yet the question sounds bizzare. However, there are ways to understand if the data come from a bulk operation or -if I am not mistaken- the form is displayed in a popup window. I wonder if the following is somehow possible: class A(models.Model): pass class AForm(forms.ModeForm): def clean(self): if <related_name> = 'from_b': # Is something like this possible? pass class B(models.Model): a_key = models.ForeignKey(A, related_name='from_b') class C(models.Model): a_key = models.ForeignKey(A, related_name='from_c') -
git bash not showing warning
when I type; python manage.py runserver on Git bash, it works but I don't see any warning like it does on command prompt. I added pictures for both of them to show what I mean. Could you guys please let me know how to enable this warnings on git bash?