Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show data after dropdown selection
I am struggling with my code. I want to show data from a specific user on screen. When the second dropdown is selected with the user from a specific group, I want his records to be shown on screen. But what ever I try, the data stays the same from one user. In a later stadium I want to make an Else and say if there is no data, that there is no data of the person. Should I do something with a jquery, or is there an easier way to solve this? The first dropdown is the group, the second dropdown the user. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class DisplayGroups(models.Model): group_name = models.CharField(max_length=200) def __str__(self): return self.group_name class DisplayUsername(models.Model): username = models.CharField(max_length=100) def __str__(self): return self.username class CijferLijst(models.Model): name = models.CharField(max_length=200, default='') vak1 = models.CharField(max_length=200, default='') cijfer1 = models.DecimalField(max_digits=3, decimal_places=1, default='1.0') vak2 = models.CharField(max_length=200, default='') cijfer2 = models.DecimalField(max_digits=3, decimal_places=1, default='1.0') username = models.ForeignKey(User, on_delete=models.CASCADE, default='') def __str__(self): return '%s %s %s %s %s %s'%(self.name, self.vak1, self.cijfer1, self.vak2, self.cijfer2, self.username) bekijk.html {% extends 'home/base.html' %} {% block title %}Cijfers studenten{% endblock %} {% block javascript %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function() { … -
Is there a way in Django Rest Framework to deliver only specific attributes?
When building a large web backend we are faced with the problem that we have models with a lot of attributes. As we want to reduce the size of the responses for efficiency we use different serializers for our models. Take this simple model for instance: class Address(models.Model): country_id = models.ForeignKey(Country, on_delete=models.PROTECT) postal_code = models.CharField(max_length=10) street = models.CharField(max_length=176) number = models.CharField(max_length=20) additional = models.CharField(max_length=256, blank=True, default='') city = models.CharField(max_length=176) state = models.CharField(max_length=50) user = models.ForeignKey('user.User', on_delete=models.CASCADE) For this alone we have an ID Serializer, a StringSerializer (for delivering a usable string), a MinimalSerializer (for a list of multiple addresses), a DetailSerializer (with depth=1 for getting country and user details ... Now with this complexity we face several issues and thought about restructuring the api to include the required fields in the request. Is this possible with django + drf? We believed to find something under Content Negotiation but this is a different topic. -
Django display uploading files in different fields
I am creating a system with Django. A user has several customers. And every customer has a different file upload field. I have upload functions but it is common for everyone. What I want is for every customer should have different pdf upload and display field. How can I do that? models.py class Pdf(models.Model): comp_name = models.CharField(max_length=200, default='', blank=True, null=True) title = models.CharField(max_length=200) pdf = models.FileField(upload_to='pdfs/') type = models.CharField(max_length=200, default='Select') year = models.CharField(max_length=200, default='Select') def __str__(self): return self.title views.py def pdf_list(request): pdfs = Pdf.objects.all() return render(request, 'pdf_list.html', {'pdfs': pdfs}) def upload_pdf(request): if request.method == 'POST': form = PdfForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('pdf_list') else: form = PdfForm() return render(request, 'upload_pdf.html', {'form': form}) forms.py class PdfForm(forms.ModelForm): CHOICES = [ ('img', 'Image'), ('txt', 'Text'), ] type = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) year = forms.fields.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) comp_name = forms.ModelChoiceField(queryset=CompanyProfile.objects.all(), required=False, widget=forms.HiddenInput()) customer/model.py class Customer(models.Model): name = models.CharField(max_length=20) surname = models.CharField(max_length=20) companyName = models.CharField(max_length=200, default="Choose") -
Django DRF authentication methods
I am new to Django and am trying to create an application using Vue js web app, Flutter for mobile and django in the back end. I am actually confused which authentication method I should be using. I am making food delivery app clone. -
Ajax - 500 Internal Server Error on LocalHost
I am trying to create an EditForm for my data in Django and am receiving a 500 Internal Server error whenever I hit Save Changes. Screenshots below are of the process within Console and when I click on the xhr error. Any idea what would be causing this, considering I am just on my local http://127.0.0.1:7000 server at this point? views class UpdateCrudUser(View): def get(self, request): id1 = request.GET.get('id', None) employee1 = request.GET.get('employee', None) description1 = request.GET.get('description', None) stakeholder_group1 = request.GET.get('stakeholder_group', None) stakeholder_quadrant1 = request.GET.get('stakeholder_quadrant', None) obj = Stakeholder.objects.get(id=id1) obj.employee = employee1 obj.description = description1 obj.stakeholder_group = stakeholder_group1 obj.stakeholder_quadrant = stakeholder_quadrant1 obj.save() user = {'id':obj.id,'employee':obj.employee,'description':obj.description,'stakeholder_group':obj.stakeholder_group,'stakeholder_quadrant':obj.stakeholder_quadrant} data = { 'user': user } return JsonResponse(data) urls path('ajax/crud/update/', views.UpdateCrudUser.as_view(), name='crud_ajax_update'), html // Update $("form#updateUser").submit(function() { console.log("open"); var idInput = $('input[name="formId"]').val().trim(); var employeeInput = $('input[name="formemployee"]').val().trim(); var descriptionInput = $('input[name="formdescription"]').val().trim(); var stakeholder_groupInput = $('input[name="formstakeholder_group"]').val().trim(); var stakeholder_quadrantInput = $('input[name="formstakeholder_quadrant"]').val().trim(); console.log("create"); if (employeeInput && descriptionInput && stakeholder_groupInput && stakeholder_quadrantInput) { // Create Ajax Call $.ajax({ url: '{% url "polls:crud_ajax_update" %}', data: { 'id': idInput, 'employee': employeeInput, 'description': descriptionInput, 'stakeholder_group': stakeholder_groupInput, 'stakeholder_quandrant': stakeholder_quadrantInput }, dataType: 'json', success: function (data) { if (data.user) { updateToUserTabel(data.user); } } }); console.log("submitted"); } else { alert("All fields must have a valid value."); … -
Customising the template for a form widget.: Can other object properties be passed as attributes?
I have a model form that represents the choices for a ManyToMany field as checkboxes. The two related models are as follows: Passenger Model: class Passenger(models.Model): ... attributes etc ..... trip_addons = models.ManyToManyField(AddOn, blank=True) 'Add on' Model: class Addon(models.Model): name = models.CharField(max_length=254) description = models.TextField() price = models.DecimalField(max_digits=8, decimal_places=2) image = models.ImageField(null=True, blank=True) image_thumb = models.ImageField(null=True, blank=True) image_url = models.URLField(max_length=1024, null=True, blank=True) def __str__(self): return self.name But rather than rendering the default html checkboxes, I would like present the 'addon' options a little more like the 3rd example 'Choose your main dish' in this link, with the picture and short description in addition to the name. I have created my own template to be used by the widget and that works. I just would like to know if can pass the description, image and price data to these templates? forms.py class CustomCheckbox(forms.CheckboxSelectMultiple): """ Creates a custom checkbox select widget that subclasses Django's CheckboxSelectMultiple and customises it with a different template """ template_name = 'bookings/forms/checkbox_select.html' option_template_name = 'bookings/forms/checkbox_option.html'. and in the Meta for my Modelform: widgets = { "trip_addons": CustomCheckbox(), } -
Which is the best way to protect a Django API?
I've deployed a Django API powered with Django Rest Framework with some open endpoints and some Authenticated endpoints using Token authentication. Which is the best way to protect the entry API allowing only to send request from the app frontend team? I was thinking to use an Nginx basic auth, but then the Authorization header is duplicated, so Token auth is not working. -
How Do I Allow Users To Post Links In Django?
I dont need to have the full rich text editor but i want users to be able to post hyperlinks that work so is there a good way to do this in django forms or models? -
element.lable_tag as placeholder in Django
I want to style my user creation Form as a Registration in HTML like I already did in the login. This is my html code: {% csrf_token %} {% for field in registration_form %} <div class="signIn-input-group"> <div class="signInput-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> <input class="signIn-data-input" type="text" placeholder="{{field.label_tag}}" class="form-control" > </div> <div class="signIn-msg"> {% if field.help_text %} <small>{{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p>{{error}}</p> {% endfor %} </div> </div> {% endfor %} This is what the Browser is displaying: <div class="signIn-input-group"> <div class="signInput-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> <input class="signIn-data-input" type="text" placeholder="<label for=" id_first_name"="">First name:" class="form-control" &gt; </div> <div class="signIn-msg"> </div> </div> How can I get rid of the First name:" class="form-control" > display? This also worked for my Login so why not here? best regards. -
How to run python script asynchronously in Django project?
I'm working on project where I scrap job offers and display it on my django app. My scrapper is an indenpendent python script based on requests and selenium. I need to run in Django background on every 5 minutes so it can scrap new data and insert it into my postgres db. Is there any recommended way of handling it ? I thought about running my script via windows scheduler as an external application and just add some psycopg2 things to update my database. I would appreciate any ideas :) -
React/Redux/Django: why this error - getState is not a function?
Im working on token authentication for my posts app (crud functionality) with react, redux and django. Using knox for the authentication. also, i pushed the frontend part of my code to bitbucket for better debugging. link here https://bitbucket.org/Yash-Marmat/frontend-part-of-posts-app/src/master/ i can't find what i missed in my code keep getting this error --> getState() is not a function (see pic below) -
How to form URLs
I am not sure about the exact terminology here. If we have the following URL: https://www.thewhiskyexchange.com/c/331/non-vintage-champagne If I load https://www.thewhiskyexchange.com/c/331/ it would automatically add(redirect to) "non-vintage-champagne". My questions are: What is the exact terminology/the methods that are used here? Is it important to add c/331/ and a redirect(or something similar) instead of a simple domain.com/non-vintage-champagne (or domain.com/products/non-vintage-champagne or something simpler) What exactly is c/331/? Do we need to structure it that way with a letter and number or we can also use simple words or similar? Any advice how to structure the URLs in a website? I am using Django + Vue 3 I am not sure if I am asking the right questions, so any additional information or links would be appreciated -
Django chained dropdown from DataFrame or dictionary
I am new to Django and have to get familiar with it. Problem I have is I need to create a survey type view with chained dropdowns. Tutorial I checked would actually create models (data in db) and jquery, but I don't need to store any data used in dropdowns, only end result. I get JSON data via API, then I use pd.DataFrame to clean it up. Clean data should be used in dropdowns eg Country -> City, without storing it. -
django "view on site" button wrong redirect after changing DB config
I tested adding another DB (holding documents) next to a 'default' DB (for auth etc.) and surprisingly that stopped 'VIEW ON SITE' button (in admin site) to work. So when I am in the admin site: http://localhost:8002/admin/reviewer/document/<uuid_here>/change/ and I click on "VIEW ON SITE" button, it takes me to http://localhost:8002/admin/r/7/<uuid_here>/ and delivers Page Not Found: Page not found (404) Request Method: GET Request URL: http://localhost:8002/admin/r/7/<uuid_here>/ Raised by: django.contrib.contenttypes.views.shortcut Content type 7 object <uuid_here> doesn’t exist You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. whereas previously (single 'default' DB for everything) it correctly redirected me to http://localhost:8002/reviewer/doc/<uuid_here> Any ideas what could the fix be? Here's my code, not sure what could be missing: docs_rev\docs_rev\settings.py DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'auth.sqlite3'), }, 'docs' : { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'docs.sqlite3'), }, } DATABASE_ROUTERS = [ 'reviewer.router.docsRouter', ] docs_rev\docs_rev\urls.py urlpatterns = [ path('admin/', admin.site.urls), path('reviewer/', include ('reviewer.urls')), path('', RedirectView.as_view(url='reviewer/', permanent=True)), path('accounts/', include('django.contrib.auth.urls')), ] docs_rev\reviewer\urls.py urlpatterns = [ path('', views.index, name='index'), path('docs/', views.DocsListView.as_view(), name='docs'), path('doc/<uuid:pk>/', views.DocDetailView.as_view(), name='document-detail'), ] docs_rev\reviewer\models.py … -
Vue - Pass props into vuex store?
I want to pass initial data into my vuex store as a prop from my template. I am using Django templates and loading vue and vuex via script tags. Is this possible? Example: index.html {{ initial_data }} <!-- Sent from django views --> <script src="{% static 'project/js/store.js' %}"></script>. -
Django bulk_update does not work as excpected with django crontab?
Im trying to create a crontab function to automatically update my objects every 1 min. I can see in terminal when debugging that my bulk_update works but they are not saved in my db and i cant figure out whats happening behind. Here is my model: from django.db import models from django_bulk_update.manager import BulkUpdateManager class Products(models.Model): name = models.CharField(max_length=200) stock = models.IntegerField() objects = BulkUpdateManager() class Meta: db_table = "products" verbose_name_plural = "products" def __str__(self): return self.name Crontab configuration settings: CRONTAB_COMMAND_SUFFIX = '2>&1' CRONJOBS = [ ('*/1 * * * *', 'utils.tasks.getStockData') ] -Here is my crontab function where i need to bulk update: def getStockData(self): data = {foo} url = 'bar' try: r = requests.post(url,json=data, headers=headers, timeout=555) alpha = r.json() if r.status_code == 200: products = Products.objects.all() serializer = ProductsSerializer(products, many=True) bulkUpdate = [] for product in serializer.data: productUpdate = { "id":product['id'], "stock": 0 } for alphaProduct in alpha['entiteteTeReja']['artikujGjendjeRi']: if product['name'] == alphaProduct["KODARTIKULLI"]: productUpdate["stock"] = alphaProduct["gjendje"] Products.objects.all().update() bulkUpdate.append(productUpdate) bulk_update(products) except requests.exceptions.HTTPError as http_error: return { 'status': False} And here are my views: from django.http import JsonResponse from rest_framework import status from rest_framework.authtoken.views import APIView from utils.tasks import getStockData from .models import Products from .serializers import ProductsSerializer class SingleProductAPI(APIView): def … -
How do I export my Django project from PyCharm to other PC? Sharing on GitHub did not work
I have to return the office laptop and wish to export my Django project from here, I'm getting some errors while sharing it on GitHub, please guide me through this. -
I how to add multiple users to manytomanyFiled at ones
in book.who_can_see.add(author.id, [2, 3]) 🔴 payload["description"] return an array like [1,2] so it seems i should convert the array to pure numbers with commas like 2,3 but I have no idea how. @api_view(["POST"]) @csrf_exempt @permission_classes([IsAuthenticated]) def add_book(request): print({"request.data": request.data}) payload = request.data user = request.user try: author = Author.objects.get(id=payload["author"]) book = Book.objects.create( title=payload["title"], description=payload["description"], added_by=user, author=author, ) # 🔴 payload["description"] this return an array like [1,2] # book.who_can_see.add(author.id, 2, 3) book.who_can_see.add(author.id, [2, 3]) # it seems i should convert the array to pure numbers with commas like 2,3 book.who_can_see.add(author.id) serializer = BookSerializer(book) return JsonResponse({'books': serializer.data}, safe=False, status=status.HTTP_201_CREATED) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
Filter based on counts django annotate query
I need to filter records based on total counts of records for vehicle_owner_organization_id , i.e if total counts in the collection for vehicle_owner_organization_id are greater than 1, then only go ahead with the following query getting monthly distinct counts. Is there an easy way to do this. Or do I need to run another query to filter. values = ['month', 'city_code'] transacting_users = list(FieldOpsBooking.objects.using( 'analytics').filter(**filter_query).annotate( month=TruncMonth('pick_up_at')).values(*values).annotate( count=Count( 'vehicle_owner_organization_id', distinct=True)).values(*values, 'count')) -
Djnago Background task not working some times
I am using Django background task. but the issues is sometimes its not working properly. task is not completing. some times the function is not getting called. My views.py def process_tasks(): process_tasks_cmd = "python manage.py process_tasks" process_tasks_args = shlex.split(process_tasks_cmd) process_tasks_subprocess = subprocess.Popen(process_tasks_args, shell=True) @api_view(["POST"]) @permission_classes([]) def test(request): process_tasks() fingerprint_sync(6, 5, 8) return Response(result, status=status.HTTP_200_OK) Tasks.py @background(schedule=django.utils.timezone.now()) def fingerprint_sync(EmployeeId,finger_activatn,device_code): """ FingerPrint Synchronization for employee After Creating FingerPrint, Sync the FingerPrint data to all Device Parameters: EmployeeId: pk of employee Returns: Background Process Execute if syncing not done- Data added to Synchronization table """ try: logging.getLogger("info_logger").info("Triggered Fingerprint sync") finger = FingerPrintInfo.objects.filter(~Q(FingerData=None), Employee=EmployeeId, Activation=finger_activatn)\ .order_by('FingerPrintId') logging.getLogger("info_logger").info("Finger data filtered and arranged") emp = Employee.objects.get(pk=EmployeeId) data = { "Employees": { "EmployeeId": emp.EmployeeId, "EmployeeCode": emp.EmployeeCode, "EmployeeName": emp.EmployeeName, "EmployeeStatus": emp.EmployeeStatus }, "FingerPrintId": finger[3].FingerPrintId, "FingerData": bytes(finger[3].FingerData).decode("utf-8") } logging.getLogger("info_logger").info("Corresponding employee identified") emp_device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"]),~Q(DeviceCode=device_code)) for div in emp_device: try: device = Device.objects.get(pk=div.DeviceId) url = protocol + div.DeviceCode + device_api["API4"] logging.getLogger("info_logger").info(url) resp = requests.post(url, json=data) logging.getLogger("info_logger").info(resp) if not resp.text.__contains__('200'): synchronization = Synchronization( Employee=emp, Device=div, SyncType=selection_type["Fingerprint"] ) synchronization.save() except Exception as ex: logging.getLogger("info_logger").info(repr(ex)) logging.getLogger("info_logger").info("Fingerprint not synced in " + div.DeviceCode) except Exception as ex: logging.getLogger("info_logger").info(repr(ex)) Here fingerprint_sync method is not calling every time. and not getting why . could anyone please … -
Python Django *png does not render; Image is broken
I am a novice in programming. I have created an app in django with python programming. I am trying to render some images on my web pages but they appear as broken. I don't seem to have a solution for this. const heartSrcOutline = '/static/network/image/heart_outline.png'; const editSrc = '/static/network/image/edit.png'; const postLimit = 10; var currentPage = 1; var currentFilter = 'all'; And the image is stored in image folder under my app. Please suggest some solution. PS: I tried changing the browser from edge to chrome but to no avail. -
Migration admin.0001_initial is applied before its dependency app.0001_initial on database 'default'
I am trying to make custom made user model for my project in Django. My models.py: class myCustomeUser(AbstractUser): username = models.CharField(default="abcdef", max_length=20, unique="True", primary_key=True) password = models.CharField(default="12345", max_length=20) is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') industry_extrafield = models.TextField(blank=True) class Employee(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='employee_releted_user') industry = models.OneToOneField(Industry, on_delete=models.CASCADE, related_name='employee_releted_industry') employee_extrafield = models.TextField(blank=True) class Inspector(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='inspector_releted_user') inspector_extrafield = models.TextField(blank=True) class Admin(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='admin_releted_user') admin_extrafield = models.TextField(blank=True) in settings.py: AUTH_USER_MODEL = 'app.myCustomeUser' Here admin.site.register is also done in admin.py. Now it shows the following message in the terminal while I try to migrate or makemigrations: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "G:\Python\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "G:\Python\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\Python\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "G:\Python\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "G:\Python\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "G:\Python\lib\site-packages\django\core\management\commands\makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "G:\Python\lib\site-packages\django\db\migrations\loader.py", line 295, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its … -
How do I add non-field related date range to Django admin form
I have a django admin page which is for viewing purposes only and rather than displaying data from the model, it is displaying data for a table linked by a foreignkey to an intermediate table which is linked via a foreign key to my model. I want to apply a date range filter on the third table. class Brand(models.Model): data ... class Organisation (models.Model): data ... brand = models.ForeignKey(Brand, on_delete=models.CASCADE) class DailyStat (models.Model): stat_type = model.CharField(max_lenth=11, choices=STAT_TYPE_CHOICES date = models.DateField() organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE) I then created a change_form.html template in 'templates/admin/brand' which displays the data from DailyStat which I want for the Brand. But I want to be able to filter this so I created a new form class BrandAdminForm(forms.ModelForm): from_date = forms.DateField(widget=admin.widgets.AdminDateWidget()) to_date = forms.DateField(widget=admin.widgets.AdminDateWidget()) class Meta: model = Brand fields = ['id','from_date','to_date'] And within the BrandAdmin definition, referenced it class BrandAdmin(admin.ModelAdmin): list_display = ['name','get_page_views','cqc_brand_id'] ordering = ['name'] search_fields = ['name'] form = BrandAdminForm These fields didn't automatically show in the detail page so I added the following within the form tags of {% block content %} of the change_form.html <table style="width:60%"> <tr> <td>From: </td> <td>{{ adminform.form.from_date }}</td> <td rowspan=2><button type="submit" value="Save and continue editing" class="btn viewsitelink">Filter</button></td> </tr> … -
Check if URL is valid on a Django formset
I have this model: class dateEvent(models.Model): link = models.URLField(null=True, blank=True) link_description = models.CharField(max_length=30, null=True, blank=True) event = models.ForeignKey('Event', on_delete=models.CASCADE) class Event(models.Model): title = models.CharField(max_length=200) [...] Views.py: [...] def event_edit_view(request, id): event = get_object_or_404(Event, id=id) active_user = request.user form_event = EventForm(request.POST or None, instance=event) DateEventFormSet = inlineformset_factory(Event, dateEvent, extra=5, can_delete=True, fields=('event', 'start_date_time', 'venue', 'link', 'link_description'), widgets={ 'venue': s2forms.Select2Widget(), 'link': forms.TextInput(attrs={'placeholder': 'http://'}), 'start_date_time': CalendarWidget(), 'description_link': forms.TextInput(attrs={'placeholder': 'Link description'}), }) form_date_event = DateEventFormSet(request.POST or None, instance=Event.objects.get(id=id), prefix="dateEvent", queryset=dateEvent.objects.filter(event__id=id)) if request.method == "POST": if form_event.is_valid() and request.POST['action'] == 'submit': if form_date_event.is_valid(): form_event.save() form_date_event.save() messages.success(request, 'Event updated successfully. See the <a href="/event-detail/' + str(id) + '">detail page</a>') return redirect('my-events') else: print(form_date_event.errors) elif form_event.is_valid() and form_date_event.is_valid() and request.POST['action'] == 'update': form_event.save() form_date_event.save() else: raise forms.ValidationError([form_event.errors, form_date_event.errors]) context = { 'event': event, 'id': event.id, 'form_event': form_event, 'form_date_event': form_date_event, } return render(request, "events/event-edit.html", context) [...] And template: <tbody id='date_body'> {{ form_date_event.management_form }} {% for formDate in form_date_event.forms %} <tr class="form-row-dateEvent"> <td>{{formDate.venue}}<br> </td> <td>{{ formDate.start_date_time}}</td> <td>{{formDate.link}}</td> <td>{{formDate.id}}{{formDate.link_description}}</td> </tr> {% endfor %} </tbody> How can I check if the URL (in the link field) entered by the user in the form is valid and throw an error if it's not? Of course the code must accept empty values, because it's … -
Json from backend which is built with Django Rest Framework is somehow undefined at frontend, built with React
I'm currently trying to learn the integration of Django Rest Framework and React.js, the former for the backend and the latter for the frontend, by building a simple to-do application. views.py from rest_framework import viewsets from . import models from .serializers import ToDoSerializer, ToDoContainerSerializer class ToDoContainerViewSet(viewsets.ModelViewSet): queryset = models.ToDoContainer.objects.all().order_by('created') serializer_class = ToDoContainerSerializer serializers.py from rest_framework.serializers import HyperlinkedModelSerializer from . import models as todo_model from rest_framework.serializers import ReadOnlyField class ToDoContainerSerializer(HyperlinkedModelSerializer): created_by = ReadOnlyField(source='created_by.id') class Meta: model = todo_model.ToDoContainer fields = ( 'url', 'id', 'created_by', 'todos_name', 'todos_important', 'todos_items_count', ) extra_kwargs = { 'url': { 'view_name': 'todos:todocontainer-detail', }, } models.py from django.db import models from core.models import TimeStampedModel from django.core.validators import MinValueValidator, MaxValueValidator class ToDoContainer(TimeStampedModel): created_by = models.ForeignKey( user_model.User, on_delete=models.CASCADE, related_name="todo_container") todos_name = models.CharField(max_length=50) todos_important = models.BooleanField(default=False) def todos_items_count(self): todo_items = len(self.todo.all()) return int(todo_items) def __str__(self): return str(self.todos_name) I built the views, serializers, models like above, and it seemed api generated properly like the below. And I tried to get the json of the above to frontend by using the axios module like the below. import React from 'react'; import axios from 'axios'; import ToDoCard from './ToDoCard'; class ToDoLists extends React.Component { state = { isLoading: true, toDos: [] }; getToDos = async …