Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django hosted on Apache - Uploading a file going to wrong location
I have a simple website that allows the user to upload a file to my server. I want the file to be uploaded into my django project folder in a sub directory. Everything is working fine but when I use the upload feature on my website I get a permissions denied on the folder /var/www BUT the thing is I changed the DocumentRoot to equal /mnt/public/apps - which is where I want my uploaded files to go (the upload creates a sub directory). I have correct permissions in /mnt/public but I can't figure out how to point django or apache so that my upload goes to the /mnt/public/apps root instead of /var/www Any help would be greatly appreciated! -
IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (..))
when deleting users with schedule_files I got this: IntegrityError at /admin/auth/user/166/delete/ (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (vacation.vacations_schedulefile, CONSTRAINT vacations_schedulefile_user_id_e85fa52f_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user (id))') My models are: class ScheduleFile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) added = models.DateTimeField(default=django.utils.timezone.now) def __str__(self): return '[User ID: {}] {}'.format(str(self.user.id), self.user.username) And class VacationEvent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) schedule_type = models.CharField(choices=SCHEDULE_TYPES, default=STRICT_TIME, max_length=3) exclude_fba_from_chatzos = models.BooleanField(default=False) schedule_file = models.ForeignKey(ScheduleFile, on_delete=models.CASCADE, null=True) status = models.CharField(verbose_name="status event", choices=EVENT_STATUSES, max_length=3, default=CREATED) And User(AbstractUser) I decided to create pre_delete signal and delete relative objects of schedule model: @receiver(pre_delete, dispatch_uid='User') def user_del(sender, instance, **kwargs): i = instance events = VacationEvent.objects.filter(user_id=166) schedule = prefetch_related_objects(events, 'schedule_file__user') schedule.delete() # instance.user.schedulefile_set.clear() # qs = VacationEvent.objects.filter(user_id=166).prefetch_related_('schedule_file') # qs.delete() # b = ScheduleFile.objects.filter(user_id=166) # e = VacationEvent.objects.filter(user_id=166) # e.schedule_file.remove(b) But it returns 'NoneType' object has no attribute 'delete'. How can I do it right? Thanks for any help. -
Django Dropdown POST
... I'm new in django and I have this problem: When I want to show the data selected on my dropdown, it doesn't work ... this is the code index.html <form method="post" action="/getdata/"> <select name="Lista"> <option selected="selected" disabled>Objects on page:</option> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> <option value="50">50</option> </select> <input type="submit" value="Select"> </form> views.py def index(request): if request.method == 'POST': Lista = request.POST.get('Lista') print Lista context = { Lista: 'Lista' } return render(request, 'showdata.html', context) else: template = loader.get_template('index.html') return HttpResponse(template.render()) getdata.html <form method="post" action="/getdata/"> <table> <tr> <td>Numero:</td> <td><strong>{{ Lista }}</strong></td> </table> </form> when I executed the server i just see the following "Numero: " without any number selected ... Thanks for your help ... -
Trying to react to a woocommerce webhook on django
Hello, I'm trying to react to a woocommerce webhook on django. I have a webhook who reacts to each order of my website. For each order, I have to parse the content to save de id, price, etc... HOW can i tell to my Django (in views.py, models.oy, etc...) to do an action when a webhook from www.xxx.com arrives thank you! -
Django AutoCompleteSelectMultipleField has required=True, but form saves with it being blank when adding an instance for the first time
On a Django project, I am using AutoCompleteSelectMultipleField from the ajax_select.fields module and I am specifying required=True for this field. The field is mandatory when I am trying to save the form for an instance that already exists, i.e. the browser does not let me save without filing in the field. But when I try to add a new instance (a photo in my case) I can save the instance without the field being filled in. Here is the code for the field in 'admin.py': from ajax_select.fields import AutoCompleteSelectField, AutoCompleteSelectMultipleField class PhotoExtendedAdminForm(forms.ModelForm): authors = AutoCompleteSelectMultipleField('authors', required=True, help_text=None, plugin_options={'minLength': 4}) How do I make this field absolutely mandatory even when I am adding a new instance? -
Two Ajax calls only meet one condition at a time
I have the following script that sends a POST of my select option to a url called requestaccess. This works great when using only one of the two, but when I change the other field the result of the POST is None for the first and correct for the second and vice-versa. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <select title ="accesslevelid" class="form-control" id="accesslevelid" onclick="accesslevelid"> <option value=""> Please select your access level </option> <option value="7"> Facility </option> <option value="5"> Division </option> <option value = "3"> Corporate </option> <option value = "6"> Market </option> <option value = "4"> Group </option> </select> <script> $(document).ready(function () { $('#accesslevelid').on('click', function () { var accesslevelid = $(this).val(); $.ajax({ url: "{% url 'requestaccess' %}", headers: { 'X-CSRFToken': '{{ csrf_token }}' }, data: { accesslevelid: accesslevelid, }, type: 'POST', success: function (result) { ; }, }); }); }); </script> </div> <div class="col"> <label for="phi"><h3>PHI</h3></label> <select class="form-control" id="phi" title = "phi" onclick="phi"> <option value = ""> Please select if you need access to PHI data </option> <option value = "0"> No </option> <option value = "1"> Yes </option> </select> <script> $(document).ready(function () { $('#phi').on('click', function () { var phi = $(this).val(); $.ajax({ url: "{% url 'requestaccess' %}", headers: { 'X-CSRFToken': '{{ csrf_token }}' … -
Django groups and special permissions
Can any one guide me in this is there any way to create django groups where there should be a group admin who can control the activity of the group and cand add members and themembers can share any kind of photos within the group and the other members outside the group cant view/access the photos/media Thanks in advance -
Convert uploaded file with Wand to PDF and save to model
Here is my code: class ToPng(APIView): def post(self, request, *args, **kwargs): revision = request.data.get('revision', None) file = request.data.get('file', None) with tempfile.TemporaryFile() as tmp: tmp.write(file.read()) all_pages = Image(blob=file.read()) single_image = all_pages.sequence[0] with Image(single_image) as img: img.format = 'png' img.background_color = Color('white') img.alpha_channel = 'remove' MyModel.objects.create(revision=revision, file=img) return Response(HTTP_200_OK) I get the error: "no decode delegate for this image format `' @ error/blob.c/BlobToImage/353" Obviously I am making a grave mistake since wand with imagemagick can convert Pdf to Png right away. I am probably reading the wrong thing but I don't know what else to do. -
How to get most recent list elements in Django template?
I want to get most 4 recent elements from a list ? I can get elements in increasing order but no idea about getting recent elements. for example: news_list[n], news_list[n-1] .... Template Code: {% for obj in news_list|slice:"last:" %} <div class="sub_highlights"> <a href="/news#{{obj.title}}"> <img src="/static/images/{{obj.imgs}}" alt="Thumbnail"> <label>{{obj.info}}</label> </a> </div> {% endfor %} views.py class NewsTemplateView(TemplateView): template_name = 'index.html' def get_context_data(self,*args, **kwargs): qs = News.objects.all() q = Reviews.objects.all() context = { "news_list" : qs, "review_list" : q } return context -
Support write operation for two-deep reverse relation serializer in Django Rest
Hi I need an API to write/post two-deep reverse relation in django rest. Here is my models.py: class Projects(TimeStampModel): project_name = models.CharField(max_length=30) project_dsn = models.CharField(max_length=30) class Objects(TimeStampModel): projects = models.ForeignKey(Projects,related_name='proj_obj',on_delete=models.CASCADE) object_name = models.CharField(max_length=50) object_description = models.TextField() object_main_table = models.CharField(max_length=50) class Rule(TimeStampModel): obj = models.ForeignKey(Objects,related_name='obj_rule',on_delete=models.CASCADE) rule_description = models.TextField() legal_hold = models.BooleanField(default=False) My serializers.py: class RuleSerializer(serializers.ModelSerializer): proj = serializers.RelatedField(source='obj.projects', queryset=Objects.objects.all()) class Meta: model = Rule fields = ('obj','rule_description','legal_hold','proj',) I need to create a Rule object. My Django rest API properly shows a dropdown for Objects model (one-deep relation) but how do I make it show a dropdown for Project model (two-deep relation) as well? The above implementation gives me this error: Exception Type: NotImplementedError Exception Value: RelatedField.to_representation() must be implemented for field proj. If you do not need to support write operations you probably want to subclass `ReadOnlyField` instead. I don't want to put read_only=True since I want a write operation. Please suggest how to accomplish this. -
Can't test successfully for view that puts form data in session
I'm trying to test a view that stores validated form data in the session. However when I try to test this I get back None for the session value and the error: AssertionError: 'example_postcode' != None The test is: class TestSignup(TestCase): def test_postcode(self): postcode = 'example_postcode' self.client.post('/users/postcode', {'postcode': postcode}) self.assertEqual(postcode, self.client.session.get('postcode')) the view is: @require_http_methods(['GET', 'HEAD', 'POST']) def postcode_view(request,): if request.method == 'POST': form = PostcodeForm(request.POST) if form.is_valid(): request.session.update(form.cleaned_data) return redirect('users:signup_2') else: form = form_class() context.update({'form': form}) return render(request, 'pages/signup_postcode.html', context) form class PostcodeForm(forms.Form): postcode = GBPostcodeField(label='Please enter your postcode', error_messages={'invalid': 'Please enter a valid postcode'}) -
How to add pagination for custom Apiview result data in DRF
I have create an api Listview in DRF 3. As database structure is complex I have written a custom query ie raw query to fetch the data. But as the data size is huge it takes a lot of time to load the data. So I need to implement the pagination. Below is the code. class SubnetList(APIView): def get(self, request, format=None): subnet_list = get_subnet_details(None) return Response(subnet_list, status=status.HTTP_200_OK) def get_subnet_details(subnet_id=None): if subnet_id: subnets = Subnet.objects.filter(id=subnet_id).values() if not subnets: raise Http404 else: subnets = Subnet.objects.values() subnet_list = [] subnet_option_query = ' SELECT ' \ ' options_value.id as value_id,' \ ' options_value.content,' \ ' options_option.id,' \ ' options_option.name' \ ' FROM subnets_subnetoption' \ ' INNER JOIN subnets_subnet ON (subnets_subnetoption.subnet_id = subnets_subnet.id)' \ ' INNER JOIN options_value ON (subnets_subnetoption.value_id = options_value.id)' \ ' INNER JOIN options_option ON (options_value.option_id = options_option.id)' \ ' INNER JOIN options_scope ON (options_option.scope_id = options_scope.id)' \ ' WHERE subnets_subnetoption.subnet_id = %s ' try: for subnet in subnets: subnet_dictionary = collections.OrderedDict() subnet_dictionary['subnet_id'] = str(subnet['id']) subnet_dictionary['name'] = str(subnet['name']) subnet_dictionary['base_address'] = str(subnet['base_address']) subnet_dictionary['bcast_address'] = str(subnet['bcast_address']) subnet_dictionary['bits'] = str(subnet['bits']) subnet_dictionary['begin'] = str(subnet['base_address']) subnet_dictionary['end'] = str(subnet['bcast_address']) subnet_dictionary['parent_id'] = str(subnet['parent_id']) subnet_dictionary['vlan_common_name'] = str(subnet['vlan_common_name']) subnet_dictionary['admin'] = str(subnet['admin']) subnet_dictionary['responsible'] = str(subnet['responsible']) subnet_dictionary['comments'] = str(subnet['comments']) super_subnet = 'True' if … -
New Urls patterns and multiple variables with the same name
I'm using Django 2.0 type of urls, and I have urls with multiple variables in them, with the same name. I'm using also ClassBasedView path('/companies/<int:pk>/products/<int:pk>/', AccountCompanyProductDetailView.as_view() In a CBV how can I get the parameters and know which is which. ? How Django knows pk from which Model I need in each position ? -
Django url.py regex not working
I am trying to catch all URLs from the safer app and send them to a catch all view; for example: http://127.0.0.1:8000/saferdb/123 http://127.0.0.1:8000/saferdb/12 I think I have an issue with my reg ex in url.py: from django.conf.urls import url from . import views app_name = 'saferdb' urlpatterns = [ url(r'^/$', views.index, name='index'), url(r'^(?P<pk>[0-9]+)/$', views.detail, name='detail'), ] Views.py is the sample code from the django tutorial: from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.all()[:5] output = ', '.join([q.DOT_Number for q in latest_question_list]) return HttpResponse(output) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) I noticed that /saferdb/ will not work unless the reg ex contains a slash: r'^/$' instead of r'^$' as shown in the django tutorial. -
ERROR: Form object has no attribute 'save_m2m'
i am working on a django project. I have created a custom user model which is called Employee and extends AbstractUser model like this : models.py from django.db import models from django.contrib.auth.models import AbstractUser from .model_manager import EmployeeManager class Employee(AbstractUser): department = models.OneToOneField(Department, on_delete=models.SET_NULL, null=True) position = models.OneToOneField(Designation, on_delete=models.SET_NULL, null=True) dob = models.DateField(verbose_name="Date of Birth", null=True) manager = models.ForeignKey('self', on_delete=models.SET_NULL, related_name='manger', null=True) REQUIRED_FIELDS = [] objects = EmployeeManager() model_manager.py from django.contrib.auth.models import BaseUserManager from config.settings import COMPANY_EMAIL_DOMAIN class EmployeeManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) username = self.model.normalize_username(username) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email=None, password=None, **extra_fields): if not email: email = username + '@' + COMPANY_EMAIL_DOMAIN extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', False) return self._create_user(username, email, password, **extra_fields) def create_superuser(self, username, password, email=None, **extra_fields): if not email: email = username + '@' + COMPANY_EMAIL_DOMAIN extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(username, email, password, **extra_fields) I wanted to … -
Django Test client.get() returns 302 code instead of 200
Running a test on a url returns 302 instead of 200. Yet testing the same urls in production with a redirect tester returns 200. Not really sure what's going on. tests.py def test_detail(self): response = self.client.get('/p/myproduct-detail.html') self.assertEqual(response.status_code, 200) urls.py url(r'^p/(?P<slug>[-\w\d]+).html$', main.views.product_detail, name='product-detail'), views.py def product_detail(request, slug): stuff... return render(request, 'product-detail.html', {}) If I add follow=True to client.get() I receive 200 code as expected. -
Django rest framework Anonymous user is always Authenticated
I'm trying to authenticate my web API method using django rest framework isauthenticated permission and TokenAuthentication The API method: @api_view(['Post']) @permission_classes((IsAuthenticated,)) def listofgroups(request): try: logout(request) data = request.data page_size = data.get('pagesize') page_number = data.get('pagenumber') group_qs = Group.objects.all() paginator = Paginator(group_qs, int(page_size)) group_list = paginator.page(int(page_number)) #group_list = tools.paginate_query_set(group_qs, 1, 3) #list = group_list[0]['model'] groups = [get_group_dto(g) for g in group_list] sorted_groups = sorted(groups, key=lambda k: k['user_count'], reverse = True) group_list_dto = { "grps": sorted_groups, "success":1, "fail":0 } return Response(group_list_dto) except Exception as e: #.error("Error %s"(e), exc_info = 1) return Response({"success" : 0, "error": str(e)}) Basically i should always set Authorization in the header like : "Authorization":"Token a26171d30745cc94bcd6ac42d9bc94e1d3992948" this token is based on rest_framework.authtoken The Error is that I can get the data with response 200 without even setting the Token in the header because its returning anonymous user which is authenticated from the back end in django. How can I prevent anonymous users from being authenticated and return 403 response error for them using django rest framework I appreciate any help -
Django user account creation confirmation email
I have a django project where I want to create users, and some time later be able to send a welcome email with a link inviting them to log in and set a password. I'm using django-allauth. I found this SO question which shows how to call allauth's password reset form, which is close to what I need, except that: I want to send a "welcome" email, which would be worded differently. I want it to send them to a "welcome" page, which would be different to a password reset (although perhaps operate the same way in that it use a token etc...) I'm thinking I could somehow hijack that, but am not sure how or where that email gets sent. django-allauth docs mention the routes /accounts/password/set/ and /accounts/password/set/ but I can't access either without logging in first. This is an existing project I inherited, and I do have a template for "/account/password_reset_from_key.html". Just not sure how it all gets wired together. Has anyone done anything similar? -
Convert PDF to Image and save to model
Pardon my ignorance if the question is in fact nonsensical. I have an ImageField in a model, field itself is stored in S3 Bucket. Model serializer gets the data sent from front and saves it. Now if the file is pdf, I have to convert it and save it. I try to write an APIView for it. Something like: class ToPng(APIView): def post(self, request, *args, **kwargs): revision = request.data.get('revision', None) file= request.data.get('file', None) import tempfile with tempfile.TemporaryFile() as tmp: tmp.write(file.read()) # write the subprocess here. # linux command: pdftoppm input.pdf outputname -png -f 1 -singlefile So am I in the right direction? How can I get the input.pdf? How can I save output.png to the model? And how can I write the subprocess? -
Retrieving related polymorphic set with django-polymorphic
I have three simple models: class Employee(models.Model): [...] class AttendanceLog(models.Model): employee = models.ForeignKey(Employee, [...]) from_datetime = models.DateTime([...]) to_datetime = models.DateTime([...]) class Salary(models.Model): employee = models.ForeignKey(Employee, [...]) [...] What I need is to make a query that will return the total (SUM) amount of time an employee was in work (attendance). What I have right now: # method in Salary def get_attended_hours(self): qs = AttendanceLog.objects.employee(self.employee).filter(to_datetime__year=self.year, to_datetime__month=self.month) qs = qs.values('employee') # group by employee (should not be needed) duration = ExpressionWrapper(F('to_datetime') - F('from_datetime'), output_field=fields.DurationField()) qs = qs.annotate(duration=Sum(duration)).values_list('duration', flat=True) # expected output: {'duration': datetime.timedelta(0, x)} # actual output: <AttendanceLogQuerySet [datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 3600), datetime.timedelta(0, 14400), datetime.timedelta(0, 10800), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), '...(remaining elements truncated)...']> # qs.query: SELECT SUM(django_timestamp_diff("human_resources_attendancelog"."to_datetime", "human_resources_attendancelog"."from_datetime")) AS "duration" FROM "human_resources_attendancelog" WHERE ("human_resources_attendancelog"."employee_id" = 22 AND "human_resources_attendancelog"."to_datetime" BETWEEN 2017-01-01 00:00:00 AND 2017-12-31 23:59:59.999999 AND django_datetime_extract('month', "human_resources_attendancelog"."to_datetime", None) = 11 AND "human_resources_attendancelog"."attendance_type" = RE) GROUP BY "human_resources_attendancelog"."employee_id", "human_resources_attendancelog"."to_datetime" ORDER BY "human_resources_attendancelog"."to_datetime" ASC # problematic part: GROUP BY "human_resources_attendancelog"."employee_id", "human_resources_attendancelog"."to_datetime" Basically, why is it also using GROUP BY on to_datetime? I tried to force the … -
Cross Table Left Join, Django ORM
I have the following models: class TradeDetails(models.Model): created_timestamp = models.DateTimeField(db_column='CREATED_TIMESTAMP', primary_key=True) trade_name = models.CharField(db_column='TRADE_NAME', max_length=45) trade_image = models.CharField(db_column='TRADE_IMAGE', max_length=500, blank=True, null=True) class Meta: managed = False db_table = 'TRADE_DETAILS' class TradeNotifications(models.Model): client_id = models.CharField(db_column='CLIENT_ID', primary_key=True, max_length=15) created_timestamp = models.DateTimeField(db_column='CREATED_TIMESTAMP') updated_timestamp = models.DateTimeField(db_column='UPDATED_TIMESTAMP', blank=True, null=True) platform_notification = models.IntegerField(db_column='PLATFORM_NOTIFICATION', blank=True, null=True) sms_notification = models.IntegerField(db_column='SMS_NOTIFICATION', blank=True, null=True) email_notification = models.IntegerField(db_column='EMAIL_NOTIFICATION', blank=True, null=True) caller_notification = models.IntegerField(db_column='CALLER_NOTIFICATION', blank=True, null=True) caller_id = models.IntegerField(db_column='CALLER_ID', blank=True, null=True) client_confirmation = models.IntegerField(db_column='CLIENT_CONFIRMATION', blank=True, null=True) device_id = models.CharField(db_column='DEVICE_ID', max_length=256, blank=True, null=True) platform = models.CharField(db_column='PLATFORM', max_length=15, blank=True, null=True) ip_address = models.CharField(db_column='IP_ADDRESS', max_length=50, blank=True, null=True) expired = models.IntegerField(db_column='EXPIRED', blank=True, null=True) trade_sent = models.IntegerField(db_column='TRADE_SENT', blank=True, null=True) class Meta: managed = False db_table = 'TRADE_NOTIFICATIONS' unique_together = (('client_id', 'created_timestamp'),) I want to perform a left join on another table on the same db using the following sql query: SELECT TRADE_DETAILS.TRADE_NAME FROM TRADE_NOTIFICATIONS LEFT JOIN TRADE_DETAILS ON TRADE_NOTIFICATIONS.CREATED_TIMESTAMP = TRADE_DETAILS.CREATED_TIMESTAMP Is there a more Django-Like way of doing this or should I just go with raw sql? -
django 1.5 python set X-Content-Type-Options nosniff
We would like to add X-Content-Type-Options nosniff . We can't upgrade to newer django version (1.5), so we can't use the SECURE_CONTENT_TYPE_NOSNIFF because we don't have SecurityMiddleware. Any help is appriciated. -
NoReverseMatch at /sitemap.xml when generating sitemap.xml django website
Apologies for the long post.I am trying to generate sitemap.xml for a basic django blog application with a few static pages. I am not sure why the error occurs. Note: I have already created a dummy blog post and it exists when I get the error. I tried to look at the django documentation but found it too confusing. The tutorials online weren't much helpful either. **Error:** NoReverseMatch at /sitemap.xml Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>\\d+)$'] **sitemap.py** from django.contrib.sitemaps import Sitemap from blog.models import Post from blog.urls import urlpatterns as homeUrls from django.core.urlresolvers import reverse class PostSitemap(Sitemap): changefreq = "weekly" priority = 0.5 def items(self): return Post.objects.all() class StaticSitemap(Sitemap): priority = 0.8 changefreq = 'weekly' # The below method returns all urls defined in urls.py file def items(self): mylist = [ ] for url in homeUrls: if url.name is None: pass; else: mylist.append(''+str(url.name)) return mylist def location(self, item): return reverse(item) **models.py** class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) **urls.py** ... from django.contrib.sitemaps.views import sitemap from .sitemaps import * sitemaps = { 'posts': PostSitemap(), 'static': StaticSitemap(), } urlpatterns = [ … -
What would be the robust design pattern for multiple class forms render/process (create, update) on single page in django
I am working on a django project in which I have to design a sales order page for order processing,now as per requirement I have to create multiple information forms on single page with different fields (formset does not helpful in this case) which I achieved by creating specific form class and then render them in template through class view function def get_context_data(self, **kwargs): context = super(CreateOrderView, self).get_context_data(**kwargs) context['ord_info_form'] = OrderInformationForm() context['billing_form'] = BillingInformationForm(prefix='billing') context['shipping_form'] = ShipingInformationForm(prefix='shipping') context['payment_form'] = PaymentInfoForm() context['summary_form'] = OrderProductsForm() return context Now, I have to save data for all forms which belongs to multiple models like billing, contact and shipping information. So for save information I created another form class for create order and set it in form_class variable in Createview class, and I override the save function in form class in which I manipulate the data for all model forms. For update order (put operation) I did the same I create another form class for update like create one in form class. As per my understanding I implement this strategy, but this seems to me repetitive design. How can I design it better for multiple forms with different fields. Please let me know what kind … -
django form without id=id_fieldname
I have the following form in django: class Person(forms.Form): first_name = forms.CharField() last_name = forms.CharField() age = forms.IntegerField() When I render the form, the html output is the following: <input id="id_age" name="age" type="number"> Is it possible to NOT include the input id? My desired output would be: <input name="age" type="number">