Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.10 monkey-patch default User
I wanted to add additional fields to a many-to-many relationship and I created a intermediate model called Contact ( the goal is to implement a system that allows the user to follow other users and be followed too). class Contact(models.Model): user_from = models.ForeignKey(User, related_name='rel_from_set') user_to = models.ForeignKey(User, related_name='rel_to_set') created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return '{} follows {}'.format(self.user_from, self.user_to) I am using the User model provided by Django (from django.contrib.auth.models) . As this model is not one I created if I want to add fields to it, I should (or at least, I think I should ) add them dinamically (with monkey-patch) . So at the end of the models.py file I added the following code: User.add_to_class('following', models.ManyToManyField('self', through=Contact , related_name='followers', symmetrical=False)) But I runned the python manage.py makemigrations I got the following error : ValueError: path is on mount 'C:', start on mount 'D:' After a quick google search : "os.relpath does give you a relative path between two directories. The problem you are encountering is that, on Windows, a relative path doesn't even exist if the two directories are on different drives (which is exactly what the error message says). " But what … -
Django : proper way to make website title editable in admin
I'm building a website with Django. I have a main title for the website in my header template, currently hard-coded in it. How can I make it editable in the admin by the website administrator (or any user with the right credentials) ? Ideally I'd also like to be able to make more such site-wide (or app-wide) attributes editable in the admin (such as site - or app- description, for instance). I have in mind something like WordPress' bloginfo() . A practical example of this is washingtonpost.com who changed their moto in their header to "Democracy dies in darkness" a few weeks ago. Of course once the title (or any other attribute) has been edited in the admin I need to be able to get it from within my template. -
serve json file to user in django
How do you serve a JSON file to user? Currently I have a JSON object that I want the user to download. I tried res = HttpResponse(json_data, content_type='application/json') res['Content_disposition'] = 'attachment; filename=result.json' but it still serves the json in the browser instead of making user download it. -
Post parameters missing in django view
I have created a small web app in django, where I am sending a post request with parameters. I can clearly see those parameters present in url in django logs but in views those parameters are missing. url: [18/Mar/2017 12:04:18] "POST /login/?email=bla@gmail.com&Password=******** H TTP/1.1" 200 20 view.py: if request.method == 'POST': for x in request.POST: print(x) email = request.POST.get("email","") Password = request.POST.get("Password", "") print("email: {0}, password:{1}".format(email, Password)) Can someone please help? -
Django's "order_by" doesn't work in production
I realize that the question is vague, so I appreciate any suggestions. I have a simple Django app which works on my local Windows machine. I also have a "production" server on Ubuntu. Both run on the same version of Django==1.10.5. The code is identical (I deploy through git) and use the same database on a remote server (different from one where the Django app is running) I have a query with .order_by() clause which works on my local machine but not on the server. On the server the query returns the correct result but with no particular order. Every time I restart Apache the order of the results changes but it's never ordered. I tried to play with quotes and string formatting but it didn't help. My exact query: models=Stock.objects.filter(store='mystore', datestamp=datestamp, \ model__in=other_stores_model_numbers_union) \ .exclude(price=0.0).order_by("price") What it can possibly be? Thanks! -
How can i validate fields which are not in forms(means custom ) field on forms.py?
I want to validate fields which are not form fields on form.py..is it possible here is my model form: class Pay_bills(forms.ModelForm): class Meta: model = Recharge_request fields = ['mobile_no','amount'] def clean_amount(self): amount = self.cleaned_data.get('amount', None) print(self.cleaned_data.get('amount')) if ( amount < 1 ): raise forms.ValidationError("Please enter valid amount") return amount and my html page <div class="form-group" style="display:none;" id="consumer_no_div"> <label for="inputFirstName" id="field-label" >Consumer No:</label> <div> {% render_field form.mobile_no class="form-control" placeholder="Customer No"%} <div class="form-group" > <label> Bill Amount:</label> <div> {% render_field form.amount class="form-control" placeholder="Amount"%} </div> </div> <div class="form-group" > <label>Service Provider:</label> <div > <select required class="form-control" id="sel1" name="service_provider" name="sel"> <option value="">Select Service Provider</option> {%for provider in ser_provider%} <option value="{{provider.id}}">{{provider}}</option> {%endfor%} </select> </div> </div> here i want to validate service provider which is not my form field ..can i do it on forms.py??thanks in advance -
Nested (M2M) fields with ElasticSearch-dsl
Basically I am trying to return the add a value to index from get_grouped_tags to be added as a field in my index. I have tried: tag = fields.NestedField(attr="get_grouped_tags") returns an empty array tag = fields.NestedField(properties={ 'name': fields.StringField(), }) gives me a key error for manager (http://dpaste.com/35D46HP). I'm using an django-elasticsearch-dsl-py which is a wrapper for elasticsearch-dsl-py where I asked for help. Due to my front end app, my data has to stay in a this layout. This data is the result of a function get_grouped_tags The Data: "tag" : { "1" : [ { "taglevel" : 1, "name" : "Foo" } ], "2" : [ { "taglevel" : 2, "name" : "Bazz" } ] }, models.py class Tag(models.Model): name = models.CharField("Name", max_length=5000, blank=True) taglevel = models.IntegerField("Tag level", null=True, blank=True) def to_search(self): tags = self.id if tags: queryset = Item.objects.filter(tag=tags) for object in queryset: object.save() return queryset class Item(models.Model): title = models.CharField("Title", max_length=10000, blank=True) tag = models.ManyToManyField('Tag', blank=True) def get_grouped_tags(self): tag = self.tag.order_by('taglevel') grouped_tags = { tag_level: [ { 'name': tag_of_level.name, 'taglevel': tag_of_level.taglevel, } for tag_of_level in tags_of_level ] for tag_level, tags_of_level in groupby(tag, lambda tag: tag.taglevel) } return grouped_tags documents.py from django_elasticsearch_dsl import DocType, Index, fields from .models import … -
how can return cv2.imshow() image to browser in django
ac=obj.perform(newdoc.docfile.path) for (score,resultID) in ac: result = cv2.imread(path1 + "/" + resultID) # cv2.imshow("Result", result) return HttpResponse(cv2.imshow("Result", result)) from cv2.show("Result",result) a pop window is open an show the image but when I through HttpResponse passing image to browser it is give result None. How can I solve the issue. -
I want to start a new django project with pycharm, but I can't find the function on it
There are not have django choice, what should I do so start a django project? -
In Django how to show both registration and login forms at home page?
I'm trying to show both Django built-in registration and login forms at home page as I feel redundant to send the user to /accounts/register/ and /accounts/login/ when they can fill just 4 fields right at the home page to encourage them to signup. I understand I have to send both of these forms as objects from views.py to home page. But I'm not sure how to send them as these are built-in forms and only get rendered to particular templates. -
'UpdateView' object has no attribute 'object'
So I've been trying to add a cancel button to my UpdateView that I've been using. Here's my code for it: views.py: class CountryEditView(generic.edit.UpdateView): model = Country fields = ['name'] template_name_suffix = '_edit' def post(self, request, *args, **kwargs): if "cancel" in request.POST: url = self.object.get_absolute_url() return HttpResponseRedirect(url) else: return super(CountryEditView, self).post(request, *args, **kwargs) # etc.... models.py: class Country(AutoUpdateModel): #A subclass of models.Model def get_absolute_url(self): return reverse('appName:country_info', args=(self.id,)) #etc... country_edit.html: <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Update" /> <input type="submit" name="cancel" value="Cancel" /> </form> However I've been getting this error: Traceback (most recent call last): File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py", line 42, in inner response = get_response(request) File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\Users\username\Envs\projName\appName\views.py", line 38, in post url = self.object.get_success_url() AttributeError: 'CountryEditView' object has no attribute 'object' This doesn't make sense to me, since the documentation page says When using UpdateView you have access to self.object, which is the object being updated. Is there something I'm doing wrong? -
Dynamically populate a database from Postgres backup in Django TestCase setUp()
I'm looking for a Pythonic way to get a robust test database set up. What I'd like to do: take a previous database backup and load it into the database that Django's TestCase creates during setUp(). (and destroy the database on tearDown()) Is this Pythonically possible? I imagine I could manually call postgres with subprocess, but I'd prefer not to do that. I could also have a dedicated permanent test database and reconfigure my test settings. I'd prefer not to do this as well. I realize that restoring and deleting a database every time a test runs could quickly become a major time sink, but I'd like to see if I could do this in the meantime. My setup: Python 3.6, Django 1.10, psql 9.5.4 -
django extending user model depending on user's role
I need to have 2 user roles in my project: client and employer Question number one: There is an option called 'groups' in Django admin panel.Is it the same stuff like user roles? Question number 2: Let's say that I need to add custom field like company_name to users with role customer I have read some question like this Extending the User model with custom fields in Django And I got from that I should use a property called OneToOneField(User) But still I still didn't get it right. So how can I add this custon field company_name in model? -
Repeat header and footer with xhtml2pdf pisa
I am creating a dynamic pdf with xhtml2pdf and I need repeat the header and footer in each page, but only I got it in the first page. I need repeat the container id='headerContent' in all dynamic pages but I can not got it. I have tried with repeat="1"inside the tag but this don't works I got this My code is: <document pagesize='letter'> <head> <style type="text/css"> @page { size: letter portrait; margin: 1.7in 0.25in 0.25in 0.25in; padding: 0; @frame header { -pdf-frame-content: headerContent; width: 8in; top: 0.3in; margin-left: 0.2in; margin-right: 0.2in; height: 1.2in; } @frame footer { -pdf-frame-content: footerContent; width: 8in; bottom: 0in; margin-left: 1cm; margin-right: 1cm; height: 1cm; text-align: right; } } #headerContent p{ font-size: 14px; line-height: 19px; } .headerinvoice th{ background-color: #CCC; padding-top:4px; border-top: thick double #ccc; border-right: thick double #ccc; } .headerinvoice td{ padding-top:4px; padding-left: 5px; border-style: solid; border-top: thick double #ccc; border-right: thick double #ccc; } .headerinvoice .lasttr{ border-bottom: thick double #ccc; } .invoice{ margin-top: 20px; } .invoice th{ background-color: #CCC; padding-top:4px; border-top: thick double #ccc; border-right: thick double #ccc; } .items td{ border-left: thick double #ccc; border-right: thick double #ccc; } h1 { text-align: middle; font-size: 18px; } h2{ padding: 0; margin: 0; line-height: 20px; … -
Client side for formset django with jquery
Im trying to do a Formset with django, I dont have any problem with the process to save data, Im having problems with the client side. I mean, with the add button and remove button with Jquery. Specifically, because I need that detect when left one field does not show "remove" button. Clone an id in the DOM with Jquery would be easy, but my problem is honestly I dont know how works the names for each fields with formset. My Forms.py class FieldsForm(forms.ModelForm): class Meta: model = Fields fields = '__all__' FieldsFormSet = inlineformset_factory(Form, Fields,extra=1,form=FieldsForm,can_delete=True) My template: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script> <form method="post" action="#">{% csrf_token %} {{form}} </form> -
django-paypal unable to handle notification signal
I'm using django standard ipn and unable to handle notification signal. Payment goes very smoothly only notification part doesn't work. this is my signals.py def show_me_the_money(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: print("yey") order = Orders.objects.get(id=38) order.paid = True order.save() valid_ipn_received.connect(show_me_the_money) apps.py class PaymentConfig(AppConfig): name = 'payment' verbose_name = 'Payment' def ready(self): import payment.signals init.py default_app_config = 'payment.apps.PaymentConfig' urls.py url(r'^payment/', include('payment.urls', namespace='payment')), I've noticed that this is a common problem but wasnt able to find any solution for this. Thank you beforehand -
redirect to another form if email exists
I want to implement an invitation feature where user will fill in email address and their email will be saved to database. If they again fill in email address and request for invitation, they should be redirected to another form(ReferForm) so they can refer other. Here is my code class InviteForm(forms.Form): email = forms.EmailField(label=_("E-mail"), required=True) def save(self, email): print('email', email) print ('############') if (Invitation.objects.get(email=email)): return True invitation = Invitation.objects.create(email=email) return invitation class RequestInvitation(FormView): template_name = 'home.html' form_class = InviteForm def form_valid(self, form): email = form.cleaned_data.get('email') invite_instance = form.save(email) if invite_instance == True: return HttpResponseRedirect('/refer-form') invite_instance.invited_by_email_address = self.request.user invite_instance.custom_invite_code = get_custom_invite_code() invite_instance.save() messages.success(self.request, '{0} has been invited'.format(email)) return HttpResponseRedirect('/') def form_invalid(self, form): # messages.error(self.request, '{0}'.format(form.errors)) return self.render_to_response(self.get_context_data(form=form)) I get an error inside form save function where i have queried for email existence. However i get an error Invitation matching query does not exist. -
Django AttributeError: type object 'Post' has no attribute 'object'
I have been working on my first website. I have this Error that i don't understand.I have looked over the code and can't see where i went wrong. Look at error. All the code is here Thank you for your help. -
Email verification regix or django built in.
So I have spent the last hour looking at links for dango email validation. And the message system. What I am trying to do is take the def create(request area. Pass the email submitted from the request.POST['email'] have it check it to be a valid email address before its added to my database. I have email regex installed. I know there is a built in one for django I can get them coded without breaking my page but they dont run when i put in fake email it doesn't catch it. Would some one give me the best way to code this out. And this does come from a form that does work. from django.shortcuts import render, redirect from .models import User from django.contrib import messages import re EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') # Create your views here. def index(request): return render(request, "emailvalidation/index.html" ) def create(request): if request.method == 'POST': User.objects.create(email = request.POST['email'] ) context ={ "email": User.objects.all(), } return render(request, 'emailvalidation/success.html' ,context) -
Optimizing Django queryset calls, with large lists?
I will try to explain my problem as best I can. I'm having performance issues, and I wonder if there's a better way of setting this up. I have a database with roughly 150 years worth of year-by-year data. Each row has about 10 columns. I am running a "simulation" on every 30yr span (we'll call each 30yr chunk a "Cycle"). So, Cycle 1 would be years 1-31. Cycle 2 would be years 2-32. Cycle 3, years 3-33. Get the idea? all_data = DataPoint.objects.all().yearly() cycle_length = 30 previous_data_points = [] for data_point in all_data: if len(previous_data_points) < cycle_length: previous_data_points.append(data_point) continue simulation_cycles.append(Cycle(previous_data_points)) if len(previous_data_points) == cycle_length: previous_data_points.pop(0) previous_data_points.append(data_point) So, for each 30 year Cycle, I feed the Cycle function the 30 queryset items to initialize data. Problem is, when I use Django's connection.queries to list out what's going on, it looks like it's doing 3000+ queries and is taking 10-12 seconds, which is pretty long for what it's doing. In the connection.queries list, I see that it's doing 30 separate calls (1 for each data point) when I pass it into Cycle (each one using "WHERE EXTRACT(MONTH FROM" which I believe is my .yearly() filter being called. But then it also … -
queryset Django ? small questions
i am making a function of search something from my database. i am not sure about the way of returning results. it does not come out anything.. but on CMD, i can see user's Email who has searched Mother_language because of print(MyUser.objects.filter(Mother_language__contains=Mother_language)) in view this is my model class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length = 30, unique = True, null = False) Nationality =models.CharField(max_length = 30,choices= Country_choice,null = False) Mother_language = models.CharField(max_length = 30,choices= Language_list,null = False) Wish_language =models.CharField(max_length = 30,choices= Language_list,null = False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) picture = models.ImageField(upload_to='profile_images',blank=True) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','Nationality','Mother_language','Wish_language','picture'] this is my form class SearchForm(forms.ModelForm): class Meta: model = MyUser fields = ('Mother_language','Nationality') this is my view def index(request): print "entered" form = SearchForm(request.POST or None) if request.method == "POST" and form.is_valid(): Mother_language = form.cleaned_data['Mother_language'] Nationality = form.cleaned_data['Nationality'] MyUser.objects.filter(Mother_language__contains=Mother_language) MyUser.objects.filter(Nationality__contains=Nationality) print(MyUser.objects.filter(Mother_language__contains=Mother_language)) return render(request, "LanguageExchange/index.html", { "MyUser": MyUser}) print(form.as_table()) return render(request, "LanguageExchange/index.html", { "form": form,}) this is my index.html <form id="form" method="get" action="{% url 'index' %}"enctype="multipart/form-data"> {% csrf_token %} {{form.as_table}} <input type="submit" value="submit" /> <br> -
Configuring Django with Gunicorn on a Private Subnet
I am attempting to deploy a django project with Gunicorn on an ec2 instance from a private subnet in a custom VPC. I've tested the instance per Amazon's instructions to ensure that it is connecting to the internet: ping ietf.org The test returns positive: --- ietf.org ping statistics --- 6 packets transmitted, 6 received, 0% packet loss, time 5008ms rtt min/avg/max/mdev = 6.420/6.683/7.011/0.201 ms However when I run: gunicorn --bind 10.0.12.99:8000 mysite.wsgi:application I get a blank white screen when I click on the link. My terminal it shows: [2017-03-17 23:36:27 +0000] [5046] [INFO] Starting gunicorn 19.7.0 [2017-03-17 23:36:27 +0000] [5046] [INFO] Listening at: http://10.0.12.99:8000 (5046) [2017-03-17 23:36:27 +0000] [5046] [INFO] Using worker: sync [2017-03-17 23:36:27 +0000] [5049] [INFO] Booting worker with pid: 5049 I collected staticfiles into an S3 Bucket with 'django-storages', and I have also ran migrations. However at this point I am only concerned with getting Gunicorn to interact with my Django app at a basic level, just to be sure that it is working. I have not created a 'gunicorn.service' file yet, and I will configure my staticfiles after figuring this out. Any thoughts? -
Calculating averages in django models
I need to find out the average amount of quantity of a customers orders. How would I do this using django's models? from django.db import models class Customer(models.Model): name = models.CharField(max_length=200) phone = models.CharField(max_length=17) average_quantity_size = ? class Order(models.Model): customer = models.ForeignKey(Customer) quantity = models.PositiveSmallIntegerField() date = models.DateField() time = models.TimeField() -
Django Tutorial 02 | makemigrations failed | Is documentation wrong?
I've just started learning Django with the help of this Django Tutorial (#02). I'm currently creating the migrations for the polls application, I have added polls.apps.PollsConfig to mysite.settings.py as instructed. Here's the relevant excerpt: To include the app in our project, we need to add a reference to its configuration class in the INSTALLED_APPS setting. The PollsConfig class is in the polls/apps.py file, so its dotted path is 'polls.apps.PollsConfig'. Edit the mysite/settings.py file and add that dotted path to the INSTALLED_APPS setting. It’ll look like this: mysite/settings.py INSTALLED_APPS = [ 'polls.apps.PollsConfig', (...) ] However, when I run ./manage.py makemigrations polls I get an ImportError: No module named 'polls' with a decently long stacktrace (which I can post if required to). I managed to solve the issue by adding just the string "apps" to the settings file, instead of "polls.apps.PollsConfig", as suggested by this answer. Now the thing bothering me now is this statement from that answer: " ...you have installed Django 1.8, but you are following the Django 1.9 tutorial." I'm clearly following the documentation for Django 1.10 and the Django module installed for my Python virtualenv is 1.10: $ python -m django --version 1.10.6 So how did I get … -
regex email validation django
Working on a project for school I know how to do this in flask but learning django. I am trying to make sure that a valid email is entered before it post. If I do not do the if else statement the form goes though but wont validate it. I have the following and the only part not working is the one part with comments but I included the whole views.py incase you see something at top that could be wrong. views.py from django.shortcuts import render, redirect from .models import User import re EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') # Create your views here. def index(request): return render(request, "emailvalidation/index.html" ) def create(request): if request.method == 'POST': #here down if len(request.form['email']) < 1: add_message("Invalid Email Address!") #if i take out the if else the form does work elif not EMAIL_REGEX.match(request.form['email']): #the validation. add_message("Invalid Email Address!") else: User.objects.create(email = request.POST['email'] ) #to here context ={ "email": User.objects.all(), } return render(request, 'emailvalidation/success.html' ,context) the traceback error Environment: Request Method: POST Request URL: http://localhost:8000/user Django Version: 1.10.6 Python Version: 2.7.10 Installed Applications: ['apps.emailvalidation', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\exception.py" in inner 42. response = get_response(request) …