Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending the user to spesific Url - django
The title may be confuse, so i will explain: Target: send the user to an app url if he type just the adrees. For emxample: If my site is: "www.goo.com", So i want to send him to "www.goo.com/hello". Why: my target chosen becase i want the user to be in an "login.html" page which in the "hello" app's "url.py". If the user will do: "www.goo.com/login.html" - I dont want to do that because then I will need to save the view which send him to "login.html" in the root app project - and that will cause a situation that the "url.py" of my root priject is full with all of my views of all my apps. -
django twilio for number phone confirmation returns exception in send function
I got an exception when i create a sms to send here is my functions def send_sms(to_number, body): account_sid = settings.TWILIO_ACCOUNT_SID auth_token = settings.TWILIO_AUTH_TOKEN twilio_number = '+15005550006' client = TwilioRestClient(account_sid, auth_token) try : client.messages.create(to=to_number, from_=twilio_number, body=body) except Exception as e: print e.message def generate_code(): return str(random.randrange(100000, 999999)) def send_confirmation_code(request,to_number): verification_code = generate_code() send_sms(to_number, verification_code) request.session['verification_code'] = verification_code return verification_code -
How to create an instance of an object in session using django?
I have an object model which has to be called on every answer given by the user on the client side. But whenever user clicks the answer, my view runs and the object is initialised again. So i thought of creating the object instance in session and reusing with the same instance again and again in my code. But it throws me this: request.session['qn_obj'] = question_class() objects not JSON serializable I need help on how to create an instance in session using django. -
Limit DecimalField after comma with 2 digits
I am doing one calculation and the result is something like 37,200025 However when I am passing this result to one field on output serializer, I wanna limit it with 2 digits after comma which is like 37,20 For that, what I am doing on output serializer is: price = DecimalField(null=True, blank=True, decimal_places=2, max_digits=10) However, it doesn't return in the end as 37,20 but again 37,200025. How can I do this convertion(rounding) with serializer. -
Django model for Form builder Application
I want to create a form builder for django from scratch i know that there are some django packages for this type of application but i want to have the option to customize and add extra fields inside model. Then i want to design forms via a web interface and save it to the database this model i have done class Form(models.Model): ''' Form name ''' name = models.CharField(verbose_name="Form name",max_length=30) user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="forms") def __str__(self): return self.name def get_absolute_url(self): return reverse_lazy('fbuild:form-update',kwargs={'pk':self.pk}) class ElementType(models.Model): ''' Element Type is for example select ''' name = models.CharField(verbose_name="Element Type name",max_length=30) user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="elementtypes") def __str__(self): return self.name def get_absolute_url(self): return reverse_lazy('fbuild:elementtype-update',kwargs={'pk':self.pk}) class FormElement(models.Model): ''' ''' caption = models.CharField(verbose_name="Form Element name",max_length=30) form = models.ForeignKey(Form, on_delete=models.CASCADE,related_name="formelements") elementtype = models.ForeignKey(ElementType, on_delete=models.CASCADE,related_name="elementtypeformelements") def __str__(self): return self.caption def get_absolute_url(self): return reverse_lazy('fbuild:formelement-update',kwargs={'pk':self.pk}) class ElementListValues(models.Model): ''' ElementListvalues for selectbox data ''' name = models.CharField(verbose_name="Name",max_length=30) value = models.CharField(verbose_name="Value",max_length=30) formelement = models.ForeignKey(FormElement, on_delete=models.CASCADE,related_name="formelementlistvalues") def __str__(self): return self.name def get_absolute_url(self): return reverse_lazy('fbuild:formelementlistvalue-update',kwargs={'pk':self.pk}) If you can share your options how to design the model better thanks a lot for your time -
whenever i always try to implement the stripe payment in django it gives an error
enter image description here Please help fast. i did install dj-stripe but when it was install its start giving an error see in image -
Is there a way to get the current memory and CPU usage of a webpage
Appologies for being so naive, but i'm quite new to building anything related to web. I'm trying to build a web app or page that could get the current memory and CPU usage of the Page itself. Bigger picture: I need to measure the performance of some flash based web content(source of which is not available to me) across different browsers and i'm planning to create a page that could load the web content inside a div and than get its memory and CPU usage over a period of time(say every 10mins) for a given period of time(could be an hour to a few days). All i could find so far is the javascript API : window.performance.memory But this is not generic and hence cant be used. Can anybody please point me into the right direction, to achieve this goal. I'm have basic experience with javascript, jquery, python/django and hence a solution in any of these will easier for me to implement. -
Python post to remote host
Hi I want to write robot to register in toefl test , I send request to remote web site as: from django.http import HttpResponse import requests from bs4 import BeautifulSoup from django.middleware import csrf def index(request): session = requests.Session() page = session.get('https://toefl-registration.ets.org/TOEFLWeb/extISERLogonPrompt.do') if request.method == 'POST': url = 'https://toefl-registration.ets.org/TOEFLWeb/logon.do' data = { 'password': request.POST.get('password', ''), 'username': request.POST.get('username', ''), 'org.apache.struts.taglib.html.TOKEN': request.POST.get('org.apache.struts.taglib.html.TOKEN', '') } page = session.post(url, data=data) return HttpResponse(request,page.text) My post request is not same as post request made by toefl original web site and instead of login shows error as : We are sorry, our servers are currently busy. Please wait a few minutes and retry your request. what is the problem? someone in other corporation did this without error -
Django test problems
I was running an unit test with django in Pycharm, but got a error message like this, its can't find the file I wrote test in : enter image description here and it worked good yesterday, I don't know how to solve it -
pass get parameters from templates in django
I am passing some parameters to my get request from templates in django. This does not work, the parameters aren't passed successfully. <ul> <form method="get" action="{% url 'crm:redirect_view' %}?job=update_namespace&types=user,hello "> <li><button type="submit">Add Namespace</button></li> </form> </ul> One solution is to create hidden input fields and pass the data, but I wanted to avoid that. -
Django Rest Framework : Fields are not getting create or update after making custom methods inside models
class UserInfo(models.Model): user_id = models.AutoField(primary_key=True) user_firstname = models.CharField(max_length=20, verbose_name = "First Name") user_lastname = models.CharField(max_length=20, verbose_name = "Last Name") user_email = models.EmailField(max_length=50, verbose_name = "Email Id") user_dob = models.DateField(auto_now = False, auto_now_add=False, verbose_name = "Date of Birth") user_mobileno = models.CharField(max_length=14, verbose_name = "Contact No") user_image = models.ImageField(upload_to = upload_location, null=True, blank=True, width_field = "width_field", height_field = "height_field", verbose_name = "Profile Picture") width_field = models.IntegerField(default=0) height_field = models.IntegerField(default=0) user_password = models.CharField(max_length=20, verbose_name = "Password") user_blood_group = models.CharField(max_length=5, verbose_name = "Blood Group") user_location_id = models.ForeignKey(Location, on_delete=models.CASCADE, verbose_name = "Current Location") user_profession = models.CharField(max_length=20, verbose_name = "Profession") user_fb_id = models.CharField(max_length=20, verbose_name = "Facebook Contact", blank=True) user_random_id = models.CharField(max_length=20, verbose_name = "Registration Id") user_created_date = models.DateField(auto_now = True, auto_now_add=False) user_updated_date = models.DateField(auto_now = True, auto_now_add=False) def get_name(self): return "%s %s" % (self.user_firstname, self.user_lastname) def __str__(self): return "%s %s" % (self.user_firstname, self.user_lastname) Not when i made following post request, it's saving user_firstname & lastname and even not updating. And get_name method returning " ". Folowing is my serializer class UserSerializer(serializers.ModelSerializer): name = serializers.CharField(source='get_name') class Meta: model = UserInfo fields = ['user_id','name'] Can anyone help to out this? -
When is it better to integrate AngularJS in Django template instead of building client side and server side apps separately?
I know if my purpose is the build an API that might be consumed by more than one client, the solution is to build client side and server side apps separately, but what is the best solution if I do not have this constraint? is it to integrate AngularJS in Django templates (or Jinja2 templates for Flask) or to develop the two applications separately? Thanks! -
How can i add submitted values in the db of various models into another model for calculations of the payroll in django
I'm trying to develop a payroll app in my finance project using Django and it has various models that should be subtracted or added on to the payslip calculations. the problem is that i cannot access values in models such as overtime_pay in OverTime model into Payroll2 model for calculations of the final pay. How can i access em or is there another way of doing it apart from calculating from the models eg views or forms? Also, how can i access gross_salary amount from a differnt model in a defferent app in the same project; model name is Employee. gross_pay is the determining value in the payroll2 calculations which i dont know how to access well im kinda new to django so please be explicit in yo answers heres the code Over time model, calculating overtime pay class OverTime(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) WEEKLY = 'Weekly' MONTHLY = 'Monthly' DAYS =( (WEEKLY,'Weekly'), (MONTHLY,'Monthly'), ) pay_frequency = models.CharField(max_length = 11,choices=DAYS, default=WEEKLY) pay_date = models.DateField(auto_now_add=True, auto_now=False) hours_worked = models.FloatField(default=1.15, max_length=10) hourly_rate = models.FloatField(default=0.00, max_length=10) overtime_pay = models.FloatField(default=0.00, help_text='in hours') # regular_pay = models.FloatField(default=0.00, max_length=10) notes = models.TextField() A = 'Approve' D = 'Decline' P = 'Pending' TYP =( (A,'Approve'), (D,'Decline'), (P,'Pending'), … -
IntegrityError : (1048, "Column 'user_dob' cannot be null")
I have modified my serializers fields by as follow, class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source='user_id') name = serializers.CharField(source='get_name') email = serializers.EmailField(source='user_email') dob = serializers.DateField(source='user_dob') contactNo = serializers.CharField(source='user_mobileno') image = serializers.CharField(source='user_image') bloodGroup = serializers.CharField(source='user_blood_group') location = serializers.CharField(source='user_location_id.location_name') profession = serializers.CharField(source='user_profession') fbId = serializers.CharField(source='user_fb_id') userId = serializers.CharField(source='user_random_id') class Meta: model = UserInfo # fields = ['user_id','get_name'] fields = ["id", "name", "email", "dob", "contactNo", "image", "bloodGroup", "location", "profession", "fbId", "userId"] Now when i make a create request using following code form views.py, def create(self, request, *args, **kwargs): # partial = kwargs.pop('partial', True) serializer = self.get_serializer(data=request.data, partial=True) print("kwargs------------>",serializer) serializer.is_valid(raise_exception=True) self.perform_create(serializer) # headers = self.get_success_headers(serializer.data) response = { "status" : status.HTTP_201_CREATED, "message" : "User Created.", "response" : serializer.data } return Response(response) It's giving me the following error IntegrityError: (1048, "Column 'user_dob' cannot be null") Even after setting partial=True its not working. PUT request is also not working, Its not updating the data def update(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=True) # serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) self.perform_update(serializer) response = { "status" : status.HTTP_200_OK, "message" : "User Detail Updated.", "response" : serializer.data } return Response(response) Can anyone help me wth this? -
Django and pytest, multiple databases, preserve deletion
In my project I am using multiple databases, 3 to be precise. One default and two reference databases (another host), which are powered and updated by our data team. I am using 4 tables from 2 external databases, which were inspected with ./manage.py inspectdb. They are set to managed=False Everything works fine, my application works as expected and planned. Now the fun begins, I need to write tests. I do not want to delete my databases. I need to read from them, I do not want to create fixtures. Every time when I try to use pytest or custom django tests, it is trying to delete my databases, recreate, run migrations and stuff. How can I preserve that ? Either in pytest or django tests ? I've tried to --re-usedb, and couple of another params. This is my database settings (parts which can be uploaded) DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'default_db', 'USER': 'default_usr', 'PASSWORD': 'default_pass', 'HOST': 'postgres.somehost.com', 'SUPPORTS_TRANSACTIONS': True, }, 'geolocations': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=some_schema' }, 'NAME': 'geo_name', 'USER': 'geo_user', 'PASSWORD': 'geo_password', 'HOST': 'some-host.domain.com', 'SUPPORTS_TRANSACTIONS': True, }, 'eoc': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=another_schema' }, 'NAME': 'eco_name', 'USER': 'eoc_user', 'PASSWORD': 'eoc_', … -
Deployment and configuration management using windows as a machine control
OVERVIEW Here's the thing, I'm a 3d artist/coder and I need to use mostly of the time windows specific software. The only logical choice for me is having a windows box as a development environment. That said, I'd like to have as a production servers centos or other rpm based distros. Right now I'm trying to find a workflow which plays well with windows as a machine control but it's proving to be quite tricky. After a lot of googling my conclusion so far is great configuration management tools like puppet, ansible, salt or similars don't play well having windows as a control machine. Till now I've been using a custom set of fabric scripts which manage the whole process of machine configuration & deployment. I think this approach is just wrong and I'm overusing fabric, I've opened another post asking about that already. NS: This video describes perfectly my idea of what good deployments are QUESTION People who's in a similar situation than mine (coding from windows & deploying to linux), how do you deploy your python software targeting linux servers? What would you recommend me? -
django models.py add models but the DB not generate the tables
django models.py add some models. Then execute : python manage.py makemigrations and then : python manage.py migrate (there's no mistake when execute these two commands) But MySQL not generate the tables. -
How do I get Django to log why an sql transaction failed?
I am trying to debug a Pootle (pootle is build on django) installation which fails with a django transaction error whenever I try to add a template to an existing language. Using the python debugger I can see that it fails when pootle tries to save a model as well as all the queries that have been made in that session. What I can't see is what specifically causes the save to fail. I figure pootle/django must have added some database database constraint, how do I figure out which one? MySql (the database being used) apparently can't log just failed transactions. -
Merge two fields in one in a Djago Rest Framework Serializer
I am using Django Rest Framework authentication system which comes with a default user table. In that table it splits first and last name in two different char fields. Is it possible to join these two fields in a serializer? Something like this: class UserSerializer(serializers.ModelSerializer): full_name = serializers.CharField(source='colaborador.user.first_name' + ' ' + 'colaborador.user.last_name') So that I would get the following response: { full_name: "firs_name last_name" } -
How to print the query of .get queryset in django
How can I know the query when doing a .get queryset in django I have this model: class Artist(EsIndexable, models.Model): name = models.CharField(max_length=50) birth_date = models.DateField() And I did this in the shell: x = Artist.objects.get(name="Eminem") print x.query Then I got the error: AttributeError: 'Artist' object has no attribute 'query' -
python/django unittest, how to handle outside calls?
I read multiple times that one should use mock to mimic outside calls and there should be no calls made to any outside serviec because your tests need to run regardless of outside services. This totally makes sense....BUT What about outside services changing? What good is a test, testing that my code works like it should if I will never know when it breaks because of the outside service being modified/updated/removed/deprecated/etc... How can I reconcile this? pseudo code below function post_tweet: data = {"tweet":"tweetcontent"} send request to twitter receive response return response If I mock this there is no way I will be notified that twitter changed their API and now I have to update my test... -
Would you recommend using new Turbolinks with Django?
I have been using the new Turbolinks which is shipped with Rails 5. Very happy. Now I have to use Django for a project but I would like to keep using Turbolinks. I know Turbolinks is agnostic, but I'm not a Django expert at all. Before losing huge amount of time I wonder: is it a smart decision to combine the new version of Turbolinks and Django? Is there any better tool to achieve the same result? -
AngularJs interval only shows {{name}}
I'm trying to get a list of all the 'cashflow' objects in my django application by calling a AngularJS get function every 5 seconds. I run the function with $interval(getCashflows, 5000); in my js file and try to display it in my html as [[getCashflows]] (see interpolateprovider) Now the only thing I get is "[[getCashflows]]" in my html.. does interpolateProvider not work or do I need to call it differently? app = angular.module("coco",[]); app.config(function($interpolateProvider) { $interpolateProvider.startSymbol('[['); $interpolateProvider.endSymbol(']]'); }); app.controller('cocoCtrl',['$scope','$http', function($scope,$http, $interval) { $scope.cashflows = {}; $scope.pvBond = {}; $scope.num = 0; $interval(getCashflows, 5000); $scope.save = function (cashflow) { //code } $scope.getCashflows = function () { alert("getcashsss"); $.ajax({ url : "/get_cashflows/", // view functie type : "GET", data: {data: data}, dataType: "json", success : function(json) { alert(json.toString()); } }); } }]); -
Regex in django models
I've got a problem with regex in django models, the file name must start with letter or numer and the rest of work can caontains letters, numbers and two special signs: - and _. My code looks like: file_validator = validators.RegexValidator( regex='^[a-zA-Z0-9]*[a-zA-Z0-9\_\-]*$', message=(u'Name must start from letter or number, it can contains big and small letters, numbers and special signs: - _'), code='invalid_file', ) But when I test it in my project, when I write file name: "mike", there is an error message. What I do wrong? -
duplicate key value violates unique constraint "user_profile_user_id_key" Django
I need help with fixing the below, the problem is that it saves twice and it finds a duplicate value when inserting into the UserProfile table. Been struggling for quite some time now. Error Message: django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_profile_user_id_key" DETAIL: Key (user_id)=(71) already exists. models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user') phone = models.CharField(max_length=20, blank=True, default='') def __unicode__(self): return self.user.username class Meta: db_table = "UserProfile" forms.py class ProfileForm(forms.ModelForm): phone = forms.CharField(required=True) class Meta: model = UserProfile fields = ('phone') class MyRegistrationForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2') views.py def register_user(request): if request.user.is_authenticated(): return HttpResponseRedirect('/user/') else: if request.method == 'POST': myregistrationform = MyRegistrationForm(request.POST, prefix='registration') userprofileform = ProfileForm(request.POST, prefix='profile') if myregistrationform.is_valid() and userprofileform.is_valid(): registration = myregistrationform.save() profile = userprofileform.save(commit=False) profile.user = registration profile.save() return HttpResponseRedirect('/accounts/registration_complete') else: myregistrationform = MyRegistrationForm() userprofileform = ProfileForm() return render(request, 'register.html', {'myregistrationform': myregistrationform, 'userprofileform': userprofileform})