Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to properly save table rows values in django
I have two django models for orders and order items.I loop through each table row in jquery and pass the results to the View via ajax.The problem is that for each ajax call that gets fired it creates a database record for the orders.I want to create an order and respective order items from the table rows.What am i doing wrong.Thanks //The View class ProductListView(TemplateView): def post(self,request,*args,**kwargs): if request.is_ajax(): line_items = {} product_id = request.POST.get("product_id") price = request.POST.get("price") quantity = request.POST.get("quantity") subtotal = request.POST.get("subtotal") grandtotal = request.POST.get("grandtotal") products = CustomerPrice.objects.get(id=product_id) product_name = products.product line_items = { "product_id":product_name, "price":price, "quantity":quantity, "subtotal":subtotal, "grandtotal":grandtotal, } Order.objects.place('Credit Card','Pending', grandtotal,subtotal,125,line_items,request.user) return super(ProductListView,self).get(request) //The Model Manager class OrderManager(models.Manager): def place(self,payment_method,payment_status, grandtotal,sub_total,po_number,lineitems,username): charge_amount = float(lineitems['grandtotal']) order = self.create(customer=username, sub_total=lineitems['subtotal'], total = lineitems['grandtotal'], charge_amount=charge_amount, #payment_method=payment_method, payment_status=payment_status, order_number=po_number) #billing_address=billing_address, #updated_by=username, #created_by=username) OrderItem.objects.create(order=order, product=lineitems['product_id'], price=lineitems['price'], quantity=lineitems['quantity'], sub_total=lineitems['subtotal'], total =lineitems['subtotal'], #tax_rate=tax_rate, #tax_method=tax_method, updated_by=username, created_by=username) return order -
Python Django Server Gone crazy
I'm a newbie in pythonndjango. My local server just messed up by itself. Last night i closed it while it was working fine. Now when i'm trying to start it its gone all crazy on me. First giving all these errors No module named ... and then when i pip installed them now unbound method login() must be called with UserView instance as first argument (got WSGIRequest instance instead) This was all working till last night :O im so stuck. Please anyone can help? Thank you in advance. -
Celery task not counted as 'succeeded' for multiple minutes after returning
I have a celery task (running as part of a Django app) which typically takes about ~5 seconds. Mostly, it works great, and after a few seconds when I query it with AsyncResult I get SUCCESS as the state. Occasionally, however, it seems that there is a VERY long lag between the task returning (as tested by putting log statements right before the return statement of the function called by the task) and celery acknowledging it as successful (as noted by Celery logging something like: Task dynamicapp.tasks.myTask[090422da-184c-40ce-8d5d-3dcba6680219] succeeded in 129.666630374s. As you can see, this is ~2 minutes, even though the function itself returned after the usual ~5 seconds. On occasion, I've even seen this take ~15 minutes to acknowledge as 'succeeded.' I'm using Celery 4.0 and deploying the Django app on Heroku, for what its worth. -
How to access the value of field through a many to many relationship using dot notation?
A Pizza has toppings, a topping has a manufacturer, and a manufacturer has a name. Let's assume the same manufacturer creates all the toppings. I'm able to get the value of the manufacturer from a query like this: pizza.toppings.all()[0].manufacturer.name This is based upon models like this: class Pizza(models.Model): pizza = models.ManyToManyField(Topping) class Topping(models.Model): manufacturer = models.ForeignKey(Manufacturer) class Manufacturer(models.Model): name = models.CharField(max_length=255) However the all()[0] in the query seems ugly. Is there any way to rewrite the above query so it looks something like this: pizza.toppings.manufacturer.name I understand there are multiple toppings so the query can't be so simple, but all()[0] seems horrible. Thanks for your advice. -
how can we integrate any SSO provider using python social auth openid connect?
In my project, the customer can configure own SSO service via admin panel. can I create a genetic code? like this. Here I am using python social auth open_id module. python social auth created an example only for google OpenID connect i am following the same but I am not sure it will be work for all or not. Can I use the below code for multiple SSO provider? like for google, okta, gluu, oracle etc.. """ This file contains Django authentication backends. For more information visit https://docs.djangoproject.com/en/dev/topics/auth/customizing/. """ from django.conf import settings from social.backends.oauth import BaseOAuth2 from social.backends.open_id import OpenIdConnectAuth class DhOAuth2Mixin(object): ACCESS_TOKEN_METHOD = 'POST' REDIRECT_STATE = False # ID_KEY = 'username' USER_INFO_URL = None def get_user_permissions(self, access_token): # TODO: Do we need to worry about refreshing the token? data = self.get_json( self.USER_INFO_URL, headers={'Authorization': 'Bearer {0}'.format(access_token)} ) return data['permissions'] class DhOAuth2(DhOAuth2Mixin, BaseOAuth2): name = 'dh-oauth2' AUTHORIZATION_URL = settings.SOCIAL_AUTH_DH_OAUTH2_URL_ROOT ACCESS_TOKEN_URL = settings.SOCIAL_AUTH_DH_OAUTH2_URL_ROOT USER_INFO_URL = settings.SOCIAL_AUTH_DH_OAUTH2_URL_ROOT # optional REVOKE_TOKEN_URL = '' REVOKE_TOKEN_METHOD = 'GET' # optional DEPRECATED_DEFAULT_SCOPE = [ '', ] EXTRA_DATA = [ # ('username', 'id'), ('code', 'code'), ('refresh_token', 'refresh_token', True), ('expires_in', 'expires'), ('token_type', 'token_type', True) ] def get_user_details(self, response): """Return user details from account""" return { 'username': response.get('username'), 'email': … -
Django 1.4, no module named APPS
I have project in Django 1.4, I copied branch on my local machine and run commands: virtualenv venv source venv/bin/activate pip install -r requirements.txt python manage.py runserver I resolve some small errors with bad version on some dependencies and stay on error: Error: No module named apps I think it's problem with from django.apps import app, when I did it in manage.py for test gave error: Traceback (most recent call last): File "manage.py", line 13, in <module> from django.apps import app ImportError: No module named apps What's going on ? -
How to write query for joining two tables in Django?
Here, what I want is to join two tables, increment like value in Post table, add another row in UserLikes tables with current User, PostId, has_liked = True. Also checking if the current user has already liked the current Post or not? Below is my code. **--models.py--** class Posts(models.Model): title = models.CharField("Title", max_length=140) url = models.FileField("URL") likes = models.IntegerField("Likes", default=0) by = models.ForeignKey(User) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + ' by ' + str(self.by) class UserLikes(models.Model): post = models.ForeignKey(Posts) user = models.ForeignKey(User) has_liked = models.BooleanField("Liked", default=False) def __str__(self): return str(self.post) + ' by ' + str(self.user) **--views.py--** def like(request, pk): post = get_object_or_404(Posts, pk=pk) print(request.user) obj = UserLikes.objects.filter(post_id__in=post.id, user=request.user) try: if obj.has_liked is not True: obj.post_id = post.id obj.user = request.user obj.has_liked = True obj.save() post.likes = str(int(post.likes) + 1) post.save() except AttributeError: return HttpResponse(post.likes) else: return HttpResponse(post.likes, {'like': 'disabled'}) **--urls.py--** url(r'^(?P<pk>\d+)/like/$', views.like, name='likes'), So, what would be the query, in views.py file? -
How change django admin "view site" link to custom absolute url
I have REST API built on Django and JS application. Both are on different domains. How to change django admin "view site" link in such way so it will open JS application? I've tried to pass absolute link (https://docs.djangoproject.com/es/1.10/ref/contrib/admin/#django.contrib.admin.AdminSite.site_url), but looks like it does not work - only relative paths allowed -
how to connect api django 1.10 with c#
I'm trying to connect Django API with c # but when I connect I face a problem in c #. Django here I use as a server API and C # as a client. errors in C # is "CSRF is missing or incorrect". here if anyone could help me. resolve the issue. -
Get all fields in get_fields without filling out tuple with all field names
So, I'm customising the Django admin panel and creating different roles with different levels of access and permissions. For different roles, I want to show different fields for a particular model. For example, let's say I have the following model: class NPVenue(models.Model): venue_name = models.CharField(max_length=255) area = models.CharField(max_length=255) description = models.TextField() address = models.TextField() contact_info = models.CharField(max_length=100) email = models.EmailField() Further, I have extended the Django User class and defined a field called user_type which takes integer value to define the user role. Now, I want to show only the first two fields to user_type == 1 and the first four fields with user_type == 2. So, I've written the following: def get_fields(self, request, obj=None): if request.user.user_type == 1: return ('sport','venue') elif request.user.user_type == 2: return ('sport', 'venue', 'description', 'address') And this is working fine for the two users. The problem I'm facing is when I log in as superuser I get a "Nonetype is not iterable" error. So, the question I have is there is easier way for me to return all fields with respect to writing all the field names in the tuple one by one. Feels like a lot of hard work for a task that should … -
Medium to Large Project, Express.js? Django? Flask?
I have a new project I'm working on and I'm expecting the project to be a decent size in both functionality and user size. Most of the design is going to revolve around creating the backend as an API, and calling it from a JS front end. It should perform lots of CRUD operations, some streaming, and live messaging. I've used Django & DRF plenty, and I've also used flask, and express a little bit. I'm considering going with a smaller framework like flask/falcon/express (maybe Go) to develop the API, but I've never made anything of significant size in any of them. The prime benefits (in my eyes) being performance, isomorphic JS (for node obv) and overall simplicity/maintenance. So I'm wondering if anyone can comment on the difference in time and difficulty of implementation using a non-monolith framework?? I'm open to the microservices approach of building things. Please feel free to suggest tools/packages! TL;DR: I want to know how different/difficult it would be to implement a medium to large scale site from scratch in a smaller microframework vs a monolith. Implementation time being the biggest wonder -
Storing data from table
My objective is to create a diary of its sort where you can give marks to each person. I have difficulties to store data from editable table. Had an idea to wrap it all by tags, but not sure whether it's gonna work.Additionally, i'm perplexed how to store this data properly, what kind of models should create for each person? .table-editable { position: relative; } .table-editable .glyphicon { font-size: 20px; } .table-remove { color: #700; cursor: pointer; } .table-remove:hover { color: #f00; } .table-up, .table-down { color: #007; cursor: pointer; } .table-up:hover, .table-down:hover { color: #00f; } .table-add { color: #070; cursor: pointer; position: absolute; top: 8px; right: 0; } .table-add:hover { color: #0b0; } var $TABLE = $('#table'); var $BTN = $('#export-btn'); var $EXPORT = $('#export'); $('.table-add').click(function () { var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line'); $TABLE.find('table').append($clone); }); $('.table-remove').click(function () { $(this).parents('tr').detach(); }); // A few jQuery helpers for exporting only jQuery.fn.pop = [].pop; jQuery.fn.shift = [].shift; $BTN.click(function () { var $rows = $TABLE.find('tr:not(:hidden)'); var headers = []; var data = []; // Get the headers (add special header logic here) $($rows.shift()).find('th:not(:empty)').each(function () { headers.push($(this).text().toLowerCase()); }); // Turn all existing rows into a loopable array $rows.each(function () { var $td = … -
Django allauth Serialization error custom User model with TimeZoneField
My custom User model have a TimeZoneField: from timezone_field import TimeZoneField class User(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name = _('user') verbose_name_plural = _('users') email = models.EmailField(_('email address'), unique=True, blank=False, null=False) username = models.CharField(_('user name'), max_length=128, unique=True, blank=False, null=False) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.')) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) language = models.CharField(_('Language'), choices=settings.LANGUAGES, default=settings.ENGLISH, max_length=2) timezone = TimeZoneField(verbose_name=_('Timezone'), default='Europe/London') objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] I use django-allauth for registration by Google accounts. When existing user (registered by google email before, not Google Account) trying login by Google Account we have error: <DstTzInfo 'Europe/London' LMT-1 day, 23:59:00 STD> is not JSON serializable Traceback: File "/webapps/myproject/tmp/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/webapps/myproject/tmp/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/webapps/myproject/tmp/venv/lib/python3.4/site-packages/allauth/socialaccount/providers/oauth2/views.py" in view 55. return self.dispatch(request, *args, **kwargs) File "/webapps/myproject/tmp/venv/lib/python3.4/site-packages/allauth/socialaccount/providers/oauth2/views.py" in dispatch 125. return complete_social_login(request, login) File "/webapps/myproject/tmp/venv/lib/python3.4/site-packages/allauth/socialaccount/helpers.py" in complete_social_login 142. return _complete_social_login(request, sociallogin) File "/webapps/myproject/tmp/venv/lib/python3.4/site-packages/allauth/socialaccount/helpers.py" in _complete_social_login 158. ret = _process_signup(request, sociallogin) File "/webapps/myproject/tmp/venv/lib/python3.4/site-packages/allauth/socialaccount/helpers.py" in _process_signup 25. request.session['socialaccount_sociallogin'] = sociallogin.serialize() File "/webapps/myproject/tmp/venv/lib/python3.4/site-packages/allauth/socialaccount/models.py" … -
Django unique together relationship with field and manytomany on self
I'm try create post with language and content, and relate it on other versions of same page, but I'm get stuck class Page(models.Model): content = models.TextField() language = models.CharField(max_length=7, choices=settings.LANGUAGES) versions = models.ManyToManyField('self', blank=True) class Meta: unique_together = ('language', 'versions',) This will not work properly, because Django not allow make "unique" ManyToMany fields. Then I'm try make same relationship trough related model: class VersionsPage(models.Model): pass # ToDo: add unique together here, to foreign key field class Page(models.Model): ... versions = models.ManyToManyField('self', blank=True, through="VersionsPage") Anyone know how to make that without using symmetrical=False? -
flask: post data after insert, delete and update in database
I want to post data to a target url after insertion, updation and deletion in a model in flask like rest-hooks in django. for now i have only found signal events of flask-sqlalchemy like below: @event.listens_for(MyModel, 'after_insert') def do_stuff(mapper, connection, target): So how to do this in flask like we do using rest-hooks in Django or is there any other library which i can use. Thanks in advance. -
Create collections in mongodb from django
Have a few question about mongodb with django! 1) What will be the best package/adaptor to use mongodb with django? 2) Can I create mongo collections without pre defining it's schema? like this one from pymongo import MongoClient client = MongoClient() clientMongoClient('localhost', 27017) client.database_names() db = client.mydb post = {"author": "Mick", "text": "My very first blog post", "tags": ["mongodb", "python", "pymongo"], "date": datetime.datetime.utcnow()} posts = db.posts db.collection_names() >>>[u'testData', u'system.indexes', u'mydb', u'posts'] # a new collection is created If yes how? 3) Then how easily can I query it? -
Is there any difference between django and django rest framework?
I want to create backend for an android app that will perform the CRUD operations on database and return data in form of APIs. Which one is better? Tell me the difference and be more elaborative. -
Refreshing a webpage through onload() and through a refresh button
I have a django web page that basically displays a few graphs based on some analysis. This analysis can happen for a time duration for over 10 mins, during which the user can press a refresh button on the webpage to refresh the graphs. So in the backend the graphs(images) in the directory are overwritten with new graphs(the paths and image names remain the same). But this is reflected when I press on the browser refresh button but not when I click on the refresh button that I have on my webpage even though the code used in both places are replicas of each other. My onload function id called getGraphs(). Every time the page is reloaded by clicking the browser refresh button this function is called and the code is as follows, function getGraphs(ip) { $.ajax({ url: '/getGraphs/', type: 'GET', data: {"ip":ip}, contentType: 'application/json; charset=utf-8', dataType: "json", success: function (result) { $('#res').empty(); //div I am updating resDiv = document.getElementById("res"); var data = result.data["directory"]; for (var i = 0; i < data.length; i++) { resDiv.innerHTML+=('<h2>'+data[i]["name"]+'</h2>'); var images = data[i]["images"]; for (var j = 0; j < images.length; j++) { console.log("i:"+i+" dataLen:"+images.length) var path="results/"+result.uniqueID+"/"+data[i]["name"]+"/"+images[j]["name"]; //the path of the image resDiv.innerHTML+=("{% load … -
How to upload a file (code) to the django Server without the help of Models
Hosted a site in Windows Server machine. The code doesn’t use Models. We are trying to upload a file from a Windows Client to the django Server without the help of Models. If there are any codes that would help us achieve this kindly share with us. Alternatively, we tried the code specified in the below link and we are getting the following error. We are new to python, hence kindly help us in resolving the error stated below: Link: Need a minimal Django file upload example SyntaxError: Non-ASCII character '\xc2' in file C:\Python27\Scripts\Myproject\My App\models.py on line 5, but no encoding declared; see http://www.python.org/pep s/pep-0263.html for details -
Django Forms and 'tuple' object has no attribute 'rsplit' error
I've seriously waisted a couple days trying to figure this out and have absolutely run into a brick wall. I've researched and read all the SO posts on this issue, but could finally use some help please. I am trying to hook up a simple contact form and below is the latest rendition of my code that throws the same 'tuple' object has no attribute 'rsplit' error when I submit the form. My Django version is 1.9 and using Python3.5 def contact(request): title = 'Contact Us' title_align_center = True form = ContactForm(request.POST or None) if form.is_valid(): form_email = form.cleaned_data.get('email') form_message = form.cleaned_data.get('message') form_full_name = form.cleaned_data.get('full_name') subject = 'Site Contact Form' from_email = settings.DEFAULT_FROM_EMAIL recipient_list = [from_email, 'charles@studiorooster.com'] message = '%s: %s via %s' % ( form_full_name, form_message, form_email) # some_html_message = ''' <h1>hello</h1> ''' email = EmailMessage( subject, message, form_email, recipient_list, ['roosteromg@gmail.com'], reply_to=[from_email], headers={'Reply-To': from_email}, ) email.send() context = { 'form': form, 'title': title, 'title_align_center': title_align_center, } return render(request, 'pages/contact.html', context) -
Cuckoo Error: TemplateDoesNotExist at / dashboard/index.html
i installed CukoosandBox and Django, MongoDB.. And there is no issue when i start "cukoo.py" and "manage.py" But, when i start the webserver(127.0.0.1:8000) on internet , It doen't work as " TemplateDoesNotExist at / dashboard/index.html " i"m so serious... and There is no "dashboard/index.html"... although i perfectly installed cukoo.. How can i solve this issue ?! Would i re-install the cokoosandBox ?! OTL Plz,, i need your help... Thank you.. enter image description here enter image description hereenter image description here -
Convert Django DateTimeField to Java DateTime for given timezone
I use Django DateTimeField for my models that stores into MySQL datetime. The value stored in MySQL is 2016-11-24 03:11:47.284918, while Django Rest Framework returns it as "2016-11-24T03:11:47.284918Z" Should I convert the datetime at django to the respective timezone for each REST request or let the client handle it? In Java, how do I convert "2016-11-24T03:11:47.284918Z" into the given timezone? For example, in java simpleDateFormat, I can't find the letter 'T' Letter Date or Time Component Presentation Examples G Era designator Text AD y Year Year 1996; 96 M Month in year Month July; Jul; 07 w Week in year Number 27 W Week in month Number 2 D Day in year Number 189 d Day in month Number 10 F Day of week in month Number 2 E Day in week Text Tuesday; Tue a Am/pm marker Text PM H Hour in day (0-23) Number 0 k Hour in day (1-24) Number 24 K Hour in am/pm (0-11) Number 0 h Hour in am/pm (1-12) Number 12 m Minute in hour Number 30 s Second in minute Number 55 S Millisecond Number 978 z Time zone General time zone Pacific Standard Time; PST; GMT-08:00 Z Time zone RFC 822 … -
Chinese characters as a get parameter value on sending a get request
I tried sending a get request on Advanced REST Client through this URL: http://127.0.0.1:8000/report/game/?gamecategory=电子游艺 However an error returned: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 27: ordinal not in range(128) It's not it in the code as this is my only code: class ReportGame(APIView): ''' @brief Game Report on Lion's new page ''' permission_classes = (AllowAny, ) model = GameAccount serializer = ReportGameSerializer def get(self, request, *args, **kwargs): ''' ''' print 'dean' return Response(data='data', status=status.HTTP_200_OK) Is there a way to resolve this using my current URL Get parameters? I'm using: python == 2.7.10 django-rest-framework == 3.5 django == 1.10 -
Popular python framework for Web Development other than Django?
I'm new to python and searching for a framework which is easy to understand , as I find Django to be too complicated. -
how to put several objects in one template
How do I pass the object from ClassDetail to CreateNewStudent in order to use it in its template ? Thanks. class ClassDetail(DetailView): context_object_name = "Class" template_name = "temp/students.html" model = Class class CreateNewStudent(CreateView): model = Student form_class = forms.StudentForm template_name = "temp/newstudent.html"