Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
About frameworks using web dev
Programming Beginner here. I've been thinking about what to do for my first web application. However, sometimes I look at Python frameworks and get confused. For example, though people often say Django is for medium or large projects while Flask is for smaller ones, I'm not even sure what exactly a small, medium, or large web application entails. Also, how do you decide what kind of framework is suitable or unsuitable for a project? And what happens when you try to use a framework meant for small applications on a large application? Finally, is what you can make dependent on the framework you use? Please answer in a way even a beginner can understand -
Production.py issue with deployment of cookiecutter-django and gunicorn to digital ocean
I built a Django project using the latest version of cookiecutter-django, which seems to be working fine on my local computer as well as when I run it through python manage.py runserver using the various settings files. I'm trying to test my Gunicorn server on Digital Ocean (running Ubuntu 16.04) but for some reason can't get the server to run properly when production.py is the one being used. When I do the following command on bash: gunicorn --bind 0.0.0.0:8000 --env DJANGO_SETTINGS_MODULE=config.settings.test --preload config.wsgi everything works fine and I get these: [2018-02-18 23:31:14 -0500] [31662] [INFO] Starting gunicorn 19.7.1 [2018-02-18 23:31:14 -0500] [31662] [INFO] Listening at: http://0.0.0.0:8000 (31662) [2018-02-18 23:31:14 -0500] [31662] [INFO] Using worker: sync [2018-02-18 23:31:14 -0500] [31666] [INFO] Booting worker with pid: 31666 But when I don't specify the settings file and default to production.py with gunicorn --bind 0.0.0.0:8000 --preload config.wsgi, where the environment variable DJANGO_SETTINGS_MODULE is set to config.settings.production, I only get these: DEBUG 2018-02-18 23:31:55,786 base 31681 140442914699008 Configuring Raven for host: <raven.conf.remote.RemoteConfig object at 0x7fbb5cc0b668> INFO 2018-02-18 23:31:55,786 base 31681 140442914699008 Raven is not configured (logging is disabled). Please see the documentation for more information. And it pretty much just gets stuck there. What might … -
trying to delete inactive users in django
I am writing a site that sends confirmation emails on signup. Until the user clicks the link, the is_active field is set to false. How can I automatically delete any users who do not click the activation link within a certain period of time? Is this even a viable option or is there a better way to work around users who never confirmed their accounts? Thanks for any help! -
Django somehow accesses the static files even after i had deleted the whole static folder
I am new to Django, I had placed the static files in the project level static folder and even in multiple applications inside the app/static/app directory. Everything was working fine until I decided to delete few of the static files. The project is surprisingly accessing the deleted static files i.e images and stylesheets. I even had deleted both the static and the staticfiles folders and it still would access the static files that I had placed in these folders. Following is a code snippet from my setting.py file. STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ('accounts', os.path.join(BASE_DIR, 'accounts', 'static')), ('transport_resources', os.path.join(BASE_DIR, 'transport_resources', 'static')),] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Whatever I do with those static files, it still manages to access the old and even deleted files. I am assuming that it keeps a cache of the files that we had used previously if this is the case, how can we clear that cache. Thanks! -
How correctly reorganize Django settings?
I am trying to reorganize my settings.py file with django-split-settings app. I use next structure but it raise error. It seems to me that I miss something. Can someone say me whats wrong I make? I have next error: ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. P.S. Database settings are correct. With next settings I can run project with python manage.py runserver command without any problem. Error happens when user try to go to any link of the project. structure: project_name/settings/ <- folder where Django by default create settings.py file __init__.py components __init__.py common.py secret_key.py database.py environments __init__.py development.py production.py __init__.py: # -*- coding: utf-8 -*- from split_settings.tools import include from os import environ ENVIRONMENT = 'development' or 'production' base_settings = [ 'components/common.py', 'components/secret_key.py', 'environments/%s.py' % ENVIRONMENT, ] include(*base_settings) common.py: # -*- coding: utf-8 -*- import os from django.core.urlresolvers import reverse_lazy BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ALLOWED_HOSTS = ['127.0.0.1'] DEFAULT_CHARSET = 'utf-8' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.forms', 'django_select2', # "django-select2" application 'modeltranslation', # "django-modeltranslation" application 'reversion', # django-reversion application 'custom_app_1', # "custom_app_1" application 'custom_app_2', # "custom_app_2" application 'custom_app_3', # "custom_app_3" application 'el_pagination', # django-el-pagination application 'custom_app_4', # 'custom_app_4' application … -
django models multiple table inheretence: can I remove the OnetoOnefield link with the parent class for only one field in the childModel
So in the example code below I'm trying to remove the OneToOnefield link between 'type2' and the Child class to avoid confusion and make things neater. I tired chucking the 'parent_link' kwargs in the desired field however that didn't work. class Parent(models.Model): type = models.CharField() type2 = models.CharField(parent_link=False)## class Child(Parent): different_type = models.CharField() different_type2 = models.CharField() -
Different session cookie for each authentication backend
I have an application with multiple authentication backends and I am wondering if it is possible to have different cookie for each backend to reference sessions of each backend separately. The application is made of a central django rest framework API that is linked to 2 frontend apps. The 2 apps are on the same domain but have their own base url (ex: app 1 : https://basedomain/app1/... ; app2 : https://basedomain/app2/...) Each app have it's own authentication backend. The authentication backends are linked to the same User model. -
Using HTTPResponse to return prettified dictionary
I'm trying to return a HTTPResponse object that is prettified JSON. I know that the indent parameter for json only works when you're printing. And printing converts an argument to a string. So shouldn't the indent parameter work if I just str() on my JSON before returning it? def conversationview(request, convo_identification): data = InputInfo.objects.all() conversation_identification = convo_identification #conversation_id = {'conversation_id': []} header = {'conversation_id': '', 'messages': []} entry = {} output = {} for i in data: if str(i.conversation_id) == conversation_identification: header['conversation_id'] = i.conversation_id entry = {} entry['sender'] = i.name entry['message_body'] = i.message_body entry['date_created'] = str(i.created) header.get('messages').append(entry) #parsed = json.loads(header) convert_to_json = json.dumps(header, sort_keys=True, indent=4) output = str(convert_to_json) return HttpResponse(output) -
Django many-to-many relationship gives "IntegrityError: could not create unique index"
I don't know much about Django. I'm taking over a project that was started by another developer. I have two models, in two apps: crawler/Publisher search/Collection In the database, we've been collecting some data about publishers, such as: name address website phone number Collection has a relationship to Users. The users can create their own collections, and add publisher data to those collections. If they want to gather publishers who focus on medicine, they can create a collection called "medicine." I added this line to crawler/Publisher: # publishers -> collections search_collection = models.ManyToManyField('search.SearchCollection', through='search.SearchPublisherCollection') Then I run: python manage.py make migrations python manage.py migrate django.db.utils.IntegrityError: could not create unique index "crawler_publisher_website_145c5f8f_uniq" DETAIL: Key (website)=(https://brandenbooks.com) is duplicated. It's true that we have some duplicate data, but why does Django care? I don't care. How do I make this error go away? And why is Django creating an index on the website field? -
Read data from local text file using CBV
so I have a python program which looks for words in a string that user typed in. I have the words save in a text file. I want to implement the same program in Django. I will have page that will allow user to input the string in a textbox then once the submit button is clicked, it will load the words that matches in my text file. I want to know what is the best approach to do this in Django using CBV? I've seen some post related to reading data from a file but most of them are in FBV. Any suggestions will be highly appreciated. -
Deleting selected rows in DataTable and Django
I've made a selectable rows checkbox using DataTables. I have created a good UpdateView for this so far, so editing items are good. How can I do something like a "Delete selected items" button using that? Here's what I've done so far.. Datatables .js script: $(function () { $('#table-part').DataTable({ dom: 'Bfrtip', responsive: true, buttons: { buttons: [ { extend: 'selectAll', className: 'bg-red waves-effect' }, { extend: 'selectNone', className: 'bg-red waves-effect' }, { extend: 'copy', className: 'bg-red waves-effect' }, { extend: 'csv', className: 'bg-red waves-effect' }, { extend: 'excel', className: 'bg-green waves-effect' }, { extend: 'print', className: 'bg-red waves-effect' }, ], }, 'columnDefs': [{ 'targets': 0, 'orderable': false, 'className': 'select-checkbox', 'checkboxes': { 'selectRow': true } }], 'select': { 'style': 'multi', }, 'order': [ [1, 'asc'] ] }); }); Here's what it looks like: I'm confused as to how can I use the class-based DeleteView in Django. I need something that gets all the id based on what rows I have selected, also, I need to have something like a conditional check that if I didn't select any rows to delete, the delete function won't continue, or it would be disabled, or something like that. Thank you very much in advance! -
How can I delete a repeated dictionary in list?
for dynamic values sometimes the value will be keep repeating, say if a variable table = [{'man':'tim','age':'2','h':'5','w':'40'},{'man':'jim','age':'4','h':'3','w':'20'},{'man':'jon','age':'24','h':'5','w':'80'}, {'man':'tim','age':'2','h':'5','w':'40'},{'man':'tto','age':'7','h':'4','w':'49'}] here {'man':'tim','age':'2','h':'5','w':'40'} dictionary set repeat twice these are dynamic value, How can I stop repeating this, so list will not contain any repeated dictionary before rendering it to templates? -
Not receiving information when using GET method, only when I don't use it
In my project I'm displaying JSON conversations for a certain ID,the ID is passed as an argument in the URL. def conversationview(request, convo_identification): data = InputInfo.objects.all() conversation_identification = request.GET.get('convo_identification') #conversation_id = {'conversation_id': []} header = {'conversation_id': '', 'messages': []} entry = {} output = {} for i in data: if str(i.conversation_id) == conversation_identification: header['conversation_id'] = i.conversation_id entry = {} entry['sender'] = i.name entry['message_body'] = i.message_body entry['date_created'] = str(i.created) header.get('messages').append(entry) output = json.dumps(header) return HttpResponse(output) URLs.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^message/', sendMessage.as_view(), name='message'), url(r'^conversations/(?P<convo_identification>\d+)', views.conversationview, name='conversationview'), ] conversation_identification = request.GET.get('convo_identification') doesn't work (nothing displays on the screen), but when I change it to conversation_identification = convo_identification it will display the information for that ID fine. I don't have any HTML for this because I don't need it. But I'm wondering why I can't use request.GET or request.get.GET()? Does it matter? I know by looking at my terminal that there is a GET request being made. -
How do you write a script referencing indexed inputs?
I'm basically a complete javascript and jquery amateur, trying to get a simple feature working. The goal is to present a list of notifications (corresponding to a django model with a flag of "read") in a user profile page, each one with an "read" checkbox that begins in the unchecked state. When the user checks the "read" box, I'd like the script to update the flag in the backend. Once this occurs, the notification won't be displayed in future visits to the profile page, and the count of unread messages will go down. I've been learning from this tutorial at Tango with Django, which I think does what I want to do. <p> <strong id="like_count">{{ category.likes }}</strong> people like this category {% if user.is_authenticated %} <button id="likes" data-catid="{{category.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-thumbs-up"></span> Like </button> {% endif %} </p> ... <script> $('#likes').click(function(){ var catid; catid = $(this).attr("data-catid"); $.get('/rango/like_category/', {category_id: catid}, function(data){ $('#like_count').html(data); $('#likes').hide(); }); }); </script> The difference is that where they have the button id=likes, I have a checkbox with something like id=notif-64, because there is a checkbox for each notification entry. Can the script be rewritten to accept inputs like notif-X? Or else, how am I going … -
Django 404 localhost:8000/admin error
When I go to "localhost:8000/admin" I get an OBJECT NOT FOUND with a 404 error message. I followed Traversy Media's tutorial and have only edited code in the setting.py file to connect to MySQL. I had to change my port to 8000 and ssl port to 1443 in XAMPP, but apache and MySQL are running smoothly. import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'M42.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'M42.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'm42', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '' } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { … -
Django error when trying to access database in network directory
Now this may be something very foolish to do, but please allow me to discuss my issue. I am attempting to have Django access a database on a remote device by accessing it's network directory like so (in the settings.py script): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/run/user/1004/gvfs/sftp\:host\=169.254.131.151\,user\=root/root/injection_log2.sqlite', }} I've successfully created a file, viewed a file, and edited a file through Vim and that exact directory. So doing this should work right? But I am getting the following bug: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 89, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 176, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 204, in _cursor self.ensure_connection() File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 199, in ensure_connection … -
Redirect to appropriate page while clicking on Button ReactJS/Django project
I'm new to the web development and chose django/Reactjs for my social network project. I made a few api methods like account/view_user/ that returns list of users and account/view_user/ that returns attributes for particular user. I also wrote a page in React that renders a list of users class PersonnelContentFeed extends React.Component { constructor() { super(); this.state = { 'items': [] } } componentDidMount() { this.getItems(); } getItems() { fetch('http://localhost:8000/api/account/view_user/') .then(results => results.json()) .then(results => this.setState({'items': results})); } render() { return ( <ul> {this.state.items.map(function(item, index) { return <PersonnelContentItem item={item} key={index} /> })} </ul> ); } } class PersonnelContentItem extends React.Component { render() { return ( <Row className="PersonnelContentItem"> <Col xs="3"></Col> <Col xs="6"> <Card> <CardImg top width="100%"></CardImg> <CardBody> <CardTitle> <strong>{this.props.item.first_name} {this.props.item.last_name}</strong> </CardTitle> <NavLink to='./PersonDetails'><Button> Details </Button> </NavLink> </CardBody> </Card> </Col> </Row> ) } } There is also a React component for person details(similar to PersonnelContentFeed) The question is: What should I do to redirect user to the appropriate details page (with right id, e.g /api/account/view_user/1) while clicking "Details" Button. Thank you all in advance. -
Django/Postgresql division by zero issue with Window function and Lag expression
How do I avoid division by zero errors where the field with zero values is neither (1) an existing model field or (2) an annotated field? Is that possible? This queryset works until there is a zero in prior_qtr_rev variable. prior_qtr_rev = Window( Lag('rev'), partition_by=F('company_id'), order_by=F('fiscal_end_date').asc() ) yoy = F('rev') / prior_qtr_rev - 1 companies = Financial.objects.filter( company__ticker='AAPL', ).annotate( rev_yoy=yoy, ) I looked at this and this for guidance. I tried wrapping the prior_qtr_rev with Case and When as suggested in the first link, but I was getting the following error. yoy = F('rev') / Case(When(prior_qtr_rev=0, then=0), default=prior_qtr_rev, output_field=FloatField() ) - 1 django.core.exceptions.FieldError: Cannot resolve keyword 'prior_qtr_rev' into field. Choices are: I am trying to avoid having to add prior_qtr_rev in my results. I only want the calculated yoy variable to be annotated. -
Django - Filter a list of objects using a field on a related model and show a value of the related model
(Sorry for my bad english) I have a problem, I need to filter a list of products to show only the availables on a branch office, and this attributes are in a related model of a products. I have a Product Model class Product(models.Model): # Relations supplier = models.ForeignKey( Supplier, verbose_name=_('supplier'), on_delete=CASCADE, ) manufacturer = models.ForeignKey( Manufacturer, verbose_name=_('manufacturer'), on_delete=CASCADE, ) family = models.ForeignKey( Family, verbose_name=_('family'), on_delete=CASCADE, ) category = ChainedForeignKey( Category, chained_field='family', chained_model_field='family', auto_choose=True, verbose_name=_('category'), ) subcategory = ChainedForeignKey( Subcategory, chained_field='category', chained_model_field='category', auto_choose=True, verbose_name=_('subcategory'), ) condition = models.ForeignKey( ProductCondition, default=1, verbose_name=_('condition'), on_delete=CASCADE, ) # Attributes - Mandatory name = models.CharField( max_length=63, unique=True, verbose_name=_('name'), ) slug = models.SlugField( max_length=63, unique=True, editable=False, verbose_name=_('slug'), ) ... ... and I have other Model with the branch office (each branch office use different prices and stock) this is the ProductPrice Model class ProductPrice(models.Model): # Relations product = models.ForeignKey( Product, verbose_name=_('product'), on_delete=CASCADE, ) branch_office = models.ForeignKey( BranchOffice, default=1, verbose_name=_('branch office'), on_delete=CASCADE, ) # Attributes - Mandatory # Costo de compra del producto neto net_purchase_price = models.DecimalField( default=0.00, max_digits=10, decimal_places=2, help_text=_('net purchase price (without taxs)'), verbose_name=_('net purchase price'), ) # IVA aplicable al producto tax_rule = models.SmallIntegerField( choices=TAX_RULES, default=1, verbose_name=_('tax rule'), ) # Precio de compra con … -
Saving Facebook picture in Django Model (REST Social Oath2)
This question is about saving Facebook Profile pictures in the Django model automatically, using https://github.com/PhilipGarnero/django-rest-framework-social-oauth2 library. The above library allows me to create and authenticate users using bearer tokens. I have the created the profile model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile') photo = models.FileField(blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.userprofile.save() Which automatically creates user profiles for each user. Now, I would like to add the following code to save the photo from Facebook. Facebook API requires user id to get this picture. photo = https://facebook/{user-id}/picture/ UserProfile.objects.create(user=instance, photo=photo) The above is not working because 1) I can't figure out where to get the user id from. 2) The image can't be stored like that, I need to convert it to bytes or some other method. -
Cannot reverse a url from name in Jinja2
I have a Django project with Jinja 2.10 templating. I have a standard Jinja environment that aliases url to Django's reverse. In urlpatterns I have the following entry: path('test', views.test, name='test') And I want to dynamically create a URL to this view from another simple template: {{ url('test') }} However, when I open the view that renders this template, I receive an error: Reverse for 'test' not found. 'test' is not a valid view function or pattern name. I see people successfully using this method (e.g. here), so why isn't it working here? -
Select a random ForeignKey in Django
Here is my problem : Imagine I have a model named "Monster" and a database named "Fight". Here is the Fight Model : class Fight(models.Model): fight_id = models.AutoField(primary_key=True) fight_user = models.OneToOneField(User, on_delete=models.CASCADE) fight_enemy = models.ForeignKey(Monster, on_delete=models.CASCADE) Now, if the user (fight_user) does not have already a "fight" model, I want to create one by selecting randomly an enemy in the "monster" model. How can I do that ? Thanks ! -
Designing an HTML form input that takes a range of numbers as well as text options
I have the following form: <table class="table"> <thead> <tr> <th><h4>Monday</h4></th> <th><h4>Tuesday</h4></th> <th><h4>Wednesday</h4></th> <th><h4>Thursday</h4></th> <th><h4>Friday</h4></th> <th><h4>Add</h4></th> </tr> </thead> <tbody> <tr> <form id="tracking_form"> <td><input type="number" name="monday" class="weekday_points" min="0" max="100" required id="id_monday" /></td> <td><input type="number" name="tuesday" class="weekday_points" min="0" max="100" required id="id_tuesday" /></td> <td><input type="number" name="wednesday" class="weekday_points" min="0" max="100" required id="id_wednesday" /></td> <td><input type="number" name="thursday" class="weekday_points" min="0" max="100" required id="id_thursday" /></td> <td><input type="number" name="friday" class="weekday_points" min="0" max="100" required id="id_friday" /></td> <td><input type="button" class="btn btn-default" onclick="submitIfUnique()" value="Add Points"></td> </form> </tr> </tbody> <tfoot> </tfoot> </table> Where a user enters a number from 0 to 100 as a score for a student. I also want to track whether the student was absent, whether the absence was explained, etc. If the student was absent, then the user shouldn't then be able to enter a score. What would be a good form design for a use case like this? I'm working in Django, so I could change the weekday number inputs to text inputs and provide choices like this: settings.py: SCORE = ['Present', 'Absent (Not Explained)', 'Absent (Explained)', 'Integrating'] + [x for x in range(0, 101)] models.py: monday = models.CharField(choices=settings.SCORE) tuesday = models.CharField(choices=settings.SCORE) wednesday = models.CharField(choices=settings.SCORE) thursday = models.CharField(choices=settings.SCORE) friday = models.CharField(choices=settings.SCORE) The problem is, the input would now … -
Django - how to delete model item from list
I'm currently building an app with Django for the purpose of creating user-story cards (a bit like a Trello board). On one page I have my cards displayed as a list: Screenshot of list The code for the list is: <h1>ScrumBuddy Board</h1> <ul> {% for card in cards.all %} <li class="card"><a href="{% url 'card' %}/{{ card.id }}">{{ card.title }}</a> </li> {% endfor %} </ul> And the view def for the board is: def board(request): cards = Card.objects context = {'cards': cards} return render(request, 'scrumbuddy/board.html', context) I'd like to add a delete link to each card that removes it from this list, preferable with a confirmation dialogue box. Any suggestions on how to do that would be fantastic. Many thanks. -
django redirects on posting form using ajax
I'm trying to understand what's actually going on. I have this CreateView based class which I'm using to add new Operation: class OperationCreate(CreateView): model = Operation form_class = OperationForm success_url = reverse_lazy('manage_operations') def form_valid(self, form): (...) form.save() return JsonResponse({'result': 'success'}) def form_invalid(self, form): form.save() return JsonResponse({'result': 'error'}) After getting a form and posting it using ajax I can see following calls logged: [18/Feb/2018 22:52:54] "GET /expenses/new_operation/ HTTP/1.1" 200 1135 [18/Feb/2018 22:53:04] "POST /expenses/new_operation/ HTTP/1.1" 200 21 [18/Feb/2018 22:53:04] "GET /expenses/manage_operations/?csrfmiddlewaretoken=okXK8OwPJ9BJGQeMvSW3Y5koSeTEIXyQDBOAroI1OU8tD7GPxQxZQ37IdhdkhiKe&account=1&type=-1&category=1&date=2001-01-01&amount=2001 HTTP/1.1" 200 3842 I don't understand where did the last one came from. I know I have specified success_url which is a legacy code after previous implementation but it's not used anymore since I have redefined from_valid method. Also I don't get why this last request contains all parameters that I have posted before. Could you please explain it to me? Here is my ajax post method: function postForm(url, form_selector) { var form = $(form_selector); var csrf_token = $('input[name="csrfmiddlewaretoken"]').attr('value') form.submit(function () { $.ajax({ headers: { 'X-CSRFToken': csrf_token }, type: 'POST', url: url, data: form.serialize() }); }); };