Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF filter object by lookup_field
im trying to show prduct by category ... category name is comming to server and i have lookup_filed for name in url. in query_set i must filter object with the category name i did queryset = CategoryAssin.objects.filter(cat_id__title=lookup_field) ...but looks im doing wrong .. how can in fix that? url: path('api/v1/store/view-category/<str:name>/', GetCategoryAPIView.as_view(), name='get-cat'), my view : class GetCategoryAPIView(generics.ListAPIView): lookup_field = 'name' queryset = CategoryAssin.objects.filter(cat_id__title=lookup_field).values_list('product', flat=True) permission_classes = [IsOwnerOrReadOnly] def get(self, request, *args, **kwargs): obj = Product.objects.filter(product_id__in=self.queryset) serializer = ProductSerializer(instance=obj, many=True,context={'request': request}) return Response(serializer.data) -
Django custom form field layout without manually redoing the whole form
I like Django form render(‘form’: form) and template {{ form }}, but it doesn’t allow you to arrange fields. I was just wondering if there was an easier way to do it, without rendering the whole form manually. What Django does: First Name Middle Name Last Name What I want to do: First Name Middle Name Last Name What makes Django {{ form }} so great is that it puts field labels and help text and all that jazz in the right places. Where as manually, you have to put all that in. If there isn’t an easier way, I’m ok with that, but I thought I would at least ask. -
Django: How to save a record in a new table before saving (user udates) the original
Scenario: Developing a question answer app. Here are different users can answer the questions. Each question may have several fields to response (2 or 3 yes/No checkboxes) and any user can update any of those any time. Problem: I need to keep a log (with time and user name) in a different log table every time the records got any changes. The log table is just a look alike of the original model (e.g. ChangeLogModel) just with 2 extra fields as logDate and ChangingUser. This will help me to check the log and find the status of the question in any specific date. Possible Solutions: Using signals (...Not used to with signals, lack of detailed tutorials, documentation is not detailed too) making the backup before doing any ".save()" (... Have o idea how to do that) Install any external app (...Trying to avoid installing any app) -
Python Django Unable to display to forms in one template
I have a problem to display two forms in one template. If I delete one of these forms {'form': form} or {'obj': obj} from my views.py the remaining form is displayed correctly. It is the first time that I need to use two form in one template so I don't know if my views.py is correct. this my views.py def Form(request): form = ResgisterStud(request.POST) obj = SomeForm(request.POST) if request.recaptcha_is_valid and form.is_valid()and request.method=='POST' and 'student' in request.POST: form.save(commit=False) form.save() messages.success(request, 'Saved student') return render(request, 'form.html', {'form': form}, {'obj': obj}) if request.method == 'POST' and 'disponnibility' in request.POST: obj.save(commit=False) obj.save() messages.success(request, 'Saved Dispo') return render(request, 'form.html', {'form': form}, {'obj': obj}) else: return render(request, 'form.html', {'form': form}, {'obj': obj}) my form.html <form method='post'> {% csrf_token %} {{ obj.as_p }} <input name="disponnibility" type='submit' value='submit'> </form> <form action="{% url "form" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-md-6 form-group"> {{ form.Nom|add_class:"form-control" }} </div> <div class="col-md-6 form-group"> {{ form.Prenom|add_class:"form-control" }} </div> <div class="col-md-6 form-group"> {{ form.Telephone|add_class:"form-control" }} </div> <div class="col-md-12 text-center"> <button name="student" class="btn" type="submit">Submit Now</button> </div> </div> </form> -
Django response with modal to overwrite something
I want to overwrite something, now I am checking if exist the object with the same name, and now, I sent a response with data = {"message": force_text(_('Another rehab program already has that name.')), "message_type": "error" } return HttpResponse(json.dumps(data), content_type="application/json") But now I wanna send a modal, or any reponse, with a button to answer if you wanna overwrite this or not, but I don't have any idea how can I do this... :( It is possible with force_text? I did not find anything... All the page is in django, and we have html a .js. Thank you! -
How do I configure url for static files and media in development?
I'm developing an application in which I need to put images on the screen. I configured the "settings" file as explained in the django tutorial. But for some reason the images are not found. settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, '/static/'), ) MEDIA_ROOT = os.path.join(STATIC_ROOT,'media') MEDIA_URL = '/static/media/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('licitacao.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) exemple.html <img class="card-img-top figure-img img-fluid rounded" src="{% static "media/800x600.png" %}" alt="Card image cap"> If I change the url static by media, the image appears, however, static files like css and js stop working. How do I run the media and static together? -
Blank Django ReactJS Webpage With No Errors
I have followed a lot of examples about how to setup Django and ReactJS for Dhjango to serve up static files using the Djano Webserver. I believe I have a good working version but for some reason I get a blank page but with no errors. I am new to ReactJS but I believe this is an issue around compatibility with Babel. There seems to be new Babel code and the tutorials I have been reading are dated. Any help would be really appreciated because I am out of ideas. Here is my code: SETTINGS.PY INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webpack_loader', 'arlo_project' ] STATIC_URL = '../../build/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, '/build/static'), # We do this so that django's collectstatic copies or our bundles to the STATIC_ROOT or syncs them to whatever storage we use. ) WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } WEBPACK.CONFIG.JS var path = require("path"); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, entry: { main:'./src/index', vendors: ['react'], }, // entry point of our app. // src/index.js should require other js modules and dependencies it needs output: { //Where you put the compiled bundle to … -
Django not running: ModuleNotFoundError: No module named 'encodings'
I have installed django website in a new Ubuntu 17.10 server. It is based on python3. It works fine when i run the website in development mode using python manage.py runserver But when i tried to configure it via apache2 webserver in port 80 by adding wsgi in apache by editing default config file as shown.. <VirtualHost *:80> ServerAdmin webmaster@localhost ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/usr/mygpsproject/gps_restapi/gps_restapi> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess gps_restapi python-path=/home/usr/mygpsproject/gps_restapi/ python-home=/home/usr/mygpsproject/venv/bin/ WSGIProcessGroup gps_restapi WSGIScriptAlias / /home/usr/mygpsproject/gps_restapi/gps_restapi/wsgi.py </VirtualHost> but Site is not working. When I checked the apache error log to find this error... [Sat Apr 14 16:16:09.201739 2018] [core:notice] [pid 5089:tid 140258267696064] AH00051: child pid 7500 exit signal Aborted (6), possible coredump in /etc/apache2 Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f906c390bc0 (most recent call first): I am not able to find what is this encodings module. it worked fine in development mode. so python is not missing any libraries for sure. What could be the problem with my configuration. -
Update field with OneToOneField relationship - Djando rest framework
I have a model class Worker(models.Model): name = models.CharField(max_length=300) code = models.CharField(max_length=100) user = models.OneToOneField(User, null=True, blank=True) def __str__(self): return self.name which has a one-to-one relationship with the django user model. and this is serializers: class WorkerSerializer(serializers.ModelSerializer): class Meta: model = Worker fields = '__all__' My viewset: @transaction.atomic def update(self, request, *args, **kwargs): with transaction.atomic(): try: instance = self.get_object() instance.id = kwargs.get('pk') serializer = WorkerSerializer(instance=instance, data=request.data) if serializer.is_valid(raise_exception=True): self.perform_update(serializer) return Response({"status": True, "results": "Datos actualizados correctamente"}, status=status.HTTP_201_CREATED) except ValidationError as err: return Response({"status": False, "error_description": err.detail}, status=status.HTTP_400_BAD_REQUEST) The problem I have is that to associate a user with a worker I have to add the id of the worker but I would like to be able to associate it simply by entering his username in the client field. How can this be done? and how can I verify if a worker already has an associated user? -
Heroku ---> Installing pip remote: AttributeError: module 'pip._vendor.requests' has no attribute 'Session'
A Python 3.6 Django ==11 app was being deployed and code being pushed regularly till yesyerday . Now have the error == remote: AttributeError: module 'pip._vendor.requests' has no attribute 'Session' -
Django: ModuleNotFoundError: No module named 'requests'
when i run server i have below error: ModuleNotFoundError: No module named 'requests' but requests have been installed on my system, when i run sudo pip3 install requests command, output is : Requirement already satisfied: requests in /home/sadegh-khan/.local/lib/python3.6/site-packages the terminal pic of my error and command to install requests is: -
Django filter using **kwargs
I'm trying to filter using some fields in an array like: qs = Model.objects.all() fields_list = ['a', 'b', 'c'] for field in fields_list: filter = {field: 20} qs.filter(**filter) This piece of code, works in shell but not in runtime. What am I doing wrong? -
Django: Filtering Many To Many, Find an Instance where multiple connected model instances exist
I have the following model where a thread can have many people. I would like to find a thread which contains specific users if it exists. class Thread(models.Model): subject = models.CharField(max_length=150) users = models.ManyToManyField(settings.AUTH_USER_MODEL, through="UserThread") class UserThread(models.Model): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Message(models.Model): thread = models.ForeignKey(Thread, related_name="messages", on_delete=models.CASCADE) sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="sent_messages", on_delete=models.CASCADE) sent_at = models.DateTimeField(default=timezone.now) What I would like is to check if there is a thread which has 2 of the following users (user1 and user2): thread = Thread.objects.get(Q(UserThread__user==user1) & Q(UserThread__user==user2)) -
Using django and iframe in html when I create links in these iframes, the url is pre-pended with the base url. How should I handle this
I am using django framework to develop a small website. My template to be deployed has 3 frames and each of this frame has a url that I am generating through the python scripts. The problem that I am facing is that the url in these iframes is getting pre-pended with the url of the parent page. I do not want the parent page url to be pre-pended. Is this possible. Also I am using folium to generate a map with markers. These markers must have popups with hyperlinks. Here again the hyperlink that I am generating in the script is getting pre-pended with the parent page url. This is again creating problem. Can someone please guide how to handle these embedded urls correctly. Please note that these embedded urls are generated in the python scripts -
How can I use input HTML with formset in Django
I have a formset with 2 fields. When I run it, display this "/>" on the screen. Look above my html code. I don´t know why this is happen. I think that is something in HTML tag and I have to change it. I appreciate if someone can help me to solve this situation. Thanks. HTML: {% load static %} <!DOCTYPE html> <body> <script src="{% static 'id15/assets/js/jquery.min.js' %}"></script> <script src="{% static 'id15/assets/js/jquery.formset.js' %}"></script> <form class=" bd-form-20 " action="" name="form-name" method="POST" > {% csrf_token %} <script> function caps(element){ element.value = element.value.toUpperCase(); } </script> <label>outorgado</label><br><br> <div> {{ formsetoutorgado.management_form }} {% for formset in formsetoutorgado %} <div class="link-formset"> <input type="text" id={{formset.nom_outorgado}} /><br><br> {{formset.nom_outorgado.errors}} <input type="text" id={{formset.num_cpf_outorgado}} /><br><br> {{formset.num_cpf_outorgado.errors}} </div> {% endfor %} </div> <script> $('.link-formset').formset({ addText: 'Adicionar', addCssClass: 'add-row', deleteText: 'Remover', deleteCssClass: 'show', }); </script> <br> <button type = "submit" > Cadastrar e Continuar </button> </form> </body> </html> -
Django: Iterating over a Nested Dictionary
This is the dictionary I would like to iterate over: { '04/14/2018': { '12:15': { 'Club 1': { 'venue_address': 'Address 1', 'venue_webaddress': 'http://www.address1.com/line-up', 'show_data': { 7968: { 'price': '20', 'payment_webaddress': 'http://www.comedycellar.com/reservation/', 'show_title': 'Street 1', 'acts': [('Act 1', None, None), ('Act 2', None, None), ('Act 3', None, None), ('Act 4', None, None), ('Act 5', None, None), ('Act 6', None, None)] } } } }, '03:00': { 'Club 2': { 'venue_address': 'Address 2', 'venue_webaddress': 'https://www.club2.com/', 'show_data': { 7879: { 'price': 'None', 'payment_webaddress': 'https://www.club2.com/checkout', 'show_title': 'Show Title 2', 'acts': [(None, None, None)] } } } }, '04:00': { 'Club 3': { 'venue_address': 'Address 3', 'venue_webaddress': 'http://www.club3.com/', 'show_data': { 7703: { 'price': '17', 'payment_webaddress': 'https://www.webaddress.com', 'show_title': 'Show Title Club 3', 'acts': [(None, None, None)] } } } }, '05:00': { 'Club 4': { 'venue_address': 'Address 4', 'venue_webaddress': 'https://club4.com/', 'show_data': { 7834: { 'price': 'None', 'payment_webaddress': 'https://club4.com/checkout', 'show_title': 'Show Title 4', 'acts': [(None, None, None)] } } } }, '05:45': { 'Club 5': { 'venue_address': 'Address 5', 'venue_webaddress': 'http://www.club5.com/', 'show_data': { 7569: { 'price': '25', 'payment_webaddress': 'https://www.clubaddress5.com', 'show_title': 'Club Address 5', 'acts': [('Act 1', None, None)] } } } }, '06:00': { 'Club 6': { 'venue_address': 'Club Address 6', 'venue_webaddress': 'https://www.club6.com/', 'show_data': { 7881: { … -
Unable to generate a file to download with Django
Part which is working fine : I have made a <form> whose submit call makes an ajax request.Code for the same : $.ajax({ type: 'POST', url: '/uploaded_proto_file/', data: formdata, processData: false, contentType: false, success: function (data) { console.log("in success") console.log("data is --->"+data) return; }, error: function (data) { console.log("in error") return; } }); I am able to receive the call for the same on the function below. Now i need to send a file (which is in my document structure) that needs to auto downloaded in my browser. I execute this function based on this answer def uploaded_proto_file(request): with open( '/Users/metal/Documents/test_pb2.py','rb') as text_file: response = HttpResponse(FileWrapper(text_file.getvalue()), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=test_pb2.py' return response The above code wasn't working fine, so I debugged it and found this error on the filewrapper statement Now I changed the solution a bit but the file sent back in response is not getting auto downloaded , it is getting printed in the console (as my success block in ajax function has console.log(data)) Changed solution : with open( '/Users/metal/Documents/test_pb2.py','rb') as text_file: response = HttpResponse(text_file, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=test_pb2.py' return response As you can see above I removed FileWrapper and was atleast able to send the … -
django viewflow - StartFunction not assigning task owner info
Followed the answer provided to How to create a django ViewFlow process programmatically However it is not assigning (or persisting) owner info in the activation record. @flow_start_view def start_process(request): request.activation.prepare(request.POST or None,) request.activation.flow_task.owner = request.user request.activation.flow_task.task_title = "Start Process" Also tried below and it is resulting in an error "'ManagedStartViewActivation' object has no attribute 'assign'" @flow_start_view def start_process(request): request.activation.prepare(request.POST or None,) request.activation.assign(request.user) request.activation.flow_task.task_title = "Start Process" -
Django function doesn't return HTML page
guys! I'm adding pagination on my website. This is my function: views.py def ProductList(request, category_slug=None, page_number=1): content = {} category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) current_page = Paginator(products, 2) content['category'] = category content['categories'] = categories content['products'] = current_page.page(page_number) return render(request, 'product/list.html', content) urls.py urlpatterns = [ url(r'^$', views.ProductList, name='ProductList'), url(r'^page/(\d+)/$', views.ProductList, name='ProductList'), ] But every time I'm trying to get next page I see this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/page/2/ Raised by: shop.views.ProductList I can't really understand what I'm doing wrong. Thank you. -
Django Authentication Tokken, can't open the admin page
I'm trying to validate my users with Tokken Authentication, the problem is that I don't know how to add a header with the Tokken so I can enter into my admin panel. Before I implemented this method if I typed http://127.0.0.1:8000/admin I could acces it with no problems. Here's my models.py class Stock(models.Model): ticker = models.CharField(max_length=10) open = models.FloatField() close = models.FloatField() volume = models.IntegerField() def __str__(self): return self.ticker # This code is triggered whenever a new user has been created and saved to the database @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) Here's my views.py (I think this is were I have to change some things): @api_view(['GET', 'POST']) def stock_list(request, format=None): if request.method == 'GET': stocks = Stock.objects.all() serializer = StockSerializer(stocks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = StockSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'POST', 'DELETE']) def stock_detail(request, pk, format=None): try: stock = Stock.objects.get(pk=pk) except Stock.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = StockSerializer(stock) return Response(serializer.data) elif request.method == 'PUT': serializer = StockSerializer(stock, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': stock.delete() return Response(status=status.HTTP_204_NO_CONTENT) Here's my urls app: urlpatterns = [ url(r'^stocks/$', views.stock_list), … -
boto3 how do i detect and handle bouce email with aws ses boto3 / django-amazon-ses
I am using this to send email in django: client = boto3.client('ses', region_name='us-east-1') conn = mail.get_connection('django_amazon_ses.EmailBackend') email = EmailMessage( 'Subject', 'Content', 'email2@mysite.com', ['email3@bademail.com', 'email4@bademail.com'], headers={'From': 'email1@mysite.com'}, ) conn.send_messages([email]) and i try to use django-amazon-ses to catch post sending, but it doesnt seem to tell anything on bounces: @receiver(post_send) def log_message(sender, message=None, message_id=None, **kwargs): logging.debug("log_message post_send") this is the output: content-type;host;x-amz-date 2c161329d17a9f0a2845a408f39916d4d106cbe8f032afda9e3f2e2fb231d61d 2018-04-14 12:39:03,783 DEBUG StringToSign: AWS4-HMAC-SHA256 20180414T123903Z 20180414/us-east-1/ses/aws4_request 77dd58301f41da183527ff7d18b53aa2b8bd421dc92acc60c57fc632efde2345 2018-04-14 12:39:03,784 DEBUG Signature: 8203af64bca6944d7c41f50a108cbe7963823ab029745ddcc22593923b1f369c 2018-04-14 12:39:03,784 DEBUG Sending http request: <PreparedRequest [POST]> 2018-04-14 12:39:03,785 INFO Starting new HTTPS connection (1): email.us-east-1.amazonaws.com 2018-04-14 12:39:05,042 DEBUG "POST / HTTP/1.1" 200 338 2018-04-14 12:39:05,043 DEBUG Response headers: {'x-amzn-requestid': 'd10cef18-3fe0-11e8-91c4-8304571e55d9', 'content-type': 'text/xml', 'content-length': '338', 'date': 'Sat, 14 Apr 2018 12:39:04 GMT'} 2018-04-14 12:39:05,043 DEBUG Response body: b'<SendRawEmailResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">\n <SendRawEmailResult>\n <MessageId>01000162c42a8923-16b72c98-fafa-4c9b-9873-5dd775dcff7d-000000</MessageId>\n </SendRawEmailResult>\n <ResponseMetadata>\n <RequestId>d10cef18-3fe0-11e8-91c4-8304571e55d9</RequestId>\n </ResponseMetadata>\n</SendRawEmailResponse>\n' 2018-04-14 12:39:05,044 DEBUG Event needs-retry.email.SendRawEmail: calling handler <botocore.retryhandler.RetryHandler object at 0x126773470> 2018-04-14 12:39:05,044 DEBUG No retry needed. what is the meaning of this: 2018-04-14 12:39:05,044 DEBUG Event needs-retry.email.SendRawEmail: calling handler <botocore.retryhandler.RetryHandler object at 0x126773470> My question is how to detect and handle bouces from aws ses sending email ? -
Django templates doesn't load the content of child templates
I'm working on a project using Django(1.11) in which I have created a base.html template in which I have defined all the universal HTML code of my project like required CSS and js files. But when I extend this template in my child templates it only loads the base template not the content of child template. Here's what I have tried: base.html: {% load static %} {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <!-- Favicons --> <link rel="apple-touch-icon" href="{% static 'images/kit/free/apple-icon.png' %}"/> <link rel="apple-touch-icon" href="{% static 'images/kit/free/favicon.png' %}"/> <!-- Fonts and icons --> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:400,700|Material+Icons"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css"/> <link rel="stylesheet" href="{% static 'css/material-kit.css' %}"> {% block head %} {% block title %} {% endblock %} {% endblock %} </head> <body class="signup-page"> <nav class="navbar navbar-color-on-scroll navbar-transparent fixed-top navbar-expand-lg " color-on-scroll="100" id="sectionsNav"> <div class="container"> <div class="navbar-translate"> <a class="navbar-brand" href="#">Docrest Gui </a> <button class="navbar-toggler" type="button" data-toggle="collapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span> </button> </div> <div class="collapse navbar-collapse"> <ul class="navbar-nav ml-auto"> <li class="dropdown nav-item"> <a href="#" class="dropdown-toggle nav-link" data-toggle="dropdown"> <i class="material-icons">apps</i> Components </a> <div class="dropdown-menu dropdown-with-icons"> <a href="#" class="dropdown-item"> <i class="material-icons">layers</i> All Components </a> <a href="http://demos.creative-tim.com/material-kit/docs/2.0/getting-started/introduction.html" … -
How to render two different Forms in one Template?
I'm a newbie in Django. Please be helping out.I have written two forms in forms.py forms.py from django import forms class MyForm(forms.Form): PRODUCT_SIZE = ( ('1', 'US letter 8.5x11 in'), ('2', 'US Trade 6x9 in'), ('3', 'commic book 6.63x10.25 in'), ('4', 'pocket book 4.25x6.88 in') ) my_choice_field = forms.ChoiceField(choices=PRODUCT_SIZE,widget=forms.RadioSelect()) class BindingForm(forms.Form): BINDING = ( ('1', 'Coil Bound Paperback'), ('2', 'Perfect Bound Paperback'), ('3', 'Saddle Stitch Paperback'), ) my_binding_choice = forms.ChoiceField(choices=BINDING, widget=forms.RadioSelect()) views.py from django.shortcuts import render,render_to_response from .forms import MyForm,BindingForm def my_view(request): form = MyForm() return render(request,'base.html',{'form': form}) def my_binding_view(request): form = BindingForm() return render(request,'base.html',{'binding_form':form}) templates/base.html <h2>Paper Size</h2> {% for ele in form %} <div class="myradiolist"> {{ ele }} </div> {% endfor %} <h2>Binding</h2> {% for ra in Binding_form %} <div class="my2ndradiolist"> {{ ra }} </div> {% endfor %} But its only rendering First part of template class called "my radio list " to the front end while only showing the part of the second class and nothing else after that. where is the problem? or im doing whole thing wrong? how can i show 2nd part of the template in same template as when i show 2nd part in different template,it renders... thanks in advance -
Django form not redirect after submit
So I made a form but after i clicked Submit button, it not redirected at all. I don't know if the form is actually submitted or not, because after i clicked submit, the url just added /submit, not even redirect to the right page. Here's my views: def submit_company_profile(request): if request.session['status'] == "employer": form = CompanyProfileEdit(request.POST or None) if(request.method == 'POST' and form.is_valid()): company_creator_profile_id = request.session['profile_id'] country = request.POST.get('country', False) province = request.POST.get('province', False) city = request.POST.get('city', False) company_name = request.POST.get('company_name', False) company_description = request.POST.get('company_description', False) company_website = request.POST.get('company_website', False) company_logo = request.POST.get('company_logo', False) query = Company.objects.filter(company_creator_profile_id=request.session['profile_id']) query_size = query.count() if query_size > 0: company = query[0] company.country = country company.province = province company.city = city company.company_name = company_name company.company_description = company_description company.company_website = company_website company.company_logo = company_logo company.save() else: Company.objects.create( company_creator_profile_id=request.session['profile_id'], country = country, province = province, city = city, company_name = company_name, company_description = company_description, company_website = company_website, company_logo = company_logo ) return redirect(reverse('app_employer:company_profile')) Here's my HTML <form method="POST" action="{% url 'app-employer:submit-company-profile' %}"> {% csrf_token %} {% for field in company_form %} <div class="form-group"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{field}} </div> {% endfor %} <div class="upload"> <p><strong>Upload your company logo</strong></p> <div class="row"> <div class="col-sm-4"> <button class="btn btn-block … -
Django : Multiple Images with Model Formset to be used in Edit View
I have done adding multiple images in a single post. but the issue i am observing is when i try to edit/update the Images. It just doesn't work. Please suggest a way of doing it. Below is the post_create view given which is working just fine. i need to create post_edit view through which i can be able to change the images as i want. I already tried. Please help. models.py class Images(models.Model): post = models.ForeignKey(Post) image = models.ImageField(upload_to="images/", blank=True, null=True) def __str__(self): return "Image" + self.post.title views.py: def post_create(request): ImageFormset = modelformset_factory(Images, fields=('image',), extra=4) if request.method == 'POST': form = PostCreateForm(request.POST) formset = ImageFormset(request.POST or None, request.FILES or None) if form.is_valid() and formset.is_valid(): post = form.save(commit=False) post.author = request.user post.save() for f in formset: try: photo = Images(post=post, image=f.cleaned_data['image']) photo.save() except Exception as e: break return redirect('post_list') else: form = PostCreateForm() formset = ImageFormset(queryset=Images.objects.none()) context = { 'form': form, 'formset': formset, } return render(request, 'blog/post_create.html', context)