Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update new on same forms
Hi I would like to update a form with unknown field with a second form. Let me explain: For example: I have a first form with: Date ,Type, Amount Then I have a second form with: Date ,Type, Score I would like all the entries in the DB that are missing Score to be shown as autofill form in a views. At the moment, I have model two models that I join later on to get what I want. Is there a way of doing this to facilitate the data entry? Cheers I am working on Python 3.6 and Django 2.0.3. -
Display singular and plural headers on appropriate context
I'd like to display the plural accordingly in template {% if page.paginator.count <= 1 %} <h3 style="display: inline">{{ page.paginator.count }} Comment</h3> {% else %} <h3 style="display: inline">{{ page.paginator.count }} Comments</h3> {% endif %} Since it's a everyday task,I wonder if it could be achieved in a straightforward way such as template-filer? -
Modify objects returned by haystack SearchQuerySet
I've got a site which stores results in a django-haystack search index and the objects in this search index can be associated with a user. If at the time the user becomes associated with a result they have certain profile data, that data is stored against the result in the search index. However if the user updates their profile after associating themselves with results, the search index never knows about the updated profile data. Therefore I'm looking for an efficient way to update the objects in the search index with the updated profile data. My current solution is to fire a celery task when certain profile data is changed, then the simple thing to do would be to save all the associated results because haystack would then update the index. signals.py @receiver(post_save, sender=UserProfile) def post_save_user_profile(sender, instance, **kwargs): """ Sync results with search index """ # Privacy Settings if 'avatar' in kwargs['update_fields']: update_results.delay(instance.pk) tasks.py @celery_app.task(bind=True) def update_results(self, user_profile_id, **kwargs): """ Get celery to sync results with the search index """ results = Results.objects.filter(owner=user_profile_id) for r in results: # sync any data with the search index aka avatars. r.save() I don't like this however as it feels like you should just be … -
SQL/Django: Modeling an organization with employee, managers, teams, and departments
I am very new to database design and work in general. I am trying to structure my databases in a way that makes sense. Here are my needs: There will be employees with different attributes Some employees will be managers There will be teams with team leads There will be departments with department leads Teams should only be a part of 1 department Departments can have many teams I am looking for a way to logically organize this. I have tried having the following tables, but I had an issue with teams being able to be in multiple departments (but teams should only be able to be in one department -- i.e. development can't be in engineering and marketing departments, but only one): Users ----------- Generic login/personal information Departments ------------- PK: department FK: department_lead to users table Teams ------------- PK: team FK: team_lead to users table FK: department Employees ------------ PK: employee_id FK: team FK: department FK: manager Any ideas on how to improve this so I can effectively do what I am looking to do? Thanks -
Ajax makes request to unexpected url
I am using Django Rest Framework, django-filters and Datatables to filter and present data on a table. My problem is that the url that the ajax makes the call to is not what I expected. Instead of something like: /?date_from_day=8&date_from_month=5&date_from_year=1960&date_to_day=11&date_to_month=8&date_to_year=2018 I get something like: ?0=d&1=a&2=t&3=e&4=_&5=f&6=r&7=o&8=m&9=_&10=d&11=a&12=y&13=%3D&14=8.... which in reality is ?date_from_day=8 The above is the gist of the situation and below I will present some code and explain what is going. More details and code We have a drf view that through a filter gives back the desired data. It's a little hacky on filtering and I have overridden the list method because it is needed for Datatables and server-processing. class FilteredProductsListAPIView(LoginRequiredMixin, ListAPIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = ProductFilter def get_queryset(self): qs = Product.objects.filter(user=self.request.user).order_by("-timestamp") date_from_day = self.request.query_params.get("date_from_day", None) date_from_month = self.request.query_params.get("date_from_month", None) date_from_year = self.request.query_params.get("date_from_year", None) if date_from_day and date_from_month and date_from_year: date_from = datetime.date(int(date_from_year), int(date_from_month), int(date_from_day)) qs = qs.filter(date__gte=date_from) # some more ugly code return qs def list(self, request, *args, **kwargs): queryset = self.get_queryset() total_count = queryset.count() draw = int(self.request.GET["draw"], 0) start = int(self.request.GET["start"], 0) length = int(self.request.GET["length"], 0) queryset = queryset[start:start+length] serializer = ProductSerializer(queryset, many=True) result = … -
Having trouble using JWT with a custom User model in Django
I've started a new Django project and like the documentation recommends I've created a custom user model just in case it's needed and made sure to set AUTH_USER_MODEL in settings. from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass I notice that when you do this you cannot run python manage.py makemigrations you actually have to specify the app the custom user model is in python manage.py makemigrations <appname>. Once I do that I'm able to start the server. I followed this post to integrate JWT into my new project: Django React JWT Without the custom user model the post works great but once I add in a custom user model I start getting these errors: Traceback (most recent call last): File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "/Users/repos/api/core/views.py", line 30, in … -
Django - NoReverseMatch - Reverse for 'contextual' with keyword arguments '{'api': '9933124422'}' not found
Html {% for well_instance, values in well_info %} <tr> {% for value in values %} <td><a href="{% url 'eric_base:contextual' api=well_instance.api %}">{{ value }}</a></td> {% endfor %} </tr> {% endfor %} views.py class WellList_ListView(ListView): template_name = 'well_list.html' context_object_name = 'well_info' model = models.WellInfo def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # get string representation of field names in list context['fields'] = [field.name for field in models.WellInfo._meta.get_fields()] # nested list that has all objects' all attribute values context['well_info_values'] = [[getattr(instance, field) for field in context['fields']] for instance in context['well_info']] # includes well instance objects & values string list for each well context['well_info'] = zip([instance for instance in context['well_info']], context['well_info_values']) return context app/urls.py app_name = 'eric_base' urlpatterns = [ re_path(r'^(?P<api>[\w-]+)/$', base_views.ContextualMainView.as_view(), name='contextual'), ] models.py # Create your models here. class WellInfo(models.Model): api = models.CharField(max_length=100, primary_key=True) well_name = models.CharField(max_length=100) status = models.CharField(max_length=100) phase = models.CharField(max_length=100) region = models.CharField(max_length=100) start_date = models.CharField(max_length=100) last_updates = models.CharField(max_length=100) def __str__(self): return self.well_name Error Message NoReverseMatch at /well_list/ Reverse for 'contextual' with keyword arguments '{'api': '9933124422'}' not found. 1 pattern(s) tried: ['well_list\\/contextual/$(?P<api>[\\w-]+)/$'] I really don't understand what's wrong with this. Judging from the fact that I get a non-null value for {'api': '9933124422'}, I think I correctly injected the dictionary … -
What is the most efficient way to create a DB record without knowing if it already exists?
The situation is that a DB must be populated but it is unknown whether the records already exist or not. I consider three techniques to accomplish this task but wonder which is the most efficient. 1. Model.objects.get_or_create() 2. Model.objects.update_or_create() 3. if not Model.objects.filter().exists(): Model.objects.create() According to the Django docs, techniques 1 and 2 internally use EAFP (Easier to ask for forgiveness than permission), while Technique 3 uses the less favored LBYL (Look before you leap). However, technique 3 avoids retrieving or saving (without modification) the object if it already exists. Follow up: Does the correct method change in the cases where there are a majority of already existing records vs a majority of non-existing records? -
DRF Serializer nested objects (update/create)
I write vote app project using Django rest framework. It has two models question and nested answer model. I need to write a serializer for the question where I can create answers. How can I properly do create and update methods? serializer.py class AnswerSerializer(serializers.ModelSerializer): class Meta(object): model = Answer fields = ('id', 'answer', 'votes_count') class QuestionSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField() answers = AnswerSerializer(many=True) class Meta(object): model = Question fields = ('id', 'question', 'answers', 'total_votes', 'user') def create(self, validated_data): answers_data = validated_data.pop('answers') with transaction.atomic(): question = Question.objects.create(**validated_data) for answer_data in answers_data: Answer.objects.create(question=question, **answer_data) return question views.py class QuestionViewSet(ModelViewSet): serializer_class = QuestionSerializer queryset = Question.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) def perform_update(self, serializer): serializer.save(user=self.request.user) POST request { "question":"first question", "answers": [{"answer":"first answer"}, {"answer":"second answer"}] } -
django aggregate sum of subgroup maximums
I have the following simplified setup in Django, using MySQL: class Category(models.Model): name = models.CharField(max_length=255) class MyTable(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE) date = models.DateField() amount = models.IntegerField() class Meta: unique_together = ['category', 'date'] And a query set comprised of the following sample data for MyTable: date category_id amount 2017-12-01 3 2 2018-01-01 1 100 2018-02-01 1 50 2018-03-01 2 2000 2018-04-01 2 4000 2018-05-01 3 2 2018-06-01 3 1 What I ultimately want is a way to get the sum of the amounts corresponding to the latest date for each category. To illustrate: The latest date for category_id 1 is 2018-02-01, where the amount is 50; The latest date for category_id 2 is 2018-04-01, where the amount is 4000; The latest date for category_id 3 is 2018-06-01, where the amount is 1; 50 + 4000 + 1 = 4051 I'm trying to figure how to get the value 4051 through an aggregate call to this queryset. I've tried every combination of "values", "annotate" and "aggregate" I could think of and nothing gets the desired result. The following gets me the latest date for each category, but every time I try to get the sum of the corresponding amounts, it calculates … -
Django app on Heroku (DATABASE_URL with specific Postgres schema)
So today was the big day...I devoted today to migrating my app from my local environment to Heroku. It's been frustrating and fun at the same time...but now I'm very stuck. I have a schema called DCPViews which I want the DB connections to default to when running queries. I've read all the relevant tutorials / posts / tips and here's where I am: settings.py import django_heroku import dj_database_url ... DATABASES = {} DATABASE_URL = 'postgres://<user>:<pass>@<host>:<port>/<db_name>?currentSchema=DCPViews' DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) # # Old database config # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME': config('DB_NAME'), # 'USER': config('DB_USER'), # 'PASSWORD': config('DB_PASSWORD'), # 'HOST': config('DB_HOST'), # 'OPTIONS': { # 'options': '-c search_path=' + config('DB_SCHEMA_NAME') # default schema name # }, # } # } # Configure Django App for Heroku django_heroku.settings(locals()) I've tried everything to get Heroku to use the correct DATABASE_URL, but no luck. I don't have permissions with my Heroku plan to create new roles nor set a search path. It also won't let me export DATABASE_URL manually and doesn't seem to accept the value I pass in the settings.py file. The heroku config -s always returns the same DATABASE_URL value. Everything works fine in my … -
How do i override django rest_auth login serializer to get Custom User Model data in response instead of just Token "Key"?
I am very new to working with django. i have developed an API for user Registration, Login and Logout with Django Rest-Auth Using Custom User Model extending AbstractUser. When i call POST on Login API endpoint using credential, i get token in response, Please check below screenshot. POST on Login API Endpoint I need to get Logged in User data as well in response. I have read somewhere that it might work if i override django rest_auth login serializer. I have no idea how do i do that! Any help would do. TIA. -
Django - Reverse for 'contextual' with keyword arguments '{'api': ''}' not found
models.py from django.db import models from django.urls import reverse # Create your models here. class WellInfo(models.Model): api = models.CharField(max_length=100, primary_key=True) well_name = models.CharField(max_length=100) status = models.CharField(max_length=100) phase = models.CharField(max_length=100) region = models.CharField(max_length=100) start_date = models.CharField(max_length=100) last_updates = models.CharField(max_length=100) def __str__(self): return self.well_name views.py class ContextualMainView(TemplateView): template_name = 'contextual_main.html' class WellList_ListView(ListView): template_name = 'well_list.html' context_object_name = 'well_info' model = models.WellInfo def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # get string representation of field names in list context['fields'] = [field.name for field in models.WellInfo._meta.get_fields()] # nested list that has all objects' all attribute values context['well_info'] = [[getattr(instance, field) for field in context['fields']] for instance in context['well_info']] return context html <thead> <tr> {% for field in fields %} <th>{{ field }}</th> {% endfor %} </tr> </thead> <tbody> {% for well in well_info %} <tr> {% for value in well %} <td><a href="{% url 'eric_base:contextual' api=well.api %}">{{ value }}</a></td> {% endfor %} </tr> {% endfor %} </tbody> app/urls.py from django.urls import re_path, include from django.contrib.auth import views as auth_views from eric_base import views as base_views app_name = 'eric_base' urlpatterns = [ re_path(r'^(?P<api>\d+)/$', base_views.ContextualMainView.as_view(), name='contextual'), ] In my models.py, I set api as my primary key, and want to use api as a unique url identifier, … -
django-celery-beat not creating tables
I've installed django-celery-beat via: pip install django-celery-beat Installed the app on my django project INSTALLED_APPS = [ ... 'django_celery_beat', ... ] ran migration via python manage.py migrate django-celery-beat I don't get any error message, and I can go to my django admin site and I see the Periodic Task section with Crontab,Intervals, Periodic Tasks, and Solar events sections. However when I click into any of them I get a message about the table not existing. (1146, "Table 'mydatabase.django_celery_beat_periodtask' doesn't exist") I've checked my mysql database and in fact there are no tables. Any idea of how to force the creation of the tables? -
setting up django server for receiving callbacks from jira and other apis
how can I start receiving and parsing callback api's responds in further with Django server? I wanna setup my DRF server to start working with JIRA webhooks, but also it might be useful for other apis such as telegram and etc. In this case I need to provide them my server's url where I would expect new events/data, but atm I don't realise what it means exactly. Where do I need to start digging in? -
multiprocessing.Process.start() raises exception django.core.exceptions.AppRegistryNotReady
Views.py def time_consuming_task_caller(i, j): print ('start', j) # time.sleep(10) # print('finished', j) def time_consuming_task_caller(i, j): Process(target=time_consuming_task, args=(i, j)).start() print ('processing...', j) return {'one': 'two'} def get_task(request): if request.method == 'GET': response = time_consuming_task_caller(5,1) # 5 is like time to sleep, 1 is task id. print(response) return HttpResponse(json.dumps(response), content_type="application/json") This causes error at return HttpResponse(json.dumps(response), content_type="application/json") because it prints all three print statements (except the commented one) Even with time.sleep() commented it causes the error. Ultimate goal is to make it work for processes that may take longer to execute. -
Form is not valid in django because it is empty
I'm trying to setup the register form for a website but it doesn't work because the form is empty so the print (request.POST) contains all the information but the form is not valid. This is the view: def register(request): print("Request submitted", request, request.method) if request.method == 'POST': print (request.POST) form = RegistrationForm(request.POST, prefix="user") print (form.is_valid()) print (form.errors) if form.is_valid(): ... else: print("not valid") else: form = RegistrationForm(prefix="user") return render(request, 'registration_form.html', {'form': form}) And this is the html: <body> <div class="login"> <h1>Alta de Usuario</h1> {% if messages %} {% for message in messages %} <div class="alert">{{ message }}</div> {% endfor %} {% endif %} <form class="login-form" method="post"> {% csrf_token %} <div> <label for="username">Nombre de usuario:</label> <input type="text" name="username" value="" placeholder="Elige un nombre de usuario"> <p class="form-valid"><i class="fas fa-check"></i></p> </div> <div> <label for="email">eMail:</label> <input type="text" name="email" value="" placeholder="Introduce tu email"> <p class="form-valid"><i class="fas fa-check"></i></p> </div> <div> <label for="pass">Contraseña:</label> <input type="password" name="pass" value="" placeholder="Introduce una contraseña"> <p class="form-valid"><i class="fas fa-times"></i></p> </div> <div> <label for="pass">Repite contraseña:</label> <input type="password" name="pass" value="" placeholder="Repite la contraseña introducida"> <p class="form-valid"><i class="fas fa-times"></i></p> </div> <div class="disclaimer"> <div class="check-terms"> <input class="terms" name="terms" type="checkbox"> <label for="terms"> Acepto los <a href="">términos y condiciones</a> </label> </div> </div> <button class="access" type="submit">Registrarme</button> </form> </div> </body> … -
what happens to users comments if user is deleted and Foreign key is set to models.SET_NULL
I was just curious what happens to users comments when user is deleted. Specially in the example below example Comment(models.models): author = models.ForeignKey(User, models.SET_NULL, blank=True, null=True) comment = models.Charfield(max_length=1000) Example of the comment: This is a comment -by Samir Tendulkar ({{user.first_name}} {{user.last_name}}) Now lets say the user is deleted This is a comment -by ?? ({{user.first_name}} {{user.last_name}}) Is there a way to add a default user as anonymous user 1) This is a comment -by Anonomous User ({{user.first_name}} {{user.last_name}}) The docs were not very clear on this -
How traslate a query in subquery Django
My problem is that I want to group by and sum for a field that I annotated before , but I can't do. from django.db.models import Max, Sum queryset = queryset.values('period', 'cell').annotate(x=Max('total')) result = queryset.values(period).annotate(result=Sum('x')) Data example: period cell total 1 2 40 1 2 41 2 3 23 1 4 44 First query queryset = queryset.values('period', 'cell').annotate(x=Max('total')) period cell x 1 2 41 2 3 23 1 4 44 Final Result that I need period result 1 85 2 23 I read that this is possible using Subquery, but I dont know how to do this. If someone has other solution is enough. Thanks -
How to specify environment variables in Apache site config for Django?
How do you specify environment variables for an Apache site? I have a multi-tenant Django site being served by Apache+ModWSGI. Each site uses the same Django code, but their settings differ slightly. An environment variable tells Django which settings to load. Currently, I'm getting a separate wsgi_<site_name>.py file, containing the variable appropriate for each site, but this violate the DRY rule. I'd like to, instead, put this variable in the Apache site config, and use a single wsgi.py file for all sites. I can't find much info on how to do this. I found this one old blog post suggesting I could use the Apache config syntax: SetEnv SITE somename along with a wsgi file like: import os, sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_DIR = os.path.abspath(os.path.join(BASE_DIR, '..')) sys.path.append(PROJECT_DIR) os.environ['DJANGO_SETTINGS_MODULE'] = 'app.settings' import django.core.handlers.wsgi _application = django.core.handlers.wsgi.WSGIHandler() def application(environ, start_response): os.environ['SITE'] = environ['SITE'] return _application(environ, start_response) but this has no effect. If I print out the SITE variable, Django never receives the value "somename" and displays the default value. As far as I can tell the mod_env component is still supported, and I've confirmed it's both installed and enabled on my server. -
Program Only Prints Last Line
I'm using Django to develop a web app for users to upload 2 different csv files, then the web app finds those differences, mark the differences respectively, and then print it as an output. The whole gig is set up and ready to go. However, when I try it for a test, it only prints the last line. I believe something is wrong with handle_uploaded_file function but I cant figure what to do with it. Previously this was the code for handle_uploaded_file function def handle_uploaded_file(file1,file2): # handle_uploaded_file is a function that takes 2 files uploaded by the users fileone = file1.readlines() # read lines from 1st file filetwo = file2.readlines() # read lines from 2nd file fileone =[line.decode("utf-8").strip() for line in fileone] filetwo =[line.decode("utf-8").strip() for line in filetwo] with open('results.csv', 'w') as outFile: # python creates a file called with difference.csv and start writing the differences for line in filetwo: # python compares the lines from both files if line not in fileone: # if line is not same print(line) # python writes those differences in difference.csv outFile.write(line+"\n") # every line python writes, adds a new row But then I had to change it to fulfill what I was looking … -
Django - How to check if server is running in ASGI or in WSGI mode?
We are running same django project in WSGI mode for handling HTTP requests and in ASGI mode for handling WebSockets. For WSGI mode we are using gunicorn3 server: gunicorn3 --pythonpath . -b 0.0.0.0:8000 chat_bot.wsgi:application For ASGI mode we are using daphne server: daphne --root-path . -b 0.0.0.0 -p 8001 chat_bot.asgi:application How to programatically detect which mode currently is running GUnicorn+WSGI or Daphne+ASGI? -
Missing formfield in django
I am trying to use formsets in Django but encounter a problem I don't understand. The error I get is [{'id': ['This field is required.']}, {}] Here is the background: In models.py I have class Ledighet(models.Model): person = models.ForeignKey(Personal,on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() In forms.py I have the single line LedighetFormset = inlineformset_factory(Personal,Ledighet,fields = ('start_date', 'end_date'),extra=1) In views.py I have def rapportera_ledighet(request,person_id): person = get_object_or_404(Personal,id = person_id) if request.method == 'POST': formset = LedighetFormset(request.POST,instance=person) if formset.is_valid(): formset.save() formset = LedighetFormset(instance=person) context={'person' : person, 'formset' : formset} return render(request, 'schema/rapportera_ledighet.html', context) and the key code in the html-file is <form method="post">{% csrf_token %} {{ formset.management_form }} <table class="table table-striped"> {% for f in formset %} <tr><td>{{ f.start_date }}</td><td>{{ f.end_date}}</td><td>{{ f.fraction }}</td><td>{{ f.typ }}</td></tr> {% endfor %} </table> <input type="submit" value="Updatera" /> </form> The form looks the way I want it to be, but I get the error above. What am I doing wrong? -
Django - print all objects attribute values
HTML <thead> <tr> {% for field in fields %} <th>{{ field }}</th> {% endfor %} </tr> </thead> <tbody> {% for well in well_info %} <tr> <td><p>{{ well.api }}</p></td> <td><p>{{ well.well_name }}</p></td> <td><p>{{ well.status }}</p></td> <td><p>{{ well.phase }}</p></td> <td><p>{{ well.region }}</p></td> <td><p>{{ well.start_date }}</p></td> <td><p>{{ well.last_updates }}</p></td> </tr> {% endfor %} <tr> views.py class WellList_ListView(ListView): template_name = 'well_list.html' context_object_name = 'well_info' model = models.WellInfo def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['fields'] = [field.name for field in models.WellInfo._meta.get_fields()] return context models.py from django.db import models from django.urls import reverse # Create your models here. class WellInfo(models.Model): api = models.CharField(max_length=100, primary_key=True) well_name = models.CharField(max_length=100) status = models.CharField(max_length=100) phase = models.CharField(max_length=100) region = models.CharField(max_length=100) start_date = models.CharField(max_length=100) last_updates = models.CharField(max_length=100) def get_absolute_url(self): return reverse("") def __str__(self): return self.well_name I was able to list all attribute field names by getting context['fields'], but I don't know how to automatically print each objects all attributes values. So in my html file, I hard-coded all the attribute names, but I want to know if I can to this in a more elegant way, by using for loop. So something like: <tbody> {% for well in well_info %} <tr> {% for value in attribute_list %} <td><p>{{ well.value }}</p></td> {% … -
How to save correctly the form data?
Please edit the save function for the given class so that it can save the data correctly from django import forms from rango.models import page,Category class CategoryForm(forms.Form, forms.ModelForm): name = forms.CharField(max_length=128, label="Please enter the category name.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0) def save(self, commit=True): instance = super(CategoryForm, self).save(commit=True) instance.name = fullname instance.ip = get_ip(self.request) if commit: instance.save() return instance class Meta: model = Category fields = ('name','views','likes')