Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-WkhtmltoPDF : How to render SVG files in the pdf using django-wkhtmltopdf?
I have been trying to use django-wkhtmltopdf for a project, and the project requires the rendering of image files onto the PDF. I am having no trouble in rendering JPEGS and PNGs using django-wkhtmltopdf but I cannot load SVG files onto the pdf. <div><img src = "C:\Users\Dhruv Shrivastava\Desktop\pdf-api\pdfengine\pdf\static\animal.svg"/></div> P.S : I have tried both absolute and relative paths and I have found that using absolute paths is the only working option, Also when I use the above HTML code, I can see a small box on the PDF but the image itself is not being displayed Any help would be really appreciated! Thanks! -
How can I access the Django server using WSL (Windows Subsystem for Linux)?
I'm using Bash on Ubuntu on Windows 10 and installed django within a python virtual environment. I'm able to start the django server successfully, but when I type in "http://127.0.0.1:8000/" in my windows 10 browser I don't get a response. I've tried changing the port number to something else (eg. python3 manage.py runserver 127.0.0.1:7171) and I still get nothing. I don't think it's a firewall issue, as WSL and the browser and all running on the same Windows 10 laptop. Do you know what the issue might be? (env) $ python3 manage.py runserver Performing system checks... System check identified no issues (0 silenced). July 26, 2018 - 00:50:25 Django version 2.0.7, using settings 'portfolio.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Windows Version: Windows 10 build 1709 (16299.492) Ubuntu Version: Ubuntu 16.04.5 LTS -
how to fillout a form in an updateView before presenting a form to a user
I an update view for a user so that they can change their settings. I want to make it so that when a user clicks the edit my info button they are taken to a form with the fields already filled out with what is in the database for the user. I have been able to update the database with new information when the users data isn't displayed. I have also been able to display the users data in the form, but then the updating no longer works. I have tried multiple suggestions from stack overflow, so I know something has to be wrong in my code cause everything I am finding says the same thing. I am pretty new to django though so I am a bit confused and would appreciate all the help I could get. Here is the relevant code in my views.py class ProfileUpdate(UpdateView): # model = Prof # fields = ['privacy_level', 'bio', 'profile_picture'] model = Prof form_class = ProfForm template_name = 'user/prof_form.html' # def form_valid(self, form): # user = form.save(commit=True) # # password = form.cleaned_data['password'] # # print(form) # self.fields['bio'].required = False # self.fields['bio'].initial = "sadfasdf" # # user.set_password(password) # user.save() # return redirect('user:index') def … -
Modal Bootstrap - Source Code is different than info rendered by Chrome
I'm doing an e-commerce project and I rant into an issue. I'm using Bootstrap and Django. I apologize for the long question I basically have a loop that runs through my list of products in the database and lists them. It's a table. Each row is a new product and the cells are specific info about the product. The last cell creates a little modal to edit the current information on the project. The information is being passed correctly through the loop, but on Chrome's rendering I see the information for product one listed in all products. This is what the table looks like: This is what my loop to generate the table looks like: <tbody> {% for product in products %} <tr> <td> <img src="{% static product.main_picture %}" style="width: 100px;"> </td> <td>{{product.id}}</td> <td>{{product.name}}</td> <td>{{product.inventory_count}}</td> <td>{{product.sold_count}}</td> <td> <!-- Button trigger edit modal --> <button type="button" class="btn btn-secondary btn-sm" data-toggle="modal" data-target="#editModal">Edit</button> <!-- Edit product Modal --> <div class="modal fade" id="editModal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Edit the product</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!-- Form to edit product --> <form method='post' action='/dashboard/products/update'> {% csrf_token %} <div class="form-group"> <label>Name:</label> <input … -
Consistent MySQL error: Exception Value: (2013, 'Lost connection to MySQL server during query') every 5-10 queries of the database
I have my django app fully deployed (with DEBUG=TRUE) and pretty often, when I query the database in some way, I will lose my mySQL connection and get the following error: Exception Value: (2013, 'Lost connection to MySQL server during query'). It seems to happen randomly. I'll be able to make 5-8 queries, and then I'll get the error. What are the reasons this could be happening? Thanks. Here is the full traceback: Environment: Request Method: GET Request URL: https://www.tcgfirst.com/ Django Version: 2.0 Python Version: 3.6.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'engine', 'contact', 'crispy_forms', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'stripe', 'checkout'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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'] Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in _get_session 191. return self._session_cache During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/mysql/base.py" in execute 71. return self.cursor.execute(query, args) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/cursors.py" in execute 250. self.errorhandler(self, exc, value) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/connections.py" in defaulterrorhandler 50. raise errorvalue File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/cursors.py" in execute 247. res = self._query(query) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/cursors.py" in _query 411. rowcount = self._do_query(q) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/cursors.py" in _do_query 374. db.query(q) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/connections.py" in query 277. _mysql.connection.query(self, query) The above exception … -
Why doesn't the send_email function show up in my console?
I made a basic Django form and implemented that into my HTML. In my views.py, I am trying to send an email out, and I know even if I can't send the email, I should still see a successful POST submission and email detail in terminal. However, the page simply refreshes and nothing happens. views.py snippet: def ticket(request, room_name): form_class = TicketForm if request.method == 'GET': form = TicketForm() else: form = TicketForm(request.POST) # validating and cleaning data if form.is_valid(): type_of_issue = form.cleaned_data['type_of_issue'] #a lot of fields are cleaned, irrelevant to question try: send_mail("Issue/Feedback for Room " + room_name, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found') return redirect('index') #index is my homepage separate from my form/ticket page return render(request, 'ticket.html', context={'room_name': room_name, 'room': room, 'form': form_class, }) ticket.html (where my form is located) snippet: <form id="ticket-border" class="" method="post"> {% csrf_token %} <!--a lot of form data goes here, irrelevant to question--> <input type="submit" value="Submit"> </form> settings.py snippet that has to do with sending email EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = 'notmyrealpassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True I've looked at many examples and YouTube videos online, but I seem to be missing why nothing shows up … -
Django messages success message with data from submitted form
I've got Messages up and running; I can get a simple "submission successful" message to work so I know the context_processors and middleware are all configured properly. However, I'm trying to dynamically update the success message with data submitted in the form. Here is my views.py: from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from menu.models import Book from .forms import AddBook from nextbook.models import Book from django.contrib import messages from django.contrib.messages.views import SuccessMessageMixin from django.views.generic.edit import CreateView def library(request): form = AddBook(request.POST or None) success = False if request.method == 'POST': if form.is_valid(): addedbook = form.save(commit=False) addedbook.save() form = AddBook() success = True messages.success(request, 'Book addition successful') return render(request, 'newbook/index.html', {'form': form}) class BookAddConf(SuccessMessageMixin, CreateView): model = Book success_message = "%(new_title)s by %(new_author)s was added to your library" def get_success_message(self, cleaned_data): return self.success_message % dict( cleaned_data, new_title=self.object.title, new_author=self.object.author ) I'm trying to get success_message to display when the user submits the form, populating the message with the data they entered. I've read through a dozen answers here on SO, but can't seem to find the right info to connect the last dots. Here's my template: {% if messages %} <ul class="messages"> {% for message in … -
Django - force form to save to a specific model
views.py class BHA_UpdateView(UpdateView): model = BHA_List pk_url_kwarg = 'pk_alt' form_class = BHA_overall_Form forms.py class BHA_overall_Form(forms.ModelForm): class Meta(): model = BHA_overall fields = '__all__' models.py class BHA_List(models.Model): well = models.ForeignKey(WellInfo, 'CASCADE', related_name='bha_list') bha_number = models.CharField(max_length=100) class BHA_overall(models.Model): bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_overall') drill_str_name = models.CharField(max_length=111) depth_in = models.CharField(max_length=111) depth_out = models.CharField(max_length=111) If I display the form fields to users using {{ form.as_p }} in my template, it will generate a page that looks like this: How can I override get() or post() method to take input from the user, and save the user input, and update a specific model instance? With my current views.py, user input from forms won't save to DB because my form refers to model = BHA_overall, where as my model for views.py is model = BHA_List. But for some reason I do not want to change my model in views.py. If I change my CBV to CreateView instead of UpdateView, it will create a new BHA_overall instance to DB without any issue. But if I want to UPDATE a specific model instance of BHA_overall, I first need to get() a model instance of BHA_overall, and update the model instance through post(). But I do not know how … -
Setting VAL of hidden field with apostrophe for use in Django using JSON.Stringify()
I'm trying to set the value of a hidden field that I'll later grab in a Django POST, but if text has apostrophes it renders incorrectly. JS Array: let vals = { "apple": "green", "banana": "yellow", "cherry": "Cherry's Are Red" } Hidden Field: <input id="hidden-input" type="hidden" name="testing-stringify" value=""> Javascript/Jquery Stringify: $('#hidden-input').val(JSON.stringify(vals)) Result in HTML: <input type="hidden" name="testing-stringify" value="{"apple":"green","banana":"yellow","cherry":"Cherry's" are red"}> As you can see, it does not render properly. Without the apostrophe, it works as expected. What I'm Expecting: <input type="hidden" name="testing-stringify" value="{"apple":"green","banana":"yellow","cherry":"Cherry's are red"}"> What's the proper way to handle this? -
Customizing the label tag in Django
I'm trying to customize the way we write labels for our forms, by adding custom classes and using titlecase instead of only capitalizing the first letter. To this end, I've written the custom filter label_with_classes(), which is essentially a wrapper around Django's Boundfield.label_tag: from django import template from django.forms import ChoiceField, BooleanField, DateField, ImageField from dashboard.forms.widgets import DateFilterWidget, CheckboxSelectDropdown from titlecase import titlecase register = template.Library() def pretty_name(name): """Convert 'first_name' to 'First Name'.""" return titlecase(name.replace('_', ' ')) def should_be_active(bound_field): '''Determine whether the field's label should have Material's "active" class added to it''' if isinstance(bound_field.field.widget, (DateFilterWidget, CheckboxSelectDropdown)): return True return (bound_field.value() and not isinstance(bound_field.field, (ChoiceField, BooleanField)))\ or isinstance(bound_field.field, (DateField, ImageField)) @register.filter(is_safe=True) def label_with_classes(bound_field, contents=None): '''Extend Django's label_tag() method to provide the appropriate Materialize CSS classes''' if not bound_field: return '' active = 'active' if should_be_active(bound_field) else '' invalid = 'invalid' if bound_field.errors else '' classes = f"{active} {invalid}".strip() if bound_field.name == 'salesforce_id': import ipdb; ipdb.set_trace() contents = contents or pretty_name(bound_field.label) return bound_field.label_tag(attrs={'class': classes}, contents=contents, label_suffix='') where I've set a trace for a particular field. I'm trying to display a generic view for a Company model with the following ModelForm: class CompanyForm(forms.ModelForm): class Meta: model = Company fields = [ 'name', 'salesforce_id', … -
Django how to locate one specific row or container in template
For example, in one template, there are 10 rows of videos and I need to quickly go to the video number 7. How do I achieve that? I know in html, you can use anchor tag then href to the id tag. But how to switch it to django style? Thanks -
How to add custom row level processing of a column in Django Model that is used by Viewsets
Here is my Model for eg. : class Lics(models.Model): files_id = models.IntegerField(blank=True, null=True) seqno = models.IntegerField(blank=True, null=True) expire = models.TextField(blank=True) the field 'expire' comes with a date. I have a function that does delta from 'now' when the api is called. How and where do I add an extra field in the ViewSet when calling Lics.objects.all() that has is added as a 4th field which shows 'days' = 4 for eg. if license is expiring 4 days from now. Expected output : [{files_id:1, seqno:2, expire:'4-jan-2019', 'days':4 }] -
Django - multiple models in one page
I have a model that looks like this: models.py class BHA_List(models.Model): well = models.ForeignKey(WellInfo, 'CASCADE', related_name='bha_list') bha_number = models.CharField(max_length=100) class BHA_Drill_Bit(models.Model): bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_drill_bit') bit_type = models.CharField(max_length=111) class BHA_overall(models.Model): bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_overall') drill_str_name = models.CharField(max_length=111) class BHA_Motor(models.Model): bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_drill_bit') motor_type = models.CharField(max_length=111) BHA_List is a parent model, and the rest are child models related by ForeignKey. The screenshot is the page I want to create So, I want to generate a base page using one of the instances in model = BHA_List. In this page, I want to edit model instances that are related to BHA_List by ForeignKey relationship. I currently have a view that looks like this, but its wrong: class BHA_UpdateView(UpdateView): model = BHA_List pk_url_kwarg = 'pk_alt' form_class = BHA_overall_Form By setting model = BHA_List, I was able to get one of the instances in BHA_List, and generate url from it. Right now my views correctly return one of the instances in BHA_List: BHA 1 I attempted to edit child models by setting form_class = BHA_overall_Form. But this doesn't do anything, though it displayed form fields on the user side. After editing and clicking Submit button, the changes are not saved … -
django form is returning None even if something is in the input
Hello so I've been creating a custom form int django and everything has been working the way I thought it would until i came across this problem. So I've created a form for instructions: class InstructionForm(forms.Form): step = forms.IntegerField(widget=forms.HiddenInput(attrs={'value':1})) instruction = forms.CharField(widget=forms.Textarea) Which I created a Formset for so I can let the user add as many as they want. view.py def create(request): recipeForm = RecipeForm() ingredientFormSet = formset_factory(IngredientForm, extra=4) instructionFormSet = formset_factory(InstructionForm) if request.method == "POST": recipe = RecipeForm(request.POST) ingredients_forms = ingredientFormSet(request.POST, prefix="ingredient") instruction_forms = instructionFormSet(request.POST, prefix="instruction") if recipe.is_valid() and ingredients_forms.is_valid() and instruction_forms.is_valid(): newRecipe = Recipe() newRecipe.title = recipe.cleaned_data['title'] newRecipe.description = recipe.cleaned_data['description'] newRecipe.save() for ingredient in ingredients_forms: cd = ingredient.cleaned_data ingredientName = cd.get('ingredient') try: ingredientObj = Ingredient.objects.get(name=str(ingredientName)) except Ingredient.DoesNotExist: ingredientObj = Ingredient(name=str(ingredientName)) finally: ingAmount = IngredientAmount() ingAmount.amount = cd.get('amount') ingAmount.unit = cd.get('unit') ingredientObj.save() ingAmount.ingredient = ingredientObj ingAmount.recipe = newRecipe ingAmount.save() newRecipe.ingredients.add(ingredientObj) newRecipe.save() #used a counter because my initial way of doing this wont work i=1 for instruction in instruction_forms: cd = instruction.cleaned_data instruct = cd.get('instruction') # I feel like the problem is somewhere in here instructObj = Instruction(instruction=instruct) instructObj.step = i instructObj.recipe = newRecipe instructObj.save() i+=1 else: ingredients_forms = ingredientFormSet(prefix="ingredient") instruction_forms = instructionFormSet(prefix="instruction") return render(request, 'foods/createFood.html',{'recipeForm':recipeForm, 'ingredientFormSet': ingredients_forms, 'instructionFormSet': … -
how a work with downloded tamplates project with django how can i add the python backend in downloded templates?
i want work on a project on Django so m don't know how to work with Downlode project template in Django i have index file of the template project so please suggest me a better answer. -
Can you write a prepare method for a field within a nested field in django-elasticsearch-dsl?
I have a document which contains a nested field. Within this nested field I have a field in which I would like to write a prepare method for. Is this possible in django-elasticsearch-dsl? -
Python line continuation results in DeprecationWarning
In Python 3.6.5, this works fine: command = "ffmpeg -i {0} -vsync 0 -q:v 2 -vf select=\"eq(pict_type\,PICT_TYPE_I)\" -r 30 {1}/frame%03d.jpg".format(file_path, output_path) That's obviously a long line, so I used a line continuation: command = "ffmpeg -i {0} -vsync 0 -q:v 2 -vf select=\"eq(pict_type\,PICT_TYPE_I)\" -r 30 {1}/frame%03d.jpg"\ .format(file_path, output_path) However, at startup, this generates a DeprecationWarning: DeprecationWarning: invalid escape sequence \, command = "ffmpeg -i {0} -vsync 0 -q:v 2 -vf select=\"eq(pict_type\,PICT_TYPE_I)\" -r 30 {1}/frame%03d.jpg"\ This does not, however: command = "foo {0} bar {1}"\ .format(file_path, output_path) I use line continuations all over the rest of the project; none have resulted in DeprecationWarning. Other questions like this one mention this warning, but none for continuation characters that I can find. What causes this warning, and why does it only appear in this very narrow case? Edit: This has nothing to do with the line continuation. The reason the error presented to me only some of the time has to do with Django's runserver. The first time runserver is run, the error is not reported. But if a change causes a reload, then the error is reported when the reloader runs. -
Django ValidationError after javascript modifies the choice field
I'm working on a job scheduling app for a REST API and I've created a Tasks, Nodes, URL, Adom, BaseOptions, and Jobs tables in Django. The BaseOptions have a foreign key for src_adom and dst_adom and the Jobs have foreign keys for the Task, src_node, dst_node, url and baseOptions. I didn't use a ModelForm but a generic Form instead and just loaded up the initial values and choices for all the fields I need in order to process a job. I did that because I couldn't figure out how to make the form change when the user selects a different node and want to change the select field for the corresponding adoms. I'm using javascript to detect a new node and changing the select field with the appropriate adoms for that node. I get a validation error if I change the initial source and/or destination node and modify the adom selection list. I know it is because my list of choices have changed from what I initially rendered the form with. Is there a way to change the choices associated with a ChoiceField during the "clean" method? I can't seem to find that in the documents or digging through the … -
Django with googlemaps api autocomplete
I'm using python client library for google map with django. I would like to be able to have a drop menu of the suggested addresses as someone is typing. Any suggestion? urls.py urlpatterns = [ path('', views.index, name='index'),] forms.py from django import forms class distance(forms.Form): pickupAddress = forms.Field(label='pickup address') destAddress = forms.Field(label='destination address') view.py import googlemaps from .form import distance gmaps = googlemaps.Client(key='*****') distance = gmaps.distance_matrix(pickupAddress, destAddress) return render(request, 'index.html', {'form': form, 'distance':distance) index.html {% load crispy_forms_tags %} <form action="" method="post"> {% csrf_token %} <table> {{ form|crispy }} </table> <input type="submit" value="Submit" /> </form> <ul> <strong> distance:</strong>{{ distance }}</ul> -
Does MySQL 5.6 support 3D Points?
Recently I've been trying to migrate from sqlite to MySQL 5.6 (5.7 had problems with GIS fields). I realized that none of my 3D Points have been imported into the MySQL database so I went in and manually tried to update rows with Django dumpdata output but apparently it doesn't accept 3d points and doesn't give any warnings or errors. Should I switch to another database system? Am I doing something wrong? mysql> UPDATE entrance SET location=GeomFromText("POINT Z (32.077624 36.58562 123)") WHERE id=1; Query OK, 0 rows affected (0.03 sec) Rows matched: 1 Changed: 0 Warnings: 0 mysql> UPDATE entrance SET location=GeomFromText("POINT(32.077624 36.58562)") WHERE id=1; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> SHOW COLUMNS FROM entrance; +---------------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------------------+--------------+------+-----+---------+----------------+ ... | location | point | YES | | NULL | ... -
Django POST with ModelViewSet and ModelSerializer 405
How can I make a ModelViewSet accept the POST method to create an object? When I attempt to call the endpoint I get a 405 'Method "POST" not allowed.'. Within views.py: class AccountViewSet(viewsets.ModelViewSet): """An Account ModelViewSet.""" model = Account serializer_class = AccountSerializer queryset = Account.objects.all().order_by('name') Within serializers.py: class AccountSerializer(serializers.ModelSerializer): name = serializers.CharField(required=False) active_until = serializers.DateTimeField() class Meta: model = Account fields = [ 'name', 'active_until', ] def create(self, validated_data): with transaction.atomic(): Account.objects.create(**validated_data) within urls.py: from rest_framework import routers router = routers.SimpleRouter() router.register( prefix=r'v1/auth/accounts', viewset=AccountViewSet, base_name='accounts', ) Do I need to create a specific @action? my attempts to do so have yet to be successful. If that is the case what would the url = reverse('app:accounts-<NAME>') be such that I can call it from tests? I haven't found a full example (urls.py, views.py, serializers.py, and tests etc). -
Django inventory app tool cart update view
I'm making an inventory app to control the existence of tools in my workshop. Besides knowing how many things I have, I want to know where things are (what tool cart the tool is in ) and who owns the tool cart (Employee). I also need to keep a record of all damaged tools. I've been going about this in the following way: 1.- I have a model called Item that has all common filed for all tools, then I create a new model per tool type with specific field for each tool type i.e.(end-mill-cutters, drill-bits, screws, etc ). these tool Type models all inherit from Item as Multi-table inheritance. 2.- I made the models for my tools carts and its called Carritos( in spanish) this table has a One To One relation ship to Employees( since a carrito can be owned by one person only). It also has a Many To Many relationship to my Item table trough a secondary model called Transaccion, this model handles make the relation between Carrito and Items this is the Carritos model class Carritos(models.Model): no_carrito = models.CharField(max_length=3, unique=True) empleado = models.OneToOneField(Empleados, on_delete=models.CASCADE) # empleado = models.ManyToManyField(Empleados, through='Transaccion') items = models.ManyToManyField(Item, through='Transaccion', related_name='carritos') f_creacion … -
Full join ManyToMany field Django
all). I writing project using Django 2.0. I have 2 models: collaborator and department (1 collaborator can work in one or more departments). So, I want to query table such as: | | Department 1 | Department 2 | Department 3 | |:---------------|:------------:|:------------:|:------------:| | Collaborator 1 | True | False | False | | Collaborator 2 | True | False | True | | Collaborator 3 | True | True | True | Collaborator contains first_name and last_name. True if collaborator works in this department. False if collaborator doesn't work in this department. I want a minimum number of requests to the database and don't how is better: use raw/execute or other django-orm methods? models.py class Department(models.Model): """Model that represents department information.""" title = models.CharField(max_length=256) class Collaborator(models.Model): """Model that represents collaborator information.""" first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) ... departments = models.ManyToManyField(Department) -
AWS django application
How to deploy my django app in AWS free tier? Can anyone explain the steps need tobe followed for deployment of django in AWS using free tier? How to install requirement and project dependencies in AWS? -
Django - edit multiple child model instances
I have a model that looks like this: models.py class BHA_List(models.Model): well = models.ForeignKey(WellInfo, 'CASCADE', related_name='bha_list') bha_number = models.CharField(max_length=100) class BHA_overall(models.Model): bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_overall') drill_str_name = models.CharField(max_length=111) class BHA_Drill_Bit(models.Model): bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_drill_bit') bit_type = models.CharField(max_length=111) class BHA_Motor(models.Model): bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_drill_bit') motor_type = models.CharField(max_length=111) BHA_List is a parent model, and the rest are child models related by ForeignKey. Below is the page I want to create: So, I want to generate a base page using one of the instances in model = BHA_List. In this page, I want to edit model instances that are related to BHA_List by ForeignKey relationship. I currently have a view that looks like this, but its wrong: class BHA_UpdateView(UpdateView): model = BHA_List pk_url_kwarg = 'pk_alt' form_class = BHA_overall_Form By setting model = BHA_List, I was able to get one of the instances in BHA_List, and generate url from it. Right now my views correctly return one of the instances in BHA_List. I attempted to edit child models by setting form_class = BHA_overall_Form. But this doesn't do anything, though it displayed form fields on the user side. After editing and clicking Submit button, the changes are not saved in DB. Someone …