Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updating selection of objects, each with a different value in bulk (Django)
Imagine I have a python dictionary where keys are existing user ids, and values are scores to be added to those users' existing scores. For example: {1: 1580, 4: 540, 2: 678} (this could stretch to n k,v pairs) I need to update the scores of all these user objects (updated_score = original_score + new_score). One way to do it is iteratively, like so: from django.db.models import F scores = {1: 1580, 4: 540, 2: 678} for user_id,score_to_add in scores: UserProfile.objects.filter(user_id=user_id).update(score=F('score')+score_to_add) But that's multiple DB calls. Can I do it in a single call? An illustrative example would be great. As you would have guessed, this is for a Django project. -
How create two models in one Post in genericAPIView
I have a two model; first is book second, book-detail. How can i create these two serializer in book list view post function? -
Python, openpyxl: how to preserve formating in the cell?
I am importing some data from xslx file to Django model. Everything works perfectly except that if cell have some formatting of "superscript" or "subscript" it loses that formatting. Is there a way to preserve the style formatting of the value in the cell? -
Displaying Django error messages in templates? - Not working
I have two forms login.html and register.html, and i follow the same methods for displaying errors in templates, but does not work. login.html <form method="post" action="" class="ui large form"> {% csrf_token %} <div class="ui stacked segment"> {% if not form.non_field_errors %} <div class="required field"> <label>Emailaddress</label> {{ form.username }} </div> {% endif %} {% if form.non_field_errors %} <div class="required field error"> <label>Emailaddress</label> {{ form.username }} </div> {% endif %} {% if not form.non_field_errors %} <div class="required field"> <label>Password</label> {{ form.password }} </div> {% endif %} {% if form.non_field_errors %} <div class="required field error"> <label>Password</label> {{ form.password }} </div> {% endif %} <small><p>{{ form.non_field_errors }}</p></small> <input type="submit" name="" class="ui fluid large teal submit button" value="login"> </div> </form> Output screenshots: Non Error output Error output register.html <form method="post" action="" class="ui large form"> {% csrf_token %} <div class="ui stacked segment"> {% if not form.non_field_errors %} <div class="required field"> <label>Emailaddress</label> {{ form.email }} </div> {% endif %} {% if form.non_field_errors %} <div class="required field error"> <label>Emailaddress</label> {{ form.email }} <p>{{ form.email.errors }}</p> </div> {% endif %} {% if not form.non_field_errors %} <div class="required field"> <label>Password</label> {{ form.password1 }} </div> {% endif %} {% if form.non_field_errors %} <div class="required field error"> <label>Password</label> {{ form.password1 }} <p>{{ … -
Django to plot a graph using plotly with data from forms
I want to plot agraph using plotly.js library and the inputs to the graph is taken from the user through an html form. I have created a html form to read X and Y values for the plot. In the views.py, i accessed the form data using request.POST.get and then added to a list x[],y[]. from django.shortcuts import render x=[] y=[] def index(request): return render(request,'home.html') def inputplot(request): if(request.method=="POST"): xvalue=request.POST.get('xvalue') yvalue=request.POST.get('yvalue') x.append(xvalue) y.append(yvalue) print x print y return render(request,'inputplot.html') del x[:] del y[:] return render(request,'inputplot.html') def plot(request): `return render(request,'plot.html',{'x':x,'y':y}) I want the lists in plot.html but when i append data to the list it automatically add some characters. For example i input a number 12 for x value, but this number appears in the list as [u'12']. Why this happened? pls give me a solution or show me another method to read user data and plot the values.??? Help me -
Ajax does not work even though I used csrf_token
I have a web game project using django first, when I bring user character data using ajax-get method, it working fine (function(){ $("document").ready(function(){ $get_id = $('#character'); //현재 로그인 된 유저가 케릭터를 갖고 있는지 확인하는 코드 $user_has_character = $(".data").data("hasCharacter"); /***************************** * when user have character * ***************************/ if($user_has_character=="True"){ get_gamestart_api_url = '/api/gamestart/data/'; //게임 화면 태그 $scene = $('#scene'); $scene.css("background", "url(../static/images/game/loadingBackground.jpg) no-repeat"); /***************************** * * json will get user's character data * * **************************/ $.ajax({ method:'GET', url:get_gamestart_api_url, }).done(function(data){ character = data[0].character[0] $get_id.append("<li class='stat'> 케릭터 닉네임: "+character.nickname+"</li>", "<li class='stat'> 케릭터 레벨: "+character.level+"</li>", "<li class='stat'> 케릭터 직업: "+character.job+"</li>", "<li class='stat'> 케릭터 공격력: "+character.status.attack_point+"</li>", "<li class='stat'> 케릭터 수비력: "+character.status.defence_point+"</li>", "<li class='stat'> 케릭터 체력: "+character.status.health+"</li>", "<li class='stat'> 케릭터 마나: "+character.status.mana+"</li>", ); }); }else{ /********************* * When the user does not have a character ********************/ } }); })(); So, I think $.ajax doesn't have any problem, and when user doesn't have character, user must create a character }else{ /********************* * When the user does not have a character ********************/ //form tag will created $get_id.append("<form method='post' action='/'> <input name='nickname' type='text' style='border: 1px solid #ff0000;'><input type='submit' class='btn_character'> </form>"); $btn_character = $(".btn_character"); console.log($btn_character); //when user click create user button $btn_character.on("click", function(event){ //using jQuery function getCookie(name) { var cookieValue = null; if … -
Migrations are not supported in this engine. Calling syncdb instead.. (Django Cassandra)
Saya menggunakan Django 1.10, Python3.4 dan Cassandra 3.0 Saya mencoba mengikuti blog https://selfieblue.wordpress.com/2015/10/26/create-webapp-docker-python3-cassandra-on-ubuntu-15-04/ Samapai pada perintah "python3.4 manage.py migrate ", tidak bekerja, tabel tidak berhasil dibuat pada Keyspace python_db Dan informasi yang keluar saat menjalankan perintah " python3.4 manage.py migrate " seperti ini : Migrations are not supported in this engine. Calling syncdb instead.. Creating keyspace python_db.. Saya sangat senang jika anda membantu saya dalama masalah ini terimakasih -
(Django) Does MySQL foreign key cascade delete parent or children first
Currently, I am using Django with a MySQL backend database. Let us having the following database schema class Parent(models.Model): parent_id = models.BigAutoField(primary_key=True) last_child = models.ForeignKey('Child', on_delete=models.PROTECT) class Child(models.Model): child_id = models.BigAutoField(primary_key=True) parent = models.ForeignKey('Parent', on_delete=models.CASCADE) Each parent can have multiple children, but each child can only have one parent. The field last_child points to the last child birthed by the parent. What I am trying to express via this schema is The last child cannot die (be deleted) as long as its parent is still alive All children die when the parent dies However I have some concerns regarding database integrity, because of the conflicting PROTECT vs CASCADE. My question is, what will MySQL attempt to delete first should I delete Parent? Will it delete Parent first then try to delete the Child rows, or the other way around? -
MariaDb Json Support
Am using windows 10, I am running MariaDB 10.1.18 and it says JSON was supported from 10.0.1 but when am trying to do flask db migrations it's throwing error ? json not support. -
django setting foreign key (one to zero-or-one)
I want to setting foreign key as below image. diagram thanks. -
password_reset() got an unexpected keyword argument 'post_change_redirect'
I am facing some issues regarding reset password in django. I am using django's default authentication app in my app accounts. Here is the url definition: urlpatterns = [ url(r'^dashboard/$', dashboard, name='dashboard'), url(r'^login/$', views.login, {'template_name': 'accounts/login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.logout, {'next_page': '/accounts/login'}, name='logout'), url(r'^password/reset/$', views.password_reset, { 'template_name': 'accounts/forgot_password.html', 'password_reset_form': ForgotPasswordForm, }, name='reset_password'), url(r'^password/reset/done', views.password_reset_done, name='password_reset_done'), url(r'^password/reset/verify/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>,+)/$', views.password_reset_confirm, name='password_reset_confirm'), ] But when I hit /password/reset/ I was getting this error: Reverse for 'password_reset_done' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] So i added 'post_change_redirect': 'accounts:password_reset_done', argument in /password/reset/ url according to this answer. Now I am getting this error password_reset() got an unexpected keyword argument 'post_change_redirect' -
How to request result search in whoosh + django
I use whoosh with django. I want to print the results of whoosh search on the html file to display the results to the user. This is my code in views.I have not used haystack. Can you help me schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT) def search(request): storage = FileStorage(settings.WHOOSH_INDEX) ix = storage.open_index() output = "Result = " with ix.searcher() as searcher: query = QueryParser("content", ix.schema).parse("second one is even") results = searcher.search(query) return render_to_response('search.html',{'query': query, 'results': results}) And this is my 'search.html' {% if results %} <ul> {% for hit in results %} <li><a>{{ hit.content}}</a></li> {% endfor %} </ul> {% endif %} -
Django 1.10 manytomany post with form
I tried to select poi(point of interest) to make loi(line of interest), I met two problems on many to many fields: 1.Why I can't post the multiple selected options. 2.How to change the name in the option with the name I want (e.g. POI_title) original name/image Model.py class POI(models.Model): user = models.ForeignKey(User,on_delete = models.CASCADE) poi_id = models.AutoField(primary_key=True) POI_title = models.CharField(max_length=10) def __unicode__(self): return "{}({})".format(self.POI_date, self.user) class LOI(models.Model): user = models.ForeignKey(User,on_delete = models.CASCADE) poi = models.ManyToManyField(POI) LOI_title = models.CharField(max_length=10) loi_id = models.AutoField(primary_key=True) Form.py class LOIForm(forms.ModelForm): class Meta: model = models.LOI fields = ['poi','LOI_title'] def __init__(self, user, *args, **kwargs): super(LOIForm,self).__init__(*args, **kwargs) self.fields['poi'].wigit = forms.widgets.CheckboxSelectMultiple() self.fields['LOI_title'].label= 'title' Views.py if request.method == 'POST': request.POST.get("name", request.user.username) loi_form = forms.LOIForm(request.POST, request.FILES) if loi_form.is_valid(): loi_form = loi_form.save(commit=False) loi_form.user = request.user loi_form.save() return HttpResponseRedirect('/make_LOI') -
implement Authorization & Authentication in Java With Domain Driven Design
My question is simple, i just want to implement DDD in Java with Authorization & Authentication for a login with diferent Roles, can Help me with this topic? documentation, VideoTutorial or any opinion will help me, sorry if this question is duplicated or is not suitable, i will modify it -
Django queryset filter by post variable
I am trying to do a queryset filter using Django. I have Coupon objects with a code, which is a CharField. I want to find all Coupon objects with a matching code. My model: class Coupon(models.Model): code = models.CharField(max_length=50) ... other fields My view: # This method returns the queryset Coupon.objects.filter(code = "abc123") # This part of the code is not working the way I want to couponCode = str(request.POST.get("code")) Coupon.objects.filter(code = couponCode) I have ensured that the POST variable is "abc123" but I am still getting an empty queryset in the second query. -
In Django, how to pass user's selection to url?
In my Django project, there are two webpages. The first one will provide a user some major programs and the user will only choose one program. Then, the second webpage will provide the user some courses which are selected by which program the user chose in the webpage. But I am having trouble pass the user's selection in the first page to the url of the second page. Here is my view.py: class MajorForm(forms.Form): major_program = forms.ChoiceField(label='Major Programs', choices=MAJORS, required=True) def choose_major(request): if request.method == "GET": form = MajorForm(request.GET) context["form"] = form if form.is_valid(): major_program = form.cleaned_data["major_program"] context["major_program"] = major_program return render(request, "major.html", context) And here is my template.py: <html> <head> <title>Choose Major Program</title> </head> <body> <div id="header"> <h1>Choose Major Program</h1> </div> <div class="frame"> <form name="form" action="{% url 'choose_major_program' major_program %}" method="GET"> {% csrf_token %} <ul> <select name="major_choice"> {% for value, text in form.major_programs.field.choices %} <option value="{{ value }}">{{ text }}</option> {% endfor %} </select> </ul> <input type="submit" value="Submit" /> </form> </div> </body> </html> And below is my urls.py: urlpatterns = [ url(r'^$', choose_major_program, name="choose_major_program")] -
update the same group if group name clashes
How can i update the same group if the name of group user wants to create matches with already created group? If i want to update instead of showing error where should i work on? Is it on validate function or create function? Here is my serializer class DeviceGroupSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source='token', format='hex', read_only=True) devices = DeviceIdSerializer(many=True) class Meta: model = DeviceGroup fields = ['id','name', 'devices',] def validate(self, data): errors = {} try: name = data['name'] if not bool(name): #empty or null errors['name'] = 'Name cannot be empty' except KeyError: if not (self.instance and bool(self.instance.name)): errors['name'] = 'Name is required' if len(data.get('devices', [])) == 0: errors['devices'] = 'Device(s) should be specified.' if bool(errors): raise serializers.ValidationError(errors) return data def create(self, validated_data): # for create - there is always name; we have already checked that in validation # TODO Further check for group-name clash - if yes, update the same group owner = validated_data['owner'] name = validated_data['name'] group = DeviceGroup.objects.create(owner=owner, name=name) tokens = [d['token'] for d in validated_data['devices'] ] BaseDevice.objects.filter(token__in=tokens, owner=owner).update(group=group) return group -
django 1.8.10 on RHEL 6.6 unable to setup
I am trying to setup a fresh Django project on RHEL 6.6 server. Initial setup failing with below error. Need help to fix below error. Django version = 1.8.10 [root@mylinux bkupdash]# django-admin startproject bkupproject [root@mylinux bkupdash]# cd bkupproject/ [root@mylinux bkupproject]# python2.7 manage.py startapp bkupapp [root@mylinux bkupproject]# ls bkupapp bkupproject manage.py [root@mylinux bkupproject]# python2.7 manage.py makemigrations No changes detected [root@mylinux bkupproject]# python2.7 manage.py migrate bkupapp Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line ... File "/usr/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 316, in execute return Database.Cursor.execute(self, query) django.db.utils.OperationalError: near "ñòN": syntax error [root@mylinux bkupproject]# -
Authenticating with Django and Mongodb
am new in django and mongoengine and i need to using authenticating and session in my web project to control users i truly install mongo_auth but when running the server the message display on page is A server error occurred. Please contact the administrator. can any on help?enter image description here -
In Django, how to pass user's selection in the first webpage to the URL of the second webpage?
I have two webpages. The first one will provide a user some major programs and the user will only choose one program. Then, the second webpage will provide the user some courses to choose which are based on what program the user select in the webpage. So I would like to know how to save user's selection in database by passing user's selection to the URL of the second webpage. Thanks for your help! -
Is it possible to build a homepage with python on virtual server when the sudo command is disabled?
I've studied Python and Django, building a homepage. And I've been using a virtual Ubuntu server(apache2 2.4.18/ php-7.0/ MariaDB 10.0.28 with phpMyAdmin/ FTP) offered for developers. The server hadn't allowed users to use python, but I asked the server administrator to give me a permission and I got it. The problem was, however, that I was not allowed to use not only any sudo command line but also basic commands like apt-get and python. The only administrator can do so, therefore it seems that I cannot install any neccessary things-virtualenv, django, and so on- by myself. Just to check whether .py file works or not, I added <?php include_once"test.py" ?> on the header of index.php about the test.py where only print "python test"(meaning only python 2 is installed on this server) is written. It works. That is, I guess, all I can do is uploading .py file with Filezilla. In this case, can I make a homepage with Python on this server efficiently? I was thinking about using Bottle Framework, but also not sure. I am confused with wondering whether I should use PHP on this server and using Python on PythonAnywhere in the end. I am a beginner. Any … -
redirection to success_url is not working with django 1.10
I have a pretty simple contact us form but the success_url is not working. The page isn't getting redirected to home after successful form submission. I've followed the documentation available here https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-editing/ class ContactFormView(SuccessMessageMixin, FormView): form_class = ContactForm template_name = 'contact.html' success_message = 'Thank you!' success_url = reverse_lazy('home') def form_valid(self, form): form.send_email() return super(ContactFormView, self).form_valid(form) form_valid is being called but redirection to sucess_url doesn't happen and there are no errors. Thanks for your help. -
How to update mod_wsgi from 3.3 to 4.5 using Ubunutu 12.02?
If I already have Django installed and configured is it possible to fully remove mod_wsgi 3.3 and reinstall mod_wsgi 4.5 on an Ubuntu 12.02 system without having to update the OS since I am running on a VPS that I do not own and the server admin says they can't update the OS for an unstated reason. -
No module named 'django_simple.todo'
I am working through a (mycodesmells) django tutorial and towards the bottom under "ADDING TO THE PROJECT" it says to update the url.py file with the code that it gives. Once I update that file it crashes the server and gives me the error. "No module named 'django_simple.todo' I looked in SO posts and template view and redirect were mentioned in the following post. 1. Does this mean its deprecated? 2. How do i fix or adjust the code for Django 1.1 and Python 3 Templateview from django.conf.urls import include, url from django.contrib import admin from django_simple.todo import views as todo_views admin.autodiscover() urlpatterns = [ url(r'^$', todo_views.index), url(r'^admin/', include(admin.site.urls)), ] -
Accessing url of ImageField via values() method on django queryset
I have a data model in Django where I save photos uploaded by users. There's an attribute called image_file in the Photo model (of the type ImageField) where the image's url is stored. I can access it with item.image_file.url in the template for instance. However, I can't seem to be able to do the following in the view: Photo.objects.filter(owner=user).order_by('-id').values('id','image_file.url')[:10] I.e. For a particular user, I'm trying to get the 10 latest photo objects' image urls along with object ids. This gives me FieldError: Cannot resolve keyword 'image_file.url' into field. Shouldn't this have worked? p.s. it's a postgresql backend