Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add and delete buttons while using formset
I am using django formsets along with a form. On submitting everything is working fine. I want to add "Add New" and "Delete" button for the formset fields. My code looks like: Views.py: def create_food_menu(request): restaurant = Restaurant.objects.get(id=request.user.restaurant.id) form = FoodMenuForm(restaurant) FoodMenuPortionFormset = modelformset_factory(FoodMenuPortion, form=FoodMenuPortionForm, extra=1) food_menu_portion_formset = FoodMenuPortionFormset(queryset=FoodMenuPortion.objects.none(), prefix="food_menu_portion_formset" ) if request.method == 'POST': form = FoodMenuForm(restaurant, request.POST, request.FILES) food_menu_portion_formset = FoodMenuPortionFormset(request.POST, prefix="food_menu_portion_formset") if form.is_valid() and food_menu_portion_formset.is_valid(): food_menu = form.save() food_menu.restaurant = restaurant unique_filename = image_converter(request.POST.get("imagebase64"), 'food_menu/image/') food_menu.image = unique_filename food_menu.save() for item in food_menu_portion_formset: food_menu_portion_obj = item.save(commit=False) food_menu_portion_obj.food_menu = food_menu food_menu_portion_obj.save() addons = item.cleaned_data['addons'] for addon in addons: food_menu_portion_obj.addons.add(addon) food_menu_portion_obj.save() messages.success(request, 'Food Item Added Successfully.') return redirect('list_food_menu') else: pass context = { "title": "add food item", 'food_menu_form': form, "food_menu_portion_formset": food_menu_portion_formset } return render(request, "food_menu/food_menu.html", context) models.py: class FoodMenu(models.Model): name = models.CharField(max_length=20) menu_sub_category = models.ForeignKey(MenuSubCategory, on_delete=models.CASCADE) logo = models.ImageField(upload_to='food_menu/logo') image = models.ImageField(upload_to='food_menu/image', default='main/default.jpg') vegetarian = models.BooleanField(default=True) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) availability = models.BooleanField(default=False) description = models.TextField(max_length=500, blank=True, null=True) class Meta: db_table = TABLE_PREFIX + "food_menu" def __str__(self): return self.name class FoodMenuPortion(models.Model): unit = models.CharField(max_length=20) food_menu = models.ForeignKey(FoodMenu, on_delete=models.CASCADE, related_name='food_menu_portion') price = models.DecimalField(max_digits=10, decimal_places=2) tax = models.DecimalField(max_digits=10, decimal_places=2) available_from = models.TimeField(null=True, blank=True) available_to = … -
How to change the option attribute of a select using Django forms
I have the following Django form (truncated): from django.forms import ModelForm from django import forms from expense.models import Expense class ExpenseForm(ModelForm): class Meta: model = Expense fields = ['category', 'type'] widgets = { 'expense_category': forms.Select( attrs={ 'class': 'form-control', } ), 'expense_type': forms.Select( attrs={ 'class': 'form-control', } ), } This is the html rendered: <select name="expense_category" class="form-control" multiple="" id="id_expense_category"> <option value="A" selected>A</option> <option value="B">B</option> <option value="C">C</option> </select> <select name="expense_type" class="form-control" multiple="" id="id_expense_type"> <option value="1" selected>1</option> <option value="2">2</option> <option value="3">3</option> </select> Desired result: <select name="expense_type" class="form-control" multiple="" id="id_expense_type"> <option class="category_a" value="1" selected>1</option> <option class="category_b" value="2">2</option> <option class="category_c" value="3">3</option> </select> In short, I would like to add the 'class' attribute to the select options, but I don't know how. I have found solutions on stackoferflow from 2011 but it looks like it is already deprecated. model.py(truncated): from django.db import models from django.contrib.auth.models import User from project.models import Project from expense.constants import * class Expense(models.Model): user = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL, ) expense_category = models.CharField( choices=EXPENSE_CATEGORY, default=EXPENSE_STAFFING_PAYMENTS, max_length=200, ) expense_type = models.CharField( choices=EXPENSE_TYPE, default=EXPENSE_PRINTER_LEASE, max_length=200, ) -
save data in editable table to database
I have a web app, backend using Django and frontend using HTML5. Restful API(Django rest framework) is used for GET, PUT, POST and DELETE data types. In the HTML page, I have an editable table, which is supposed to save whatever edited content to database. How could I achieve that? HTML5 page: <table id="thisTable" contenteditable='true' class="table table-bordered table-sm" width="100%" cellspacing="0" style="font-size: 1.0rem;" id="bk-table" data-toggle="table" data-toolbar="#toolbar" data-cookie="true" data-cookie-id-table="materialId" data-show-columns="true" data-show-refresh="true" data-show-fullscreen="true" data-show-export="true" data-height="650" {# data-sticky-header="true"#} {# data-sticky-header-offset-left="7em"#} {# data-sticky-header-offset-right="7em"#} data-click-to-select="true" data-id-field="id" data-show-footer="true" data-url="/api/materials/" data-query-params="queryParams" data-remember-order="true" data-pagination="true" data-side-pagination="server" data-total-field="count" data-data-field="results"> <thead class="thead-dark" > <tr contenteditable='true'> <!--th data-sortable="true" >ID</th--> <th data-field="courseCode" data-formatter="renderCourse">Course Code</th> <th data-field="type">Course Type</th> <th data-field="school">School</th> <th data-field="discipline.name">Discipline</th> <th data-field="discipline.hop1">HOP Name</th> <th data-field="discipline.hop1_email">HOP Email</th> <th data-field="discipline.executive">Executive Name</th> <th data-field="discipline.executive_email">Executive Email</th> </tr> </thead> </table> rest.py: class MaterialSerializer(serializers.ModelSerializer): book = BookSerializer(many=False) course = CourseSerializer(many=False) # should not use SemesterCourseSerializer this because it also include books # setting allow_null True so that this field always present in the output, otherwise it will not present when null # that cause datatable alert error when render missing field. school = serializers.ReadOnlyField(source='course.courseInfo.school.name', allow_null=True) #courseCode = serializers.ReadOnlyField(source='course.courseInfo.code') courseId = serializers.ReadOnlyField(source='course.courseInfo.id') year = serializers.ReadOnlyField(source='course.semester.year') month = serializers.ReadOnlyField(source='course.semester.month') term = serializers.ReadOnlyField(source='course.semester.term') quota = serializers.ReadOnlyField(source='course.quota') type = serializers.ReadOnlyField(source='course.courseInfo.type') available = serializers.ReadOnlyField(source='course.courseInfo.available') … -
Merge two Django query sets and deduplicate objects sharing a common value
I have a Django project using a segmentation library and need to merge two query sets and deduplicate the resulting query set, which is causing me to scratch my head over how to do so. not_segments = Page.objects.all().no_segments() (paraphrased) gives me pages with segment pages excluded. only_segments = Segment.objects.get_queryset().for_user(user=user) (paraphrased) gives me segmented page objects from the same model, but of course there are overlaps. not_segments = Page 1, Page 2, Page 3, Page 4 only_segments = Page 2 (for user), Page 4 (for user) So let’s say there’s a guid field in the model which is not enforced as unique, but rather identical in value between a root page and its segment child page. How do I compare the objects of the two query sets when merging them and omit objects from not_segments if an object with the same guid exists in only_segments? To get at the desired result of queryset = Page 1, Page 2 (for user), Page 3, Page 4 (for user) -
Django and React Google cloud deployment
I have a website that uses Django for the backend and React for the frontend and i want to make my website ready for customers. what are the step i should take to make my application production ready? what settings in react or Django should i change? what do i do with static files? what do i do with the database? should use something like Nginx? how do i make sure my app is secure? should i even use google cloud or is there a better alternative for my application like AWS or something similar? -
Shopify API to get All Records for Customers,Orders & Products (Django)
I have searched for getting all customer one by one.But after some study understand the whole way to solve. for getting 250 data from shopify api we can use limit but pagination and synchronization for getting all data we need some step to get all data. shop_url = "https://%s:%s@%s.myshopify.com/admin/api/%s/" % (API_KEY, PASSWORD, SHOP_NAME, API_VERSION) endpoint = 'customers.json?limit=250&fields=id,email&since_id=0' r = requests.get(shop_url + endpoint) Step 1:Where we need to put the initial id to start extraction and store to your db customers.json??limit=250&fields=id,email&since_id=0 Step 2:Next changes the since_id value with with last id of your extraction like my image. last id=5103249850543 (suppose) Mentioned in Fields Data customers.json??limit=250&fields=COLUMN_YOUNEED_FOR_CHK&since_id=5103249850543 -
Django Python Google Social Auth: django.db.utils.ProgrammingError: relation "account_emailaddress" does not exist
I am super new here so don't roast me. I keep getting this error: django.db.utils.ProgrammingError: relation "account_emailaddress" does not exist For context, I am running a django application and am trying to run "manage.py migrate account" in order to use Google Social Authentication. After trying to sign up with google, it gives me this error as well: relation "account_emailaddress" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "account_emailaddress" -
How to change the option attribute of a select using Django forms
I have the following Django form (truncated): from django.forms import ModelForm from django import forms from expense.models import Expense class ExpenseForm(ModelForm): class Meta: model = Expense fields = ['category', 'type'] widgets = { 'category': forms.Select( attrs={ 'class': 'form-control', } ), 'type': forms.Select( attrs={ 'class': 'form-control', } ), } And this is the html rendered: <select name="category" class="form-control" multiple="" id="id_category"> <option value="A" selected>A</option> <option value="B">B</option> <option value="C">C</option> </select> <select name="type" class="form-control" multiple="" id="id_type"> <option value="1" selected>1</option> <option value="2">2</option> <option value="3">3</option> </select> And this is the desired result: <select name="type" class="form-control" multiple="" id="id_type"> <option class="category_a" value="1" selected>1</option> <option class="category_b" value="2">2</option> <option class="category_c" value="3">3</option> </select> In short, I would like to add the 'class' attribute to the select options, but I don't know how. I have found solutions on stackoferflow from 2011 but it looks like it is already deprecated. -
AttributeError: module 'xml.etree.ElementTree' has no attribute '_IterParseIterator'
I'm using Python v3.8.5 and Django v3.2.6. When I type in "models.py" this code : image = models.ImageField(null=True, blank=True) But it was shows : AttributeError: module 'xml.etree.ElementTree' has no attribute '_IterParseIterator'. The full error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 393, in execute self.check() File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\model_checks.py", line 34, in check_all_models errors.extend(model.check(**kwargs)) File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 1271, in check *cls._check_fields(**kwargs), File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 1382, in _check_fields errors.extend(field.check(**kwargs)) File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\files.py", line 384, in check *self._check_image_library_installed(), File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\files.py", line 389, in _check_image_library_installed from PIL import Image # NOQA File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\Image.py", line 43, in <module> import defusedxml.ElementTree as ElementTree File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\defusedxml\ElementTree.py", line 62, in <module> _XMLParser, _iterparse, _IterParseIterator, ParseError = _get_py3_cls() File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\defusedxml\ElementTree.py", line 56, in _get_py3_cls _IterParseIterator = pure_pymod._IterParseIterator AttributeError: module 'xml.etree.ElementTree' has no attribute '_IterParseIterator' Why I am getting this error ? Thanks in advance. -
Django-OpenCV : Invalid number of channels in input image:
I want to upload an image to my django backend and have the images treated and prepared for OCR before it is saved. However for some images i get this error : Invalid number of channels in input image: 'VScn::contains(scn)' where 'scn' is 1 i tried to run the processing pipeline on jupyter and used the same image and the error didn't show up so maybe when saving the image to the ImageField this error is being produced however i can't fix it. here is the processing code (preprocessing.py) from cv2 import cv2 import numpy as np from matplotlib import pyplot as plt def process_image(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (9, 9), 0) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 5)) dilate = cv2.dilate(thresh, kernel, iterations=5) # Find all contours contours, hierarchy = cv2.findContours(dilate, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key = cv2.contourArea, reverse = True) # Find largest contour and surround in min area box largestContour = contours[0] minAreaRect = cv2.minAreaRect(largestContour) # Determine the angle. Convert it to the value that was originally used to obtain skewed image angle = minAreaRect[-1] if angle < -45: angle = 90 +angle elif (angle>-45)and(angle<=0): angle=angle elif … -
How to Read a Specific sheet from an Excel File Using Django
I'm reading an xlsx file to store the data in the database. Everything is working correctly. But my question is that I want to read only one specific spreadsheet from the Excel file. For example, a file can have multiple sheets like: Sheet1, Sheet2 ... I want to read data only from Sheet2 and store in database. At the moment I'm doing it as follows: imported_data = dataset.load(data.read(), format='xlsx') However, this way it does not filter a specific sheet. How can I do this? After I put each line of sheet in database.. -
How do I create a nested json format in django rest serializer?
Currently I have this format in the api "inner_divertor": { "volume": 5.2, "volume_units": "m^2", "volume_notes": "xyz" }, "outer_divertor": { "volume": null, "volume_units": "m^3", "volume_notes": null } I'm trying to add a nested "volume" variable "inner_divertor": { volume:{ "volume": 4.3, "volume_units": "m^2", "volume_notes": "xyz" } }, "outer_divertor": { volume:{ "volume": null, "volume_units": "m^3", "volume_notes": null} } class InnerDivertorSerializer(FlexFieldsModelSerializer): class Meta: model = InnerDivertor fields = ( 'volume', 'volume_units', 'volume_notes') class OuterDivertorSerializer(FlexFieldsModelSerializer): class Meta: model = OuterDivertor fields = ( 'volume', 'volume_units', 'volume_notes') -
Django with Oracle DB - ORA-19011: Character string buffer too small
I have the following model for an Oracle database, which is not a part of my Django project: class ResultsData(models.Model): RESULT_DATA_ID = models.IntegerField(primary_key=True, db_column="RESULT_DATA_ID") RESULT_XML = models.TextField(blank=True, null=True, db_column="RESULT_XML") class Meta: managed = False db_table = '"schema_name"."results_data"' The RESULT_XML field in the database itself is declared as XMLField. I chose to represent it as TextField in Django model, due to no character limit. When I do try to download some data with that model, I get the following error: DatabaseError: ORA-19011: Character string buffer too small I figure, it is because of the volume of data stored in RESULT_XML field, since when I try to just pull a record with .values("RESULT_DATA_ID"), it pulls fine. Any ideas on how I can work around this problem? Googling for answers did not yield anything so far. -
Why ListStyle plugin doesn't show up in my CKEditor in Django website?
As seen here, I have two more extraPlugins, which do show up on the Website. The problem is liststyle only. Am I supposed to add anything to the toolbar list? 'NumberedList' and 'BulletedList' are already there, and I thought liststyle was supposed to override them. As you can see, the liststyle is again not seen here, although field and codesnippet are. I have also downloaded the plugin dependencies for liststyle. Is there anything else I need to do? -
Data in templates
I need your support. I have 2 models Author and Post, I want to display the data for a particular author in a template. I want display the posts of an specific Author, and the information (first_name and last_name) of that Author. In my view file I created a method, with 2 querysets. One of this QuerySet looks in the table Post the posts of an specific Author, and the other query set looks in the Author table the information of the Author owner of the posts. My question, Can I do this with only one QuerySet? If yes, How can I display it in the template? MODELS class Autor(models.Model): first_name = models.CharField(max_length=30, null=False, verbose_name='First Name') last_name = models.CharField(max_length=30, null=False, verbose_name='Last Name') class Post(models.Model): autor = models.ForeignKey(Autor, on_delete=models.CASCADE) post = models.CharField(max_length=200, null=False, verbose_name='Post') VIEW.PY def index(request): autor = Autor.objects.filter(first_name='Peter').first() autor_posts = Post.objects.filter(autor__first_name='Peter') return render(request, 'posts.html', {'autor_posts': autor_posts, 'autor': autor}) POSTS.HTML Author: {{ autor.first_name }}, {{ autor.last_name }} Posts: {% for post in autor_posts %} <p>{{ post.id }}, {{ post.post }}</p> <p></p> {% endfor %} -
Why can't I run "python manage.py startup APP_NAME" with django?
I'm trying to build a Django app, but it doesn't let me startup the app so I can bring it to the development server. I run python manage.py startup APP_NAME, where I expect the app to run. Instead, I get an error saying there is no such file or directory called manage.py. However, I have it open. Is there a reason for this? -
Django and Axios Forbidden (CSRF token missing or incorrect.)
I am having issue with my django server when trying to connect it to axios. It should be a simple fix but I am stuck! I am getting this error from my django server: [23/Aug/2021 19:25:36] "POST /subscription HTTP/1.1" 403 2519 Forbidden (CSRF token missing or incorrect.): /subscription Here is the method I am using: const newsletterSignUp = async function (email) { try { let res = await axios({ method: "post", url: "http://127.0.0.1:8000/subscription", data: { email: email }, }); return res; } catch (err) { console.error(err); return err; } I have tried adding custom headers, but I think the dash in the name is causing issues and I don't know how to solve it. headers: { set-cookie: "csrftoken=ee95ec102d0d884ea95eb09cb421cdd8382aed79" } I know my Django code is fine since it works in the browser. I have attached it for reference. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Email subscriptions</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" /> </head> <body class="container py-4"> <!--Email subscription Form --> <form method="post" action="{% url 'subscription' %}"> {% csrf_token %} <div class="form-group"> <label>Subscribe to get the latest Articles</label> <br /> <input type="email" name="email" placeholder="Enter Email to Subscribe" /> <button class="btn btn-info" type="submit">Submit</button> </div> </form> <!-- message if … -
I can't get response from my views.py to my AJAX call
I'm working in a personal project and in one section I'm showing cards on the screen, but the card only show one at time. I needed to do a Ajax call and it's working good, but the only thing that I can't get is the response from my view. This is my Ajax call: $('#accept').on('click', function() { var accept_value = $('#accept').val(); $.ajax({ url: '/cards/', type: 'POST', data: {'duo_status': accept_value}, headers: { "X-CSRFToken": "{{ csrf_token }}" }, success: function(data) { console.log('Accepted: success') console.log(data) } }) }) And I'm sending this from my view, that is a list of objects: return render(request, 'cards.html', {'duo_filter': shuffled_list}) When I click the button, the data is sent to the views.py normally, but when I try to show this data in the console, it shows me this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <title>Cards</title> </head> <body> <div style="display: flex;"> <strong style="padding: 0 5px;"></strong> <p id="card_username"></p> </div> <!--BOTÕES (ACEITAR/RECUSAR)--> <div style="display: flex;"> <button style="margin: 10px 20px; background-color: red;" id="refuse" value="refuse,"> Recusar </button> <button style="margin: 10px 20px; background-color: green;" id="accept" value="accept,"> Aceitar </button> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).ready(function() { $('#refuse').on('click', … -
Django Foreign Key many to one not working
I am abit confused on how to make a foreing key work with many to one relationship. I have 2 Models, auditsmodel (Which is the model containing the data) and dv_mode(Containing data validation as options for the answers). I have created a Foreign key in auditsmodel to reference the Data validation options. Models.py class dv_model(models.Model): # auditsModelKey = models.ForeignKey(auditsModel, on_delete = models.CASCADE) Defect_Area_dv = models.CharField(_('Defect Area dv'), max_length=200) Key_Driver_dv = models.CharField(_('Key Driver dv'), max_length=200) Sub_Key_Driver_dv = models.CharField(_('Sub Key Driver dv'), max_length=200) QS_Login_dv = models.CharField(_('QS Login dv'), max_length=200) QS_Name_dv = models.CharField(_('QS Name dv'), max_length=200) Status_dv = models.CharField(_('Status dv'), max_length=200) Metric_name_dv = models.CharField(_('Metric name dv'), max_length=200, default='') Correct_Associate_Action_dv = models.CharField(_('Correct Associate Action dv'), max_length=200) Correct_investigator_Action_dv = models.CharField(_('Correct investigator Action dv'), max_length=200) Action_Correctly_Captured_dv = models.CharField(_('Action Correctly Captured dv'), max_length=200) Audit_Outcome_dv = models.CharField(_('Audit Outcome dv'), max_length=200) Defect_Area_Investigator_dv = models.CharField(_('Defect Area Investigator'), max_length=200) Document_Name_dv = models.CharField(_('Document Name dv'), max_length=200) Document_Type_dv = models.CharField(_('Document Type dv'), max_length=200) Type_of_Audit_dv = models.CharField(_('Type of Audit dv'), max_length=200) If_Correctly_Captured_No_dv = models.CharField(_('If Correctly Captured No dv'), max_length=200) Country_dv = models.CharField(_('Country dv'), max_length=200) Region_dv = models.CharField(_('Region dv'), max_length=200) Key_Driver_unique_dv = models.CharField(_('Metric name dv'), max_length=200, default=None) Sub_Key_Driver_unique_dv = models.CharField(_('Metric name dv'), max_length=200, default=None) def __str__(self): return self.Defect_Area_dv class auditsModel(models.Model): Dv_model = models.ForeignKey( dv_model, on_delete=models.CASCADE, … -
I can't get this foreignkey table value to be displayed in the django template
I cant get some ForeignKey values displayed in my template. This are the two models involved in the question: ** Models.py ** class Portfolio(models.Model): title = models.CharField(max_length= 50, null= True) description = models.TextField(max_length= 300, null= True) class Spotify_Playlist(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete= models.CASCADE, null= True) title = models.CharField(max_length= 50) spotify_url = models.CharField(max_length= 50) description = models.TextField(max_length= 100, null= True) artist_img = models.ImageField(null= True, upload_to= 'image/') *** Admin.py *** @admin.register(Portfolio) class PortfolioAdmin(admin.ModelAdmin): inlines = [ SpotyListInline, SpotySingleInline, YoutubeInline, ] class SpotyListInline(admin.TabularInline): model = Spotify_Playlist So Im trying to display the spotify playlist in my template like this *** index.html *** <section id="portfolio"> {% for portfolio in portfolios %} <h1>{{ portfolio.title }}</h1> <p>{{ portfolio.description }}</p> {% for playlist in portfolio.Spotify_Playlist_set.all %} <p>{{playlist.title}}</p> <iframe src='https://open.spotify.com/embed/playlist/{{ playlist.spotify_url }}' width="50%" height="380" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe> {% endfor %} {% endfor %} </section> But the {{playlist.value}} and the embeded player with the {{playlist.spotify_url}} aren't showing. I would really appreciate any help -
Django: Table doesn't exist, and can't run initial migration to create table
I was trying to run a migration and it said that a table didn't exists, django.db.utils.ProgrammingError: (1146, "Table 'blah_blah' doesn't exist") After much frustration, I said ok and I deleted all the tables from my database to try and start fresh (as if I just started a new project) I deleted all the migrations folders, deleted the database and made a new one, changed the settings to use that database. But I still get a table doesn't exist error? Is this an issue with some kind of caching mechanism or something? -
Django - How can this UpdateView return to a filtered TableView?
I have a Django project in which I have a TableView with filters on it. It can redirect to UpdateViews and DeleteViews from the rows in the table, and it works fine, and the UpdateView correctly redirects to the TableView on success. My issue is, I can't manage to make the UpdateView redirected to the TableView while keeping the filters the TableView had when the UpdateView was called. The UpdateView has this get_context_data method, in which I'm able to send the filtered URL: def get_context_data(self, **kwargs): context = super(SaleUpdateView, self).get_context_data(**kwargs) ... context['referrer'] = self.request.META.get('HTTP_REFERER') return context I made a button in the HTML template to redirect to that referrer, which should redirect to the filtered TableView, but it redirects me to the unfiltered TableView. I think it has to do with my form_valid method and get_success_url method: def form_valid(self, form): ... return HttpResponseRedirect(self.get_success_url()) def get_success_url(self, form): ... return reverse_lazy('sale_list') How can I access either the self.request.META.get('HTTP_REFERER') or the referer data I sent to the template, in the context of the get_success_url method? -
Django determine the value of a checkbox in a template from views
I have been trying to design a page in Django that works as follows. My "list_books.html" page lists every book object handed to it. I have a number of functions in views.py that determine what values would be used to determine the books shown on that page (i.e. all books by an author, all books in a series, all books with the same publication year) ex. @with_person_email def book_list_author(request, person): return show_book_list(request, person.books, { 'author': person }) def show_book_list(request, blist, template_args, **kwargs): # this is just the defaults, will be replaced by data.update below data = { 'genre': None } try: # filters the list based on the keyword arguments blist = dataview.book_list(blist, **kwargs) except dataview.DataViewError as e: blist = None data['error'] = str(e) try: data['books'] = RequestPages(request, blist, desc=True) except Exception as e: if not utils.is_db_regex_exception(e): raise data['books'] = None data['error'] = 'Invalid regex.' data['genres'] = models.Genre.objects.order_by('kind', 'name') data.update(kwargs) data.update(template_args) return render(request, 'book_list.html', data) book_list.html has a for loop that goes through each book and prints information about it. However, I have a boolean on the book model called "is_archived". I want to be able to both set "is_archived" on the book from book_list.html, and filter the books shown … -
Django admin doesn't show map for PointField
I have a django model with PointField from django.contrib.gis.db.models import PointField class Construction(models.Model): coordinates = PointField(blank=True) In admin.py i have only admin.site.register(Construction) In admin page (/admin/api_buildings/construction/2/change/) I don't see map to set point foeld It works fine for localhost, but doesn't work on my server. On the server I have the following picture The picture shows that static/gis/js/OLMapWidget.js is not found settings.py contains STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Dockerfile FROM osgeo/gdal:ubuntu-small-latest ENV DEBIAN_FRONTEND=noninteractive RUN apt update && apt upgrade -y && apt install -y \ software-properties-common curl \ libsm6 libxext6 libxrender-dev libgl1-mesa-glx libsqlite3-mod-spatialite RUN add-apt-repository ppa:deadsnakes/ppa RUN apt update && apt install -y python3.8 python3.8-dev python3.8-distutils RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.8 1 RUN update-alternatives --set python /usr/bin/python3.8 RUN curl -s https://bootstrap.pypa.io/get-pip.py -o get-pip.py && \ python get-pip.py --force-reinstall && \ rm get-pip.py COPY requirements/production.txt ./requirements.txt RUN python -m pip install -r requirements.txt RUN mkdir /app COPY . /app -
I'm having trouble solving a junior python test
I'm doing junior python developer test as a training, and came across the following test. *Route to register a new reseller requiring at least, cpf, full name, email and password. *Route to validate a reseller login *Route to register a new purchase requiring at least code, value, date, cpf from the reseller. All entries are saved with the status "In validation", except when the CPF is 153.509406-56, in which case it is saved as "Approved". *Route to edit a purchase, allow editing only if the sale status is "In validation". *Route to delete a purchase, allow deletion only if the status of the sale is "In validation". I'm having trouble creating the edit and delete route based on validation