Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What if you send post data from one form to another form in Django?
I want to send POST data from A to B. I worte code in a way like below. A views.py class A(view): def get(self, request, *args, **kwargs): I do my work in here return render(request, 'A template.html', {passing data in context}) A template.html <p> test : {{ passingdata.name }}</p> <form action="{% url to B url %}" method="post">{% csrf_token %} <input type="integer" name="num_of_datas"> <input type="integer" name="product_pk" value={{passiongdata.id}} hidden="True"> <input type="submit" value ="order"> </form> B views.py class ProductOrderView(FormView): template_name = 'B template.html' form_class = Form success_url = '/success/' B template.html <form action="." method="post">{% csrf_token %} {{ form }} <input type="submit" value="confirm"> </form> If I move to B by clicking submit button which direct to B (action = "URL to B"), form shows with error message like 'this field is required'. but If i hit URL to B on browser and see form, it shows properly. I don't know what it work differently. moving another form by action attribute doesn't seem to work properly. I couldn't set initial value in form with init method. -
Adding a link/button in django admin app page
My question is simple and I have seen many answers and related question to this. None of them is so clear and specifying what to add on what page. Say my application url is : http://mydjnagoapp.com/admin/pollsapp where pollsapp is my app name. This page has list of all my models to which I can add data(with add and change buttons). I have created new admin views, now I want to add links for those views on my app page where I have all my models. (not specific about the position). Is it possible. If so can someone give the list of things in detail, like what pages can be edited and where to add what. I tried following this but I didn't get where the link/button will be added in this case. Thanks in advance -
Python Django view to return POST-request to client
I have built a web shop with Django and during payment i build-up a POST-request in the view consisting of necessary payment parameters, which then are sent to the payment gateway, and the payment gateway are happy with the POST-request in general. So far so good, i want to do this without posting hidden forms visible in the HTML source:code in the browser, with other words i want to build and return the POST-request and data from the Django view to the client. So i want to do something like this to make sure the POST-request originate from the client and not the server to get around session problem(if its possible to return sessions and act like a man in the middle I'm open for that type of solutions as well): return requests.post('https://payment.gw/PostAPI/Init', data = payload) doing this i get the error: Django Version: 1.8.13 Exception Type: AttributeError Exception Value: 'Response' object has no attribute 'get' -
How to include image inside an xblock on openedx fullstack
Im trying to include an image on a Xblock inside Openedx. The code works fine on Devstack, but trows an DisallowedFileError on fullstack. On Xblock.py [...] context = { [...] 'img_fullscreen': self.runtime.local_resource_url(self, 'static/img/fs.png'), } frag = Fragment(render_template('static/html/vimeomanage.html', context)) [...] On Xblock.html [...] <img src ="{{img_fullscreen}}" id= "fullscreen-button" alt="Fullscreen" height="20" width="20"/> [...] The error stack: 2016-10-10 04:15:13,190 ERROR 3314 [openedx.core.djangoapps.common_views.xblock] xblock.py:36 - Failed to load xblock resource Traceback (most recent call last): File "/opt/bitnami/apps/edx/edx-platform/openedx/core/djangoapps/common_views/xblock.py", line 31, in xblock_resource content = xblock_class.open_local_resource(uri) File "/opt/bitnami/apps/edx/edx-platform/venv/lib/python2.7/site-packages/xblock/core.py", line 76, in open_local_resource raise DisallowedFileError("Only files from public/ are allowed: %r" % uri) DisallowedFileError: Only files from public/ are allowed: u'static/img/fs.png' -
Django keeps returning old view?
My views.py for a app (Django) was: # yomamabot/fb_yomamabot/views.py from django.views import generic from django.http.response import HttpResponse # Create your views here. class YoMamaBotView(generic.View): def get(self, request, *args, **kwargs): return HttpResponse("Hello World!") Now I made it: # yomamabot/fb_yomamabot/views.py class YoMamaBotView(generic.View): def get(self, request, *args, **kwargs): if self.request.GET['hub.verify_token'] == '2318934571': return HttpResponse(self.request.GET['hub.challenge']) else: return HttpResponse('Error, invalid token') But it still shows hello world whenever I navigate to localhost:8000/<gigantic url> Why? -
Validation does not get called on PATCH
i have a serializer like class MySerializer(serializers.HyperlinkedModelSerializer): age = serializers.HiddenField(default=None) class Meta: model = Profile def validate_age(self, value): # this code not executing in update(put/patch) When i POST the data validate_age get called, but not in the case of PATCH. Is it the intended behaviour or i am missing something ? -
set template_name on django ListView according to user data
my User model have a field which define there structure level in a firm. my goal is to let each user to see his data plus extra data related to user under him. I Have set groups permission to try and see if it would help me get what I want. but permission is not really the point here only redirect to different html( I want to handle logic in the back end ) on function base view this is straight foreword ( i think ) if request.user is ***** my problem is on class base view like this class IndexHome(ListView): model = Task template_name = 'index.html' I am not sure how can I access user in the class? I know I can access the user from an instance self.request.user but how can i make this work class IndexHome(ListView): user = request.user if user.department_director.all(): department_director = list(user.department_director.all()) template_name = 'index1.html' elif user.group_leader.all(): group_leader = list(user.group_leader.all()) template_name = 'index2.html' elif user.team_leader.all(): team_leader = list(user.team_leader.all()) template_name = 'index3.html' elif user.tech_leader.all(): tech_leader = list(user.tech_leader.all()) template_name = 'index4.html' else: template_name = 'index5.html' model = Task or maybe there is a way of setting template_name from the instance and my problem solved? -
Selenium give user the option to fill captcha
I have design problem with my program. I did tool that automatically do things in site X but the problem is that sometimes it gives captcha, and sometimes even more than one time (I mean it can be 5 captchas one by one). I want to give all responsibility for this to the user on the GUI, the API that start the webdrivers is flask that opening process.. My problem is how can I start the process I need on the site, and if there are problem, just send captcha to the user by API, and wait for answer, than continue the process, my problem is because the HTTP protocol is only for one request, response and that's all. Hope the problem clear. Thanks Lior -
Django: Downloading uploaded files
I have form details in this question Django: Adding files to a form gives multiple argument error How to download the uploaded file. When i go to edit view of the form, i can see uploaded file url, but its not downloading. What setting to be changed for development and production mode? Error upon clicking link: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/Certificate.docx Using the URLconf defined in tiktant.urls, Django tried these URL patterns, in this order: ^ ^$ [name='home'] ^ ^login/$ [name='login'] ^ ^logout/$ [name='logout'] ^ ^logout_then_login/$ [name='logout_then_login'] ^ ^dashboard/$ [name='dashboard'] The current URL, media/Certificate.docx, didn't match any of these. -
eroor in receiving data from the Django REST API
I have a mobile app made with ionic2 and Angularjs2. i am running my django on localhost i.e http://127.0.0.1:8000/stocks/ this url returns JSON Data as shown below: [ { "id": 1, "ticker": "FB", "open": 7.0, "close": 10.0, "volume": 500 }, { "id": 2, "ticker": "AMZN", "open": 125.05, "close": 200.98, "volume": 800 }, { "id": 3, "ticker": "MSFT", "open": 1.25, "close": 87.0, "volume": 7000 } ] i am using a provider in my app to get the data from the url import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class GetData { public data:any; constructor(public http: Http) { console.log('Hello GetData Provider'); } load(){ if (this.data) { return Promise.resolve(this.data); } return new Promise(resolve => { this.http.get('http://127.0.0.1:8000/stocks/') .map(res => res.json()) .subscribe(data => { this.data = data; resolve(this.data); }); }); } } this provider i am using in my page to receive the data and show import { Component } from '@angular/core'; import {GetData} from '../../providers/get-data'; import { NavController } from 'ionic-angular'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { public recvData:any; constructor(public navCtrl: NavController, public getData: GetData) { this.loadPeople(); } loadPeople(){ this.getData.load() .then(data => { this.recvData = data; }); console.log("the received data is … -
Permissions on socket
So I am building a docker container for a django app and I am using uwsgi + nginx. Everything seems fine, but when I try running uwsgi with a socket - i get the following error bind(): Operation not permitted [core/socket.c line 230]. I am using supervisor to get everything started. When I use command = /usr/local/bin/uwsgi --http :8000 --module mysite.wsgi it works fine but when I change to command = /usr/local/bin/uwsgi --socket app.sock --module mysite.wsgi --chmod-socket=664uwsgi stops working properly, even when I chmod-socket=664. -
How to sort list of objects that having foreign key in django?
I want to sort the List of User objects based on the Bank balance Model User Class User(model.Model): name, birthday ... Model Bank Class Bank(model.Model): user = model.OneToOneField('user.User') balance = model.IntegerField() ... Data User has 2 objects `Username 1` and `Username2` Bank has 2 objects: - object1: - user: user1 - balance: 5000 - object2: - user: user2 - balance: 3000 List of objects user_list [<User: User 1>, <User: User 2>] If I do sorted(user_list) it will return same list, but I want it sorted based on Bank.balance so the list should be [<User: User 2>, <User: User 1>]. How should I do it? Regards, -
IntegrityError at /person/create/ UNIQUE constraint failed: member_person.user_id
my model: class Person(models.Model): name = models.CharField(max_length=250) slug = AutoSlugField(populate_from='name') birth_date = models.DateField(null=True, blank=True) blood_group = models.CharField(max_length=5) present_address = models.CharField(max_length=250, blank=True) permanent_address = models.CharField(max_length=250, blank=True) user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='member_persons') my views: @require_authenticated_permission( 'member.add_person') class PersonCreate(CreateView): template_name = 'member/person_form.html' model = Person success_url = '/person/' form_class = MemberForm def get_form(self, form_class=None): form = super().get_form(form_class) form.request = self.request return form my form is: class MemberForm(ModelForm): class Meta: model = Person exclude = ('user',) def clean_user(self): user = self.cleaned_data['user'] if Person.objects.filter(user=user).exists(): raise forms.ValidationError("You already submitted data") return user def save(self, commit=True): person = super().save(commit=False) if not person.pk: person.user = get_user(self.request) if commit: person.save() self.save_m2m() return person It worked fine for first instance of person but when I tried to submit member form again with different data it gives following integrity error: Traceback: File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py" in execute 337. return Database.Cursor.execute(self, query, params) The above exception (UNIQUE constraint failed: member_person.user_id) was the direct cause of the following exception: File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/utils/decorators.py" … -
Cannot create super user in django
I know there are questions in SO regarding this issue. But most questions relates to AbstractBaseUser. I did not find any question with AbstractUser. PROBLEM: I want to implement authentication for django project. So I thought of implementing custom user model by inheriting AbstractUser. Here is my Model: class User(AbstractUser): phonenumber = models.CharField(max_length=25,unique=True) username = models.CharField(max_length=25,default="") profile_path = models.URLField(max_length=1500) country = models.CharField(max_length=100,default="") what_do_you_do = models.CharField(max_length=500,default="") where_do_you_do = models.CharField(max_length=500,default="") time_stamp = models.DateTimeField(auto_now_add=True,blank=True) USERNAME_FIELD = 'phonenumber' I have added AUTH_USER_MODEL = 'XXX.User' in settings.py . And I thought of creating a super user. python manage.py createsuperuser But it is giving me following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/sandesh/server/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/sandesh/server/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sandesh/server/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/sandesh/server/local/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/home/sandesh/server/local/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/sandesh/server/local/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() takes exactly 4 arguments (3 given) -
User has no profile in django form
I have extended my user's table with profile table, but while registration of user site only ask email and password for user type "customer" and for user type "promoter" there is another registration form which requires other fields also like date of birth, address, country, state, city etc etc. But after login if we go to account settings page , the account setting page of both types of users are same, that's why for account setting i have created a single django form. class userAccountSettingsForm(forms.Form): email = forms.EmailField(required = True, max_length=50, widget=forms.EmailInput(attrs={ 'class' : 'custome-input promote-input', 'autocomplete' : 'off', 'data-empty-message' : 'Please enter a email.', 'data-error-message' : 'Please enter a valid email.', 'readonly' : 'readonly' })) firstname = forms.CharField(required = True, max_length=50, widget=forms.TextInput(attrs={ 'class' : 'custome-input promote-input', 'autocomplete' : 'off', 'data-empty-message':'Please enter first name.' })) lastname = forms.CharField(required = True, max_length=50, widget=forms.TextInput(attrs={ 'class' : 'custome-input promote-input', 'autocomplete' : 'off', 'data-empty-message':'Please enter last name.' })) dob = forms.DateField(required = False, widget=forms.DateInput(attrs={ 'class' : 'custome-input promote-input', 'id' : 'custom-datepicker', 'autocomplete' : 'off', 'readonly':'readonly' })) phone = forms.IntegerField(required = True, widget=forms.TextInput(attrs={ 'class' : 'custome-input promote-input', 'autocomplete' : 'off', 'data-empty-message':'Please enter mobile number.' })) address = forms.CharField(required = False, max_length=225, widget=forms.TextInput(attrs={ 'class' : 'custome-input … -
How to provide initial data to modelformset?
Basically I'm trying to create a model form set from a simple model, excluding one FK field and trying to fill it in dynamically in the view. Model: class EventRegistration(models.Model): event = models.ForeignKey(Event, related_name='registrations') first_name = models.CharField(max_length=100) Model form set: ... modelformset = modelformset_factory(EventRegistration, exclude=('event',)) ... And the rest of the view: .... object = get_object_or_404(Event.get_published(), slug=slug) if request.method == 'POST': formset = formset(request.POST, initial=[{'event': object}]) if formset.is_valid(): ... else: print formset.errors # This prints [{'event': [u'This field is required.']}] ... As you see, passing initial argument doesn't seem to work here. Or am I missing something? -
installed django 1.8 on mac using pip but django-admin --version not working
I installed django 1.8 on mac using pip but django-admin --version giving error that django command not found.On attempting to reinstall, it shows that it is already installed. -
Improving Django view
I am trying to serialize a DJango queryset object. data = Data.objects.filter(name__icontains='John') data_list = serializers.serialize('json', data, fields=('name', 'title')) return HttpResponse(data_list, content_type="application/json") STDOUT of data_list [{"pk": 4, "model": "XXX", "fields": {"name": "John ad", "title": "Mr. "}}] In the output list I also want to add a dummy field with some hardcoded values. STDOUT of data_list [{"pk": 4, "model": "XXX", "fields": {"name": "John ad", "title": "Mr. ", "Dummy": "Value"}}] Any help on how I should proceed or any links I should read would be appreciated. -
How to rewrite multiple join statements with aggregate in Django ORM way?
I read the documentation on aggregate for Django. But it does not provide an example of how to retrieve both the aggregate and other related fields. And certainly not an example where the tables are joined. I have a working query that I want to be in Django ORM. SELECT SUM(pc.count), p.name, p.art_number from packagecontent pc inner join product p on pc.product_id = p.id inner join package pack on pc.package_id = pack.id where pack.pallet_id is not null group by p.id; How do I rewrite this using Django ORM? Not by using the .raw function by the way. -
Django: Adding files to a form gives multiple argument error
Hi I have a Django project working perfectly fine. Now I need to add a field to it to upload documents. However after adding the file stuffs, Django gives errors. Unable to solve it even after whole day Googling. Models.py class salesman(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL) company=models.ForeignKey(Organisation,related_name='salesmancomp') salesman_name=models.CharField(max_length=250) salesman_address=models.CharField(max_length=750,null=True,blank=True) salesman_PAN=models.CharField(max_length=250,null=True,blank=True) salesman_commission_rate=models.FloatField(null=True,blank=True) attachment = models.FileField(null=True,blank=True) class Meta: unique_together=(('company','salesman_name'),) def __str__(self): return self.salesman_name forms.py class salesmanform(forms.ModelForm): def __init__(self,user, *args, **kwargs): self.request = kwargs.pop('request', None) super(salesmanform, self).__init__(*args, **kwargs) class Meta: model=salesman fields=('salesman_name','salesman_PAN','salesman_commission_rate','salesman_address','attachment',) widgets = { 'salesman_address': forms.Textarea } def clean(self): cleaned_data=self.cleaned_data salesman_name=cleaned_data['salesman_name'] pk=self.instance.pk insert = pk ==None if insert: try: salesman.objects.get(salesman_name=salesman_name,company=self.request.user.company.entity) except salesman.DoesNotExist: pass else: raise forms.ValidationError("Salesman already exist.") else: pass return cleaned_data Views.py @login_required def salesmancreate(request): action="Salesman Creation" if request.method == 'POST': rec_form=salesmanform(request.FILES,request=request,user=request.user,data=request.POST) if rec_form.is_valid(): new_rec = rec_form.save(commit=False) new_rec.user = request.user new_rec.company=request.user.company.entity new_rec.save() return HttpResponseRedirect(reverse('salesmancreate'),{'section':'added'},messages.add_message(request, messages.SUCCESS,'Salesman added Succesfully')) else: rec_form=salesmanform(request=request,user=request.user) receivablescreated=salesman.objects.filter(company=request.user.company.entity).order_by('-id') return render(request,'account/salesman.html',{'rec_form':rec_form,'receivablescreated':receivablescreated,'action':action}) My Template <form action="." method="post"> <div class="form-group"> {{ rec_form.salesman_name|attr:"class:form-control"|attr:"placeholder:Salesman Name"}} </div> <div class="input-group margin-b-20"> {{ rec_form.salesman_commission_rate|attr:"class:form-control"|attr:"placeholder:Commission Perentage" }} <span class="input-group-addon"><i class="fa fa-envelope-o fa-percent"></i></span> </div> <div class="form-group"> {{ rec_form.salesman_PAN|attr:"class:form-control"|attr:"placeholder:PAN of Salesman" }} </div> <div class="form-group"> {{ rec_form.salesman_address|attr:"class:form-control"|attr:"style:height: 83px;"|attr:"placeholder:Address of Salesman" }} </div> <div class="form-group"> {{ rec_form.attachment|attr:"class:form-control"|attr:"style:height: 83px;"|attr:"placeholder:Address of Salesman" }} </div> <div class="form-group clearfix"> <div class="pull-right"> {% csrf_token %} <button type="submit" class="btn btn-success … -
Error while using MySql with Python 3.4.3 and Django 1.9.6
I have tried using pymysql mysql-client mysql-connector-pyhton and various other ways stated in this question but still I am not able to use MySql as my database. Whenever I try to do run it shows below error message. raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb' I have tried these two Database configuration in my setting.py file Setting 1: This works with python 2.7 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'user_db', 'USER': 'ecom', 'PASSWORD': 'ecom@123', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '', } } error message : `raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'` Setting 2: as suggested in this question's answer DATABASES = { 'default': { 'NAME': 'mydatabase', 'ENGINE': 'mysql.connector.django', 'USER': 'myuser', 'PASSWORD': 'secretpassword', 'OPTIONS': { 'autocommit': True, }, } } error message : Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: No module named 'mysql' Still I am not able to use mysql as backend can anyone please let me know what I am doing wrong or is it even possible with python … -
Django hide fields only in CREATE object admin page
As subject, i want to hide some fields ONLY when users enter the 'CREATE' admin page for specific model. I know that change list_display can hide fields in admin page, but it's a global setting which will take affect not only in 'CREATE' admin page, but also in 'UPDATE' admin page. -
Web hosting for Django and Cdeigniter applications
I have a website which is currently developed in Codeigniter framework. I want to develop another one using Django framework. Please help me to find a good and popular web hosting which can host both Django and Codeigniter applications and should also support MySql and Sqlite. I am new to web hosting. Thanks in advance -
Django - Postgres - 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)
So I get the error above when I try to use the Admin console and view one of the models in my database. The rows in my database were scraped from a website so if I'm correct, I accidentally scraped the u'\xa0' character and Django does not like this. Correct me if I'm wrong. Now to fix it I imagine I can just run a psql query to find any u'\xa0' characters and replace them with whatever I need (empty string in this case). I thought maybe I could use the replace function from postgres: UPDATE <table> SET <field> = replace(<field>, '\xa0', '') but it doesn't appear to be working. Any tips? Error: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128) -
Is there official support of composite foreign key?
This is a very basic question. Apologies in advance. Is there an official support of composite keys in Django models. I could find hacks or unofficial pluggable apps only. Most of the forums that say that it is in progress are years old. If there is not, which is the best and most stable alternate without changing the legacy database (oracle)? Is this any good? https://pypi.python.org/pypi/django-composite-foreignkey