Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save data to database using Django forms
my Save button does not save the user entered data into the database in a django form, where is the problem? models.py class Cemetery(models.Model): id = models.AutoField(primary_key=True) name=models.CharField(verbose_name="Cemetery Name",max_length=100) city=models.CharField(max_length=30) zipcode=models.CharField(max_length=5) date_created=models.DateTimeField(editable=False, auto_now_add=True) date_modified= models.DateTimeField(editable=False, auto_now=True) created_by=models.ForeignKey('auth.User') def __str__(self): return str(self.id) +'-' + self.name + ' - ' + self.city forms.py class CemeteryForm(forms.ModelForm): class Meta: model=Cemetery fields=('name','city','zipcode',) views.py def cemetery_add(request): if request.method=="POST": form=CemeteryForm(request.POST) if form.is_valid(): cemetery=form.save(commit=False) cemetery.name=request.name cemetery.city=request.city cemetery.zipcode=request.zipcode cemetery.created_by=request.user cemetery.date_created=timezone.now() cemetery.save() return redirect('cemetery_list') else: form=CemeteryForm return render(request,'heaven/edit_cemetery.html',{'form':form}) template {% extends 'heaven/base.html' %} {% block content %} <!-- Edit Cemetery --> <h2>New Cemetery</h2> <form method="POST" class="cemetery-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} when I push the save button, this is the error I receive: AttributeError at /cemetery_add/ 'WSGIRequest' object has no attribute 'name' -
Django web server running on digital ocean machine, how do i view it on my laptop?
Also, can I make some sort of domain as well? Very nooby with this stuff, tried a bunch of tutorials and did not work. Django server runs with no errors while I am ssh'd into it. -
Django How To create first search the table name in database using radiobutton than search the content in that table
Django How To create first select the customer type in table in database using radiobutton than search the content in that table()using column name) I am creating one table in model.py from __future__ import unicode_literals from django.db import models from django.core.validators import RegexValidator TITLE_CHOICES = ( ('MR', 'Mr.'), ('MRS', 'Mrs.'), ('MS', 'Ms.'), ) KYC_CHOICES = ( ('YES', 'yes'), ('NO', 'no'), ) CUSTOMERTYPE_CHOICES =( ('INDIVIDUAL', 'individual'), ('PROSPECT', 'prospect '), ('SME ', 'sme'), ('CORPORATE', 'corporate'), ) class Customer (models.Model): First_Name = models.CharField(max_length=30) Middle_Name = models.CharField(max_length=30) Last_Name = models.CharField(max_length=30) Date_of_Birth = models.DateField(max_length=10) SCV_ID = models.CharField(max_length=9) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") Phone_Number = models.CharField(validators=[phone_regex], blank=True ,max_length=10) # validators should be a list Address = models.TextField() Customer_Type = models.CharField(max_length=15, choices=CUSTOMERTYPE_CHOICES) Title = models.CharField(max_length=3, choices=TITLE_CHOICES) KYC_Compliance_Flg = models.CharField(max_length=3, choices=KYC_CHOICES) Bank_CIF = models.CharField(max_length=30) Card_CIF = models.CharField(max_length=30) BIR_Login_Name = models.CharField(max_length=30) Credit_Card_Number = models.PositiveIntegerField() Debit_Card_Number = models.PositiveIntegerField() Card_Account_Number = models.PositiveIntegerField() Card_DDA_Account_Number = models.PositiveIntegerField() Passport_Number = models.PositiveIntegerField() National_ID = models.PositiveIntegerField() class Meta: unique_together = ('Passport_Number', 'National_ID',) def _get_Full_Name(self): "Returns the person's full name." return '%s, %s %s' % (self.First_Name, self.Middle_Name,self.Last_Name) Full_Name = property(_get_Full_Name) class Meta: ordering = ['First_Name', 'Middle_Name','Last_Name'] In that How to create at fontend first select … -
python2.7 django 1.10.3. Can't use oauth2app
I have installed oauth2app by pip and I added it to setting.py, when I make migtate mysql didn't creat tables for oauth2app. -
Overriding create method in Django RestFramework to POST data
I'm currently using Django RestFramework to create APIs that use both GET and POST to retrieve/insert data within my Django application. I currently have a database model called TransactionDateTime that has a field called start_dt (see below), which takes DateTimeField. The challenge is that I'm passing a string in my json POST data structure (see below) and I need to override the create method in order to loop through the JSON structure to convert the string to the appropriate datetime structure. I know the logic to be used to successfully convert string to datetime, because I was able to perform it in the Django shell (see below), but I don't know how to override the create method and write the appropriate code within the create method to make this happen. Please assist. Below is a copy of my view that is successfully returning JSON data structure via GET, with a BIG question within the create method TransactionDateTime model from models.py class TransactionDateTime(models.Model): room = models.ForeignKey(Room, on_delete = models.CASCADE) start_dt = models.DateTimeField('start_dateTime') end_dt = models.DateTimeField('end_dateTime', blank=True, null=True) def __str__(self): return str(self.start_dt) Data Structure to be used on POST [ { "start_dt": "2015-01-28 03:00:00" }, { "start_dt": "2015-01-28 05:30:00" } ] Logic … -
"No module named memcache" error in openstack keystone
I have configured Openstack newton on ubunu 16.04 LTS. It works fine Now i have planned to integrate Murano in to this. All progressed fine..When i am running dashboard using "tox -e venv -- python manage.py runserver " command. I am able to run the murano dashboard. When im accessing environment tab it displaying error "Error: There was an error communicating with server". And log message display a error "No module named mamcache". For your reference error message below: {"title": "Internal Server Error", "code": 500, "error": {"message": "No module named memcache", "traceback": "Traceback (most recent call last):\n File \"/root/murano/murano/murano/api/middleware/fault.py\", line 130, in process_request\n return req.get_response(self.application)\n File \"/root/murano/murano/.tox/venv/local/lib/python2.7/site-packages/webob/request.py\", line 1299, in send\n application, catch_exc_info=False)\n File \"/root/murano/murano/.tox/venv/local/lib/python2.7/site-packages/webob/request.py\", line 1263, in call_application\n app_iter = application(self.environ, start_response)\n File \"/root/murano/murano/.tox/venv/local/lib/python2.7/site-packages/webob/dec.py\", line 130, in call\n resp = self.call_func(req, *args, **self.kwargs)\n File \"/root/murano/murano/.tox/venv/local/lib/python2.7/site-packages/webob/dec.py\", line 195, in call_func\n return self.func(req, *args, **kwargs)\n File \"/root/murano/murano/.tox/venv/local/lib/python2.7/site-packages/keystonemiddleware/auth_token/init.py\", line 320, in call\n response = self.process_request(req)\n File \"/root/murano/murano/.tox/venv/local/lib/python2.7/site-packages/keystonemiddleware/auth_token/init.py\", line 552, in process_request\n resp = super(AuthProtocol, self).process_request(request)\n File \"/root/murano/murano/.tox/venv/local/lib/python2.7/site-packages/keystonemiddleware/auth_token/init.py\", line 348, in process_request\n data, user_auth_ref = self._do_fetch_token(request.user_token)\n File \"/root/murano/murano/.tox/venv/local/lib/python2.7/site-packages/keystonemiddleware/auth_token/init.py\", line 388, in _do_fetch_token\n data = self.fetch_token(token)\n File \"/root/murano/murano/.tox/venv/local/lib/python2.7/site-packages/keystonemiddleware/auth_token/init.py\", line 661, in fetch_token\n cached = self._cache_get_hashes(token_hashes)\n File \"/root/murano/murano/.tox/venv/local/lib/python2.7/site-packages/keystonemiddleware/auth_token/init.py\", line 644, in _cache_get_hashes\n cached = self._token_cache.get(token)\n … -
Django blog with PostgreSQL DB on AWS Elastic Beanstalk and RDS
I'll try to keep the story as short as possible. I've build a simple blog using Django and PostgreSQL I am am having a really hard time deploying it on AWS Elastic Beanstalk. I have tried every single tutorial I could find (the aws one, the realpython one, etc.), every answer to questions on stackoverflow and I have failed miserably. I have tried using the UI and the CLI and I always ended up with errors and problems. I've setup a simple virtual enviroment, I have installed Django, psycopg2 but for some reason I just cannot figure this out. I built the .ebextensions and .elasticbeanstalk folders and the requirements.txt with no luck in the end. Can someone please provide a step-by-step simple guide for dummies like me on how can I get this blog up and running, before I lose my mind? In the end I want to end up with a working blog on EB and with a PostgreSQL dc on RDS. I would be grateful to anyone willing to shine some light on this. Thank you very much -
Django filter in ModelForm with specific models
class Report(models.Model): # .... product = models.ForeignKey(Product) class Product(models.Model): name = models.CharField(max_length=50) class Item(models.Model): box = models.ForeignKey(BoxInTransport) product = models.ForeignKey(Product) class BoxInTransport(models.Model): transport = models.ForeignKey(Transport) box = models.ForeignKey(Box) This is - in short - structure of models. And I have a view to let me create new report: class ReportCreateView(CreateView): model = Report form_class = ReportForm def get_form_kwargs(self): # updating to get argument from url kwargs = super(DifferenceCreateView, self).get_form_kwargs() kwargs.update(self.kwargs) return kwargs and the form: class ReportForm(ModelForm): class Meta: model = Report fields = [ 'product' ] def __init__(self, box_nr=None, *args, **kwargs): super(ReportForm, self).__init__(*args, **kwargs) self.fields['product'].queryset = ??? How can I get onlny this products which belong to specify box? To be more meaningfully: Only products which: Item.objects.filter(box__box__box_code=box_nr) Now I get all Items what I need, but I need pass to self.fields['products'] onlny product form this new Items queryset. Could you help me? -
Django- Session Variables in user_passes_test
I'd like to run method decorator @user_passes_test and use a session variable in that test: def has_correct_search(user): source = request.session['source'] if ApiSearch.objects.filter(user=user, source=source).exists(): return True else: return False The problem is that I don't know how to pass the request object: @method_decorator(user_passes_test(has_correct_search, redirect_field_name=search_url_name)) def dispatch(self, request, *args, **kwargs): (...) Is there any trick to getting ahold of session variables in this case? What are my options? -
2nd Django form not rendering in HTML
I can not figure out what is happening here. I have two forms but the second one will not render any input fields to the template. The second form is in a different template than the first. I am still very new to programming but I have searched everywhere for an answer to this with no luck. forms.py from django import forms class ContactForm(forms.Form): contact_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Name*'})) contact_email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Email*'})) contact_phone = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Phone Number*'})) content = forms.CharField( required=True, widget=forms.Textarea(attrs={'placeholder': 'Your comments'}) ) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['contact_name'].label = "" self.fields['contact_email'].label = "" self.fields['contact_phone'].label = "" self.fields['content'].label = "" class EstimateForm(forms.Form): contact_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Name*'})) contact_email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Email*'})) contact_phone = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Phone Number*'})) def __init__(self, *args, **kwargs): super(EstimateForm, self).__init__(*args, **kwargs) self.fields['contact_name'].label = "" self.fields['contact_email'].label = "" self.fields['contact_phone'].label = "" views.py def contact(request): form_class = ContactForm if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): messages.success(request, 'Profile details updated.') contact_name = request.POST.get( 'contact_name' , '') contact_email = request.POST.get( 'contact_email' , '') contact_phone = request.POST.get( 'contact_phone' , '') form_content = request.POST.get('content', '') # Email the profile with the # contact information template = get_template('contact_template.txt') … -
How to draw image from raw bytes using ReportLab?
All the examples I encounter in the internet is loading the image from url (either locally or in the web). What I want is to draw the image directly to the pdf from raw bytes. -
How can I include my javascript file?
I need to inculde my javascript a file in django. I know how to include files of CSS. I'm doing it so way: <link rel="stylesheet" href="{% static 'demo/style.css' %}"/> How can I include my javascript file? -
html page in iframe can't find its css file
Well this question is complicated because I'm working within a django framework. This should not be a factor though, I think. At least the people at the django mailing list seem to think it is an html problem. My main (top page) html page includes the following code: </iframe> The src is so terse because the call is handled through a django view which has the code : from django.shortcuts import render def mainPage(request): return render(request, 'main/main2.html') def welcome(request): return render(request, 'main/welcome.html') The css files are in a static files directory. The main page loads its css file OK. The welcome.html file loads ok but does not load its css file. It has the following standard header: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Welcome To UUCLB Archives</title> *<!--Setup stylesheet-->* <link rel="stylesheet" type="text/css" href="/static /welcomePage.css"/> <!-- The setup for jQuery --> <script src="/static/jquery.js"></script> </head> The welcome.html css file does not load nor is there any indication that welcomePage.css is having any effect whatsoever. Why would the main page ( called through the same view ) load and use its css file while the welcome.html file called by the iframe does not. I hope I have all of the relevant code … -
Django - How to use an increment counter inside of template
I'm trying to have my form not display (display:none;) if the maximum number of people signed up for a specific event is reached/exceeded. signups is a model with fields eventname and fullname. I'm also using a ListView, FormView to loop through the list of events, each with a sign up form. I'm trying to do something like: <form action="/events/" class="form" method="POST" style="{% for signups in signup %}{% if signups.eventname == events.name %}*counter increment here*{% if *counter value* >= events.maximum %}display:none;{% endif %}{% endif %}{% endfor %}" id="{{ events.name }}" name="{{ events.name }}"> {% if signups.eventname == events.name %} checks the model signups for objects with matching eventnames so that only objects for the wanted event is counted. This is all inside of {% for events in events_list %}{% endfor %} and consider text inside asterisks comments. How would I do this? If you would like to see any other files or information, I will gladly edit this. -
Django Template not rendering MultipleChoiceField correctly
I have an issue when setting initial values in my MultipleChoiceField in a class that my template does not render those as being selected. class TestForm(forms.Form): choices = [('choice1', 'A'), ('choice2', 'B'), ('choice3', 'C')] test = forms.MultipleChoiceField(choices=choices, label='Test', initial=['choice1','choice2']) f = TestForm() When I run this using the manage.py shell I get the correct HTML output print f <tr><th><label for="id_test">Test:</label></th><td><select multiple="multiple" id="id_test" name="test"> <option value="choice1" selected="selected">A</option> <option value="choice2" selected="selected">B</option> <option value="choice3">C</option> </select></td></tr> You can see that it has the selected attribute in the code. But when I have this in my template: {% for field in f %} <p>{{ field.label_tag }}<br>{{ field }}</p> {% endfor %} The selected attributes are not rendered Even if I just have in place of those 3 lines {{ form.as_p }} it still does not work. Is there something else I need to do in the form class to tell it to render the pre-selected choices? Thanks -
Reverse for 'product_list_by_category' with arguments '('books',)' and keyword arguments '{}' not found
I have tried all the questions and answers on stackoverflow and read and write and rewrite my template, but I keep getting the error "Reverse for 'product_list_by_category' with arguments '('books',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['shop/(?P[-\W]+)/$']" Here is my model.py class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering=('name',) verbose_name = 'caterory' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', kwargs={'slug': self.slug}) view: def product_list(request, category_slug=None): 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) return render(request, 'shop/list.html', {'category': category, 'categories': categories, 'products': products}) Here is my urls.py url(r'^(?P<category_slug>[-\W]+)/$', views.product_list, name='product_list_by_category'), And this is my template: {% block content %} <div id="sidebar"> <h3>Catergories</h3> <ul> <li {% if not category %} class="selected" {% endif %}> <a href="{% url 'shop:product_list' %}">All</a> </li> {% for c in categories %} <li {% if category.slug == c.slug %} class="selected" {% endif %}> <a href="{{ c.get_absolute_url }}">{{ c.name }}</a> </li> {% endfor %} </ul> </div> {% endblock content %} -
Accessing to objects of a dynamic way in django template
I have the following class based view in which I perform to queryset: class PatientDetail(LoginRequiredMixin, DetailView): model = PatientProfile template_name = 'patient_detail.html' context_object_name = 'patientdetail' def get_context_data(self, **kwargs): context=super(PatientDetail, self).get_context_data(**kwargs) queryset= RehabilitationSession.objects.filter(patient__slug=self.kwargs['slug']) context.update({'patient_session_data': queryset,}) return context When I acces the value of patient_session_data key sent, in my template: {% extends "base.html" %} {% block content %} {{patient_session_data}} {% endblock content %} I get this the QuerySet object: <QuerySet [<RehabilitationSession: Hernando Zambrano Cuellar>, <RehabilitationSession: Hernando Zambrano Cuellar>, <RehabilitationSession: Hernando Zambrano Cuellar>]> I want access to specific attibute named upper_extremity of my RehabilitationSession model, then I make this: {% for upperlimb in patient_session_data %} {{upperlimb.upper_extremity}} {%endfor%} And I get this in my template: Izquierda Izquierda Izquierda This mean, three times the value, because my queryset return me three objects. This is logic. For access to value of a separate way I make this in my template: {{patient_session_data.0.upper_extremity}} And I get: Izquierda My goal I unknown the amount of querysets objects RehabilitationSession that will be returned by the queryset executed in my PatientDetail cbv, because the number is dynamic, may be any amount of objects returned. I want read the value content of each patient_session_data upper_extremity and accord to the value make something … -
Django LDAP model
What is the best way to use LDAP as a Django datasource? I want to use the generic ListView with a Django model which is populated utilizing an OpenLDAP server. I figured out already that I could use a Django manager to manipulate the affected QuerySet but it looks like the QuerySet has to be initialized by some database before. -
Django: HTML to WordprocessingML converter
I'm trying to convert HTML content from a rich text editor to docx format in a Django 1.8 application. So far, I've tried: python-docx: Easy to convert from docx to HTML. Can't see how to do the opposite oodocx: Easy to build a docx by adding HTML chunks, but not easy to do it with a big amount of existent HTML code. Using zipfile to open an empty existent docx, and try to put some HTML directly in word/document.xml. It obviously didn't work, but I had to try... So, I think my options are: Write my own html-to-docx library, maybe based in oodocx. Overkill Convince my boss to drop docx format, and just use plain HTML Am I missing something here? -
How to compare ArrayField type model value and display if exist in the array?
I have data saved in my db model for - Fields: id, flags # flags is an ArrayField Sample values like: (1, [[1, 'Tag 1', 0],[2, 'Tag 2', 1], [3, 'Tag 3', 0]]) (2, [[1, 'Tag 4', 1],[2, 'Tag 5', 0], [3, 'Tag 6', 1]]) I am using following way to fetch the specific row and display the tags column data- get_flag = FlagMain.objects.filter(id=2) From the result, how can I view the "flags" column data? Also, how can I compare with array value which exist in second position- i.e. [2, 'Tag 5', 0]? I have 2 variable temp_id=2 and flag_name='Tag 5', so I want to compare those value with second position array value in db table row #2. Not sure if its possible or not! But hoping to get advise from some experts. Thanks in advance -
Django returns error on ModelChoiceField with values rendered in runtime
First the idea: I have a manger, who manages different branches each of which has restaurants assigned to them. I want him to be able to make orders and choose restaurants available for his specific branch. I use a class with static values to remember which manager is making the order. Second: the code. forms.py: class NewOrderFormManager(Form): restaurant = forms.ModelChoiceField(queryset=None) # other fields here def __init__(self, *args, **kwargs): super(NewOrderFormManager, self).__init__(*args, **kwargs) branches = StaticData.get_branches_assigned_to_manager() self.fields['restaurant'].queryset = Restaurant.objects.filter(branch__in=branches) views.py: class NewOrderFromManagerFormView(FormView): template_name = 'admin_custom/new_order_from_manager_form.html' form_class = NewOrderFormManager def get(self, request, *args, **kwargs): StaticData.find_branches_corresponding_to_manager(request.user) return super(NewOrderFromManagerFormView, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): StaticData.find_branches_corresponding_to_manager(request.user) return super(NewOrderFromManagerFormView, self).post(request, *args, **kwargs) def form_valid(self, form): # some code to be executed storage class: class StaticData: branches = None @classmethod def find_branches_corresponding_to_manager(cls, user): cls.branches = None if roles.has_role(user, roles.ROLE_ADMIN): cls.branches = Branch.objects.all() elif roles.has_role(user, roles.ROLE_COURIER_MANAGER): cls.branches = user.couriermanager.branches.all() @classmethod def get_branches_assigned_to_manager(cls): return cls.branches Third: the problem. There seams to be some trouble with posting a request for some specific restaurant. When I access clean() method I can find an error saying that the choice I've made is not valid and I should choose another. I am using superadmin'account for this purpose and I've checked that … -
django.db.utils.IntegrityError: NOT NULL constraint failed:
I have the following Django 1.10 model that is giving an error when I run: python manage.py makemigrations ... return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: steps_entry.project_id What am I doing wrong here? The models.py code: from __future__ import unicode_literals from django.db import models # Create your models here. class Project(models.Model): project_title = models.CharField(max_length=200) created_date = models.DateTimeField('date created') def __str__(self): return self.project_title class Entry(models.Model): title = models.CharField(max_length=200) REFERENCE = 'reference' BACKBURNER = 'backburner-item' ACTION_STEP = 'action-step' CONTAINER_CHOICES = ( (REFERENCE, 'Reference'), (BACKBURNER, 'Backburner'), (ACTION_STEP, 'Action'), ) container = models.CharField(max_length=200, choices=CONTAINER_CHOICES, default=ACTION_STEP) project = models.ForeignKey('Project', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.title -
Customize ImageField.image.url
I have a Django model for a user-uploaded photo. It contains a field defined as class Photo(models.Model): image = models.ImageField(upload_to='photo_image_files') @property def name(self): return filename_without_extension ... and settings.py defines MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') This means images are saved in /media/photo_image_files/. I would like to have JPEG files accessible at /jpeg/:filename and hide the actual path to the images from visitors. I have defined the corresponding view and url. However, now {{ photo.image.url }} predictably points to /media/photo_image_files/filename.jpg. As a workaround, I include images as <img src="/jpeg/{{ photo.name }}" /> But that means I specify the location twice, in urls.py and in the template. How can I customise the URL? -
Django - Keep the form values filled after form validation
When I submit the form and it is not validated for some reason the form is rendered all blank. I am not using the {{ form }} to render the complete form, I like to let other people to customize it. This is a part of the form: <form method="post" action="" enctype="multipart/form-data">{% csrf_token %} <div class="panel panel-default"> <div class = "panel-heading"> Informações de Contato </div> <div class = "panel-body"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> <input type="text" class="form-control" id="id_{{ anuncioForm.nome_contato.name }}" name="{{ anuncioForm.nome_contato.name }}" value= "{{ request.user.first_name }} {{request.user.last_name}}" placeholder="Nome"> </div> <p class="help-text">{{ anuncioForm.nome_contato.help_text }} </p> <br> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span> <input type="text" class="form-control" id="id_{{ anuncioForm.email_contato.name }}" name="{{ anuncioForm.email_contato.name }}" value="{{ request.user.email }} " placeholder="E-mail"> </div> <p class="help-text">{{ anuncioForm.email_contato.help_text }} </p> <br> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-glyphicon glyphicon-phone"></i></span> <input type="text" class="form-control" id="id_{{ anuncioForm.telefone_contato.name }}" name="{{ anuncioForm.telefone_contato.name }}" placeholder="Telefone ou Celular"> </div> <p class="help-text">{{ anuncioForm.telefone_contato.help_text }} </p> </div> </div> This the view.py def anunciar_imovel(request): ImageFormSet = modelformset_factory(ImagensAnuncio, form=ImagensForm, extra=3) if request.method == 'POST': anuncioForm = AnuncioForm(request.POST, request.FILES) formset = ImageFormSet(request.POST, request.FILES, queryset=ImagensAnuncio.objects.none()) if anuncioForm.is_valid() and formset.is_valid(): novo_anuncio = anuncioForm.save(commit=False) novo_anuncio.user = request.user novo_anuncio.save() for form in formset.cleaned_data: imagem = form['imagem'] photo = ImagensAnuncio(anuncio=novo_anuncio, imagem=imagem) photo.save() return render(request, 'account/index.html') … -
Can i integrate django-oscar or django-shop in an existing django project?
Could i use those in an existing project and have only one login ? Or if that's not possible, could I have a separate project on a subdomain and have one login for both projects? I am fairly new to Django and got pretty confused by the documentations, so any advice would be appreciated.