Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query clause be included if data exist else be excluded
I have a query which I want to perform. If the query variable has some things in them the query should be presented. But if it does not have anything inside of them then it should be left blank Modelname.objects.raw("select * from tab1, tab2, tab3 where tab1.id=tab1.tb2_id and tab3.id=tab1.tb3_id and CASE %s WHEN None THEN #This place is basically empty ELSE tab1.name=%s END and CASE %s WHEN 0 THEN #This place is also basically empty ELSE tab1.year=%s END", [user_name,user_name,digit,digit]) -
Django fetching data with HttpOnly cookie says 401 (Unauthorized)
I have been trying to use HttpOnly cookie with Django for two days but couldn't solve it yet. I tried adding all of these to my settings.py file SESSION_COOKIE_HTTPONLY=True SESSION_COOKIE_PATH = '/;HttpOnly' LANGUAGE_COOKIE_HTTPONLY=True CSRF_COOKIE_HTTPONLY=True My home.html file fetch('http://127.0.0.1:8000/api/books/', { method: 'POST', mode: 'same-origin', credentials: 'include' // Do not send CSRF token to another domain. }).then(function(response) {response.json()}).then( event=>console.log(event) ) My api is working and i am signed in but it still gives me "401 (Unauthorized)" response. I searched in google for days and still couldn't solve it. I think i am missing something but don't know what -
How to connect Celery with redis?
I have taken a free trial for Redis and it gave me an endpoint with a password. I haven't done anything with Redis or celery before so I really don't have any idea how it works. From the Docs of Celery everyone connects to the local host but how can I connect to this endpoint? CELERY_BROKER_URL='redis://localhost:6379', CELERY_RESULT_BACKEND='redis://localhost:6379' What should I replace this with? Where should I give the password? My endpoint looks something like this: redis-18394.c252.######.cloud.redislabs.com:18394, Should I add the password at the end of this after a / ? -
Djagno: form.is_valid() error, but only after "if request.method == 'POST'"?
When I print(formexam) BEFORE the "if request.method == 'POST'", it shows the appropriately filled out form items (the exam was created earlier, now I'm just updating it to make changes as desired). However, when I print(formexam) AFTER "", it shows the form fields (at least several of them, I didn't look at every single one) to be empty. What makes that happen? Also, a very very similar views.py function ("changeExam", bottom of this post) works just fine. Thank you! views.py def updateExam(request, pk): exam = Exam.objects.get(id=pk) formod = form_od.ODForm(instance=exam.od) formos = form_os.OSForm(instance=exam.os) formexam = ExamForm(instance=exam) print(f'The errors are: {formexam.errors}') if request.method == 'POST': formexam = ExamForm(request.POST, instance=exam) print(f'The errors are: {formexam.errors}') formod = form_od.ODForm(request.POST, instance=exam.od) formos = form_os.OSForm(request.POST, instance=exam.os) if formod.is_valid() and formos.is_valid(): print("these are valid") if formexam.is_valid(): print("so is this one.") else: print("Exam form not valid.") Results of hitting submit button: The errors are: The errors are: <ul class="errorlist"><li>doctor<ul class="errorlist">.<li>This field is required.</li></ul></li><li>examtype<ul class="errorlist"><li>This field is required.</li></ul></li></ul> these are valid Exam form not valid. However, this very similar one works: views.py def changeExam(request, pk): exam = Exam.objects.get(id=pk) form = ExamForm(instance=exam) if request.method == 'POST': form = ExamForm(request.POST, instance=exam) if form.is_valid(): print(form) form.save() -
How do you obtain the username in models, without sending the username from views?
I'm trying to include in a models class the username. When I send username from views, ie: in views.py def listing(request, name): return render(request, "auctions/listing.html", { "user": request.user.get_username() }) The above, makes it so that I'm no longer signed in when I visit listing.html Is there a way to return the user without changing the username on this page? The other thought I had was is there a way to just directly access the current user via models without returning anything to models from views. But the following returns errors, that models has no attribute... user = models.get_username() When I read the documentation here https://docs.djangoproject.com/en/3.2/ref/contrib/auth/ I thought it allows me to call get_username() from models as I'm doing above. Thanks -
In this setup, how do I inner join Product, ProductAttributes, and ProductAttributesValue? [Django models & view]
The first line of views.py is the Products queryset that I want to inner join with the next line of the views.py (the inner join of ProductAttributes and ProductAttributesValue) # models.py class Product(models.Model): title = models.CharField(max_length=255) class ProductAttributes(models.Model): name = models.CharField(max_length=255) class ProductAttributesValue(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) attribute = models.ForeignKey(ProductAttributes, on_delete=models.RESTRICT) # views.py - just code fragments Product.objects.filter(categories=self.category) # Products only in selected category products_att = ProductAttributes.objects.filter(productattributesvalue__isnull=False) # Inner join of ProductAttributes and ProductAttributeValues - sent to context in view products_att = products_att.values("id", "name", "productattributesvalue__value") context['attribute_values'] = products_att -
(index):551 Uncaught ReferenceError: validateText is not defined
Just wondering if anyone could help me troubeshoot this error? I am currently working on building a chat application within Django. When I try to send a message within my chat, I receive the following error within the console: (index):551 Uncaught ReferenceError: validateText is not defined Here's the code within my template file from where the error seems to be originating from: var msgP = document.createElement("p") msgP.innerHTML = validateText(msg) msgP.classList.add("msg-p") div1.appendChild(msgP) Just to add in here - My knowledge of JQuery isn't the best, so I do apologise if this comes across as a silly question! Any suggestions would be welcome! :-) -
How to remove tags from RichTextField and calculate words saved in RichTextField Django?
Below is my model I want to calculate the word count in the RichTextField , I tried len(blog.content.split()) but the problem with this is that it doesn't removes the tags and calculates them too, whereas I want only the word count and not tags like <img> , <p> etc. title = models.TextField( verbose_name="title", blank=True ) tagline = models.TextField( verbose_name="tagline", blank=True ) content = RichTextField( verbose_name="content", blank=True ) image = models.TextField( verbose_name="image", blank=True )``` -
Can I concatenate two fields in a Django model to create a third field that will be the primary key for the Model?
I am trying to create a model in Django that will be used to hold records for a review form I am creating. This model will have numerous fields but at the moment I am concentrating on the primary key determination. I have two fields, "claim number" and "review type" that I would like to concatenate as "claim number | review type" as a string to create a third field in the model called "review name". I understand concatenation as I've done this to define full name on other fields using the first and last name fields in the model. Here's my model currently: class QualityReview(models.Model): claim_number = models.CharField(max_length=40) review_type = models.ForeignKey(ReviewType, on_delete=models.CASCADE) def ReviewName(self): return self.claim_number + " | " + self.review_type Is it possible to use that ReviewName def in a field called review_name? -
django form field queryset to selected user
I have a list of users, when i click an user a form is created with user, area and room fields. I want to have the user field to be the one that was created and to be non editable. My implementation sets the initial data user to be the one that was clicked, but I can edit it and I get all users. If I disable field, then it is not counted when form is saved, so I get the error that the object cannot be saved because user is not provided. # user detail view class UserDetailView(LoginRequiredMixin, FormMixin, DetailView): model = TbUser form_class = TbPeopleEntranceRightForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() context['user_terminal_permissions'] = TbTerminalPermission.objects.filter( user=super().get_object()) context['user_entrance_rights'] = TbPeopleEntranceRight.objects.filter( user=super().get_object()) context['people_entrance_rights'] = TbPeopleEntranceRight.objects.all() context['rooms'] = TbRoom.objects.all() context['form'] = TbPeopleEntranceRightForm( initial={'user': self.object}) return context def get_success_url(self): return reverse_lazy('user-detail', kwargs={'pk': self.object.id}) def get_form_kwargs(self): kwargs = super().get_form_kwargs() obj = self.object user = TbUser.objects.filter(id=obj.id) #kwargs.update({'user': user}) kwargs['user'] = user return kwargs def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() print("posting") if form.is_valid(): print("valid") form.save() return self.form_valid(form) else: print("invalid") print(form.errors) return self.form_invalid(form) # form class TbPeopleEntranceRightForm(forms.ModelForm): # user = forms.ModelChoiceField( # queryset=TbUser.objects.none(), required=False) area = forms.ModelChoiceField( queryset=TbArea.objects.none(), to_field_name="name") … -
TimeField returning None in Django
I have an existing database I need to pull data from the timestamp field in Django. I created the Django model as a TimeField, but when I query the data I get 'None' instead of the data in the timestamp field. From my model class: (there is more in the model, I just condensed this for readability) class Report(models.Model): upload_time = models.TimeField() date = models.CharField(max_length=9) @staticmethod def get_reports(**query): reports = Report.objects.order_by('date').filter(query) for report in reports: print(report.upload_time) In my views.py I have a method that checks for the date I am looking for to pull all reports from that date. The database saved the date as a string, so I get that ok, then just turn it into a datetime object and call my get_reports method by passing the date into it. It works to get everything from the report except the timestamp. What am I missing? -
How to make a Timer exactly 30 seconds from created date Django
I need to make an operation only available in 30 seconds, and then it expires. I Have this model: (operation) status = CharField(max_length=10, default="INI") created_at = DateTimeField(auto_now_add=True) account = ForeignKey(Account, null=False, on_delete=CASCADE) metadata = models.JSONField(default=dict) external_ref = CharField(max_length=128) expires_at = DateTimeField(default=timezone.now()+timezone.timedelta(seconds=30)) I wanna be able to create in the expires_at field, a timestamp with exactly 30 seconds from the created_at Date, it is like a timeout function, but when I run the test: def test_timeout_is_30_seconds(self): print(self.operation.created_at) timer = self.operation.created_at + timezone.timedelta(seconds=30) print(timer) self.assertEqual(self.operation.expires_at, timer) it fails with this message: AssertionError: datetime.datetime(2021, 6, 22, 19, 0, 42, 537490, tzinfo=<UTC>) != datetime.datetime(2021, 6, 22, 19, 0, 45, 844588, tzinfo=<UTC>) I dont know if I need to make an external function or method inside the class or directly in the View, but I would prefer this default behavior in the models so I dont need to worry about setting expiry dates I would be very grateful if you could help me solve it! :D any tips and information is appreciated -
main.js:95 WebSocket connection to 'wss://website' failed :(
I have tried to make a simple video calling app using Django and WebRTC. I tried running this on localhost and it works well, but I tried hosting it on a website hosting platform and now it doesn't work. I surfed through many websites to correct this, but failed. I haven't used Redis server. Here are some required files: asgi.py import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack import chat.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myProject.settings') application = ProtocolTypeRouter({ "https": get_asgi_application(), # Just HTTP for now. (We can add other protocols later.) "websocket": AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ) }) settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '****' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['my hosting website url'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat', 'channels', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myProject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
Why am I getting an error with Django Rest Framework GenericViewSet?
I have been trying to figure out why I am having trouble with getting a list view from a GenericViewSet. It only happens on the list view. Other views seem to be okay. The error I get is this: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "api:user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. [22/Jun/2021 18:10:29] "GET /api/users/ HTTP/1.1" 500 183983 I have tried removing lookup_field = "username" and it still does the same thing. I'm just at a loss trying to figure out the cause of my problem here. Any help would be appreciated. Here is the model: # Override UserManager and allow login with both username and email address class CustomUserManager(UserManager): def get_by_natural_key(self, username): return self.get( Q(**{self.model.USERNAME_FIELD: username}) | Q(**{self.model.EMAIL_FIELD: username}) ) class User(AbstractUser, TimeStampedModel): class Meta(object): unique_together = ('email',) email = EmailField(_('email address'), unique=True, blank=True, max_length=255) phone_number = PhoneNumberField(_('phone number'), blank=True) address = CharField(_("street address"), blank=True, max_length=255) city = CharField(_("city"), blank=True, max_length=255) state = USStateField(_("state"), blank=True) zip = USZipCodeField(_("ZIP code"), blank=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'last_name', 'email'] # for allowing both username and email login objects = … -
How to limit query depth in strawberry-graphql (Django implementation)?
I have a nested structure in my strawberry-graphql schema resolver implementation. Any suggestion on how I can limit query depth in strawberry-graphql (Django implementation)? -
Updating a model using a dynamic serializer in Django Rest Framework
I set up a serializer that is able to dynamically serialize the desired fields as specified in the Django Rest Framework docs. class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) >>> class UserSerializer(DynamicFieldsModelSerializer): >>> class Meta: >>> model = User >>> fields = ['id', 'username', 'email'] >>> >>> print(UserSerializer(user)) {'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'} >>> >>> print(UserSerializer(user, fields=('id', 'email'))) {'id': 2, 'email': 'jon@example.com'} How would I set up the view to allow editing by post method? I tried something like this. views.py def post(self, request, pk, format=None): fields = form_fields_map[request.data['form_info']['index']]['main_info'] user = User.objects.get(pk=pk) user_serializer = UserSerializer(customer, request.data['main_info'], partial=True, fields=fields) if customer_serializer.is_valid(): customer_serializer.save() return Response(customer_serializer.data) else: return Response(status=status.HTTP_422_UNPROCESSABLE_ENTITY) but I get this error. `update()` did not return an object instance. -
There are duplicate fields in 'fieldsets[4][1]' Django
Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/stevek/.local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/stevek/.local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/stevek/.local/lib/python3.9/site-packages/django/core/management/base.py", line 469, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'accounts.admin.CustomUserAdmin'>: (admin.E012) There are duplicate field(s) in 'fieldsets[4][1]'. System check identified 1 issue (0 silenced). ^C% ~/Projects/Python/CRAFTMINE/web │ main !8 ?1 ✔ │ 25m 24s │ 10:44:26 ~/Projects/Python/CRAFTMINE/web │ main !8 ?1 python3 manage.py runserver INT ✘ │ 10:44:26 Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/stevek/.local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/stevek/.local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/stevek/.local/lib/python3.9/site-packages/django/core/management/base.py", line 469, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'accounts.admin.CustomUserAdmin'>: (admin.E012) There are duplicate field(s) in 'fieldsets[4][1]'. ``` I got this error but don't know what's wrong. My admin.py shows from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import … -
Any equivalent material for Django like this for rails: https://rebuilding-rails.com/
Rebuilding Rails is a fantastic resource to really be an expert on the rails framework. It basically teach you how to create a tiny, toy version of rails, so you can see how the framework works from the inside out. Anyone knows of a similar resource for Django? -
"user_id" is empty when setting MyForm(data=data) (Django)
I have the following model #models.py class MyModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,null=True) link = models.URLField(max_length=2048) date_added = models.DateTimeField(default = timezone.now) used = models.BooleanField(default = True) and my form class MyModelForm(forms.ModelForm): class Meta: model = Wishlist exclude = [ "user","date_added" ] when I in my view try to "manually" create an instance and save it, the "user_id" in my database is NULL #views.py def AddLink(request): user = request.user instance = MyModel(user=user) if request.method == "POST": form = MyModelForm(request.POST,instance = instance) if form.is_valid(): link = form.instance.wishlist used = form.instance.discount_pct #some util function to do some stuff res = my_util_func(link,api_key) for used, link in zip(res[0],res[1]): data = {"link":link,"used":used} form = MyModelForm(data=data) form.save() context = { "results":res} return render(request, "discounttracker/myhtml.html",context=context) I have tried changing data to data = {"link":link,"used":used,"user":user} and data = {"link":link,"used":used,"user_id":user} but it is still empty. How can I add the user here? -
Django factories import classes from each other error
I had 2 factory classes: 1. from factories.data import BFactory class AFactory(factory.DjangoModelFactory): class Meta: model = A full_name = factory.Sequence(lambda n: 'Full name %s' % n) label = factory.Sequence(lambda n: 'lable-%s' % n) content = factory.SubFactory(BFactory) from factories.data import AFactory class BFactory(factory.DjangoModelFactory): class Meta: model = B full_name = factory.Sequence(lambda n: 'Full name %s' % n) label = factory.Sequence(lambda n: 'lable-%s' % n) content = factory.SubFactory(AFactory) When i run my code, seems like i got a circular imports, because 2 classes import each other. Do you have any suggestion ? Thanks -
Appending the logged-in User to Django REST framework POST model update
I've tried to follow this answer Django Rest Framework - Post Foreign Key but can't get it to work. A user POSTs the creation of an Event, but I cannot figure out how to configure the serializers to append the User foreign key constraint to associate Event with the User. models.py class Event(models.Model): created = models.DateTimeField(editable=False, auto_now_add=True) modified = models.DateTimeField(auto_now_add=True) zone = models.CharField(max_length=1024, null=True) start_datetime = models.DateTimeField(null=True) runtime_seconds = models.IntegerField(default=60, null=True) user=models.ForeignKey(User, on_delete=models.CASCADE,default=None,null=True) def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.created = timezone.now() self.modified = timezone.now() return super(Event, self).save(*args, **kwargs) def __str__(self): return str(self.id) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ['zone','start_datetime','runtime_seconds','user'] def to_representation(self, instance): self.fields['user'] = UserSerializer(read_only=True) return super(EventSerializer, self).to_representation(instance) views.py This feels janky--I making dog out of tee'ing up the merged event and user data but still not sure why it doesn't work. class EventCreateView(APIView): permission_classes = (IsAuthenticated,) serializer_class = EventSerializer def post(self, request): user_serialized = UserSerializer(request.user) payload={ **request.data, **user_serialized.data} pprint(payload) serializer_event = EventSerializer(data=payload) if serializer_event.is_valid(): pprint(serializer_event.validated_data) serializer_event.save() return Response(serializer_event.data, status=status.HTTP_201_CREATED) pprint(serializer_event.errors) return Response(serializer_event.errors, status=status.HTTP_400_BAD_REQUEST) Example POST {"id":"fc01ef4c-c05f-4416-ba10-dd0d779abddb","zone":"278c6def-beab-49a2-9876-ce3eef35a16e","start_date":"2021-06-10T06:00:00.000Z","start_time":"1:30 am","start_datetime":"2021-06-10T07:30:00.000Z","runtime_seconds":"333"} Output--missing user_id OrderedDict([('zone', '278c6def-beab-49a2-9876-ce3eef35a16e'), ('start_datetime', datetime.datetime(2021, 6, 10, 1, 30, … -
difference between django and django rest framework
Okay I just finished a YouTube course on Django tutorials and i more or less understand Django to an extent. Now the issue is Django rest framework. Google says its used to create APIs but i just dont get it. if the Django framework can be used to create web applications then what can Django rest framework be used for in terms of web application development. By this question, i mean that is Django framework all you need to create a web app or do you need to add it to the rest framework?. What is the connection between a web app and an API?. Does a web app need an API to function?. I'll appreciate a simple explanation of the difference between the two and and how they connect to each other. Thanks. -
Next Auth - OAUTH_GET_ACCESS_TOKEN_ERROR
I'm trying to implement oauth in my next.js app. for backend I'm using Django ODIC Provider and Next Auth for the front-end. but I'm getting an error: { "error": "invalid_grant", "error_description": "The provided authorization grant or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client" } How can I fix this ? I have created a file named: [...nextauth].js in /api/auth/ and added my custom provider. Here's how my env looks like: NEXTAUTH_URL = http://localhost:3000 CLIENT_ID = 466647 CLIENT_SECRET = 079e7fe518e245cb316701faa19ec463c0073fba25d1e51c2db996ab SCOPES = openid profile email and [...nextauth].js: import NextAuth from 'next-auth' export default NextAuth({ providers: [ { id: "pullstream", name: "Pullstream", type: "oauth", version: "2.0", scope: process.env.SCOPES, params: { grant_type: "authorization_code" }, accessTokenUrl: "https://accounts.dev.pullstream.com/api/openid/token/", requestTokenUrl: "https://accounts.dev.pullstream.com/api/accounts/login/", authorizationUrl: "https://accounts.dev.pullstream.com/api/openid/authorize/", profileUrl: "https://accounts.dev.pullstream.com/api/accounts/profile/", async profile(profile, tokens) { console.log(profile, tokens) }, clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET } ], }) -
Scraping Bing or Google in Django
I am building a search engine for only men's apparel in django, so I need help in scraping Bing or Google and using custom querying to get only men's apparel results. body { font-size: 10pt; font-family: arial, sans-serif; } a { text-decoration: none; } a:hover { text-decoration: underline; } button { font-weight: bold; font-family: arial; } /* Top Toolbar */ .top-toolbar { height: 50px; } .top-toolbar nav { float:right; margin: 7px 21px; } .top-toolbar nav a { margin: 3px 6px; color: #404040; } .top-toolbar nav a:hover { color: #111111; } .top-toolbar nav button { padding: 7px 12px; border-radius: 2px; /* background-color: #4585F1;*/ background-image: -moz-linear-gradient(top left, #4084F9 0%, #4585F1 100%); background-image: -o-linear-gradient(top left, #4084F9 0%, #4585F1 100%); background-image: -webkit-gradient(linear, left top, right bottom, color-stop(0, #4585F1), color-stop(1, #0097DE)); background-image: -webkit-linear-gradient(top left, #4084F9 0%, #4585F1 100%); color: white; border: 1px darkblue; font-size: 9.5pt; } .top-toolbar nav button:hover { box-shadow: 1px 1px 0 rgba(0,0,0,.2); } .top-toolbar nav img { margin: 0 7.5px; height: 22px; position: relative; top: 7px;} /* End of Top Toolbar */ /* Search */ .search { text-align: center; clear: both; margin: 11% 0 0 0; } .logo { max-width: 21%; margin: 0 auto; } .search img { margin-bottom: 3%; max-width: 100%; … -
How to model a database to a Dynamic HTML Form?
I'm trying to make a POST REQUEST to link Dynamic HTML form (when you push the add button, will add another textbox, like in the photo) into Django's default database. Right now I have the following issue, every time I submit data, it only saves the last row. How is the best way to model database and HTML form to save that data ? Any documentation is appreciate it ! Infraestructura.html {% extends "Portafolio/layout.html" %} {% load static %} {% block scripts %} <script src = "{% static 'Portafolio/scriptinfra.js' %}" type="text/javascript"></script> {% endblock %} {% block content %} <form action= "{% url 'infraestructura' %}" method="POST" class="form mt-5" id="infra"> {% csrf_token %} <h1>Factibilidad Técnica y Operativa</h1> <h2>Análisis de Infraestructura</h2> <main class="container"> <section class="row"> <div class="col-lg-4 mb-2"> <input name='Infraestructura' class="form-control" type="text" placeholder="Infraestructura"> </div> <div class="col-lg-4 mb-2"> <input name='Tiempo' class="form-control" type="text" placeholder="Tiempo"> </div> <div class="col-lg-4 mb-2"> <input name='Costo' class="form-control" type="text" placeholder="Costo Mensual"> </div> </section> </main> <nav class="btn-group"> <button id='add' class='btn btn-success' type='button'> <i class="fa fa-plus-square"></i> Añadir </button> <button id='rem' class='btn btn-danger' type='button'> <i class="fa fa-minus-square"></i> Eliminar </button> </nav> <!-- Submit buttom--> <div class="d-grid gap-2 mt-3"> <input type="submit" class="btn btn-lg btn-primary"> </div> </form> {% endblock %} models.py from django.db import models # Create your …