Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Manager object has no attribute 'save'
In my serializers.py I have a OrderCreateSerializer: class OrderCreateSerializer(ModelSerializer): data_params = serializers.DictField() # 根据产品数据模型不同而异 class Meta: model = Order fields = ( "product_describe", # 产品描述 (购买xx产品 + 参数) "billing_type", # 计费类型 ("包年包月") "data_params", # 数据 ) def create(self, validated_data): request = self.context.get("request") if request and hasattr(request, "user"): user = request.user validated_data["order_num"] = generateOrderNum(userid=user.id) validated_data["order_status"] = "未支付" validated_data["order_status"] = "未支付" data_dic = validated_data.pop("data_params") # # data_dic["data"]["profile"] validated_data["buytime"] = data_dic["data"]["buytime"] validated_data["count"] = data_dic["data"]["count"] validated_data["paytype"] = "" validated_data["cost"] = "" validated_data["account"] = user.account return Order.objects.save(**validated_data) # this is the line 57 When I save the validated_data, it report the bellow error: Manager object has no attribute 'save' My Order model is like bellow, there is many fields in it : class Order(models.Model): """ 订单 """ order_num = models.CharField(max_length=128, unique=True) # 订单编号 order_status = models.CharField(max_length=12) # 订单状态 "未支付", "已支付,未完成", "已完成", "已经删除","其他" product_describe = models.TextField() # 产品描述 billing_type = models.CharField(max_length=16) # 计费类型 buytime = models.CharField(max_length=16) # 比如:1月 永久 count = models.IntegerField() # 购买数量 paytype = models.CharField(max_length=16) # 支付方式(支付包,微信,xxx) cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00) # 费用(需要花费多少钱) account = models.ForeignKey(to=Account) # 所属账户 ctime = models.DateTimeField(auto_now_add=True) # 创建时间 uptime = models.DateTimeField(auto_now=True) # 更新时间 def __str__(self): return self.product_describe def __unicode__(self): return self.product_describe I don't know why there is the … -
update user's username or password or email if changed
I have a form where admin can add employee and while adding employee detail admin can fill up username and password and email for that employee. Adding employee with username and password i could do but editing I could not do. user = User.objects.get(username=request.user.username) user.username = form.cleaned_data['username'] But how do i get other user instance and edit that user username or password if admin has changed the username and password of that user? Because this employee form is filled only by admin class EmployeeForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = models.Employee fields = ('name', 'designation', 'section', 'phone_number', 'mobile_number', 'email', 'gender', 'role', 'username', 'password', 'avatar',) def employee(request): form = EmployeeForm(request.POST or None) if request.method == "POST" and form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] office_instance = OfficeSetup.objects.get(owner=request.user) form = form.save(commit=False) form.office = office_instance user = User.objects.create_user( username=username, password=password, email=email) user.save() form.save() messages.success(request, 'Thank you') return redirect('employee-list') messages.warning(request, 'Error') context = { 'form': form } return render(request, 'dashboard/hrm/employee.html', context) def edit_employee(request, id): instance = get_object_or_404(Employee, id=id) form = EmployeeForm(request.POST or None, instance=instance) if request.method == "POST" and form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] office_instance = OfficeSetup.objects.get(owner=request.user) form = form.save(commit=False) form.office = office_instance # change … -
Create Google Cloud Function using API in Python
I'm working on a project with Python(3.6) & Django(1.10) in which I need to create a function at Google cloud using API request. Here's what I have tried: From views.py : try: auth = views.getauth() # Prepare Request Body req_body = { "CloudFunction": { "name": func_obj.fname, "entryPoint": func_obj.entryPoint, "timeout": '60s', "availableMemoryMb": func_obj.fmemory, "sourceArchiveUrl": func_obj.sc_github, }, "sourceUploadUrl": func_obj.bucket, } service = discovery.build('cloudfunctions', 'v1beta2', http=auth, cachce_dicovery=False) func_req = service.projects().locations().functions().create(location='projects/' + func_obj.project + '/locations/-', body=req_body) func_res = func_req.execute() print(func_res) return HttpResponse('Submitted',) except: return HttpResponse(status=500) It returns 500 status response only, is there something wrong with my request? Help me, please! Thanks in advance! -
What type files should be put into .gitignore file in Django project
From my other post, I know the __pycache__ should be put into the .gitignore when I use git. And in the other post I saw, there are also .pyc and .pyo files. whether them should all be put into the .gitignore file? Can we summarize in the Python/Django project, what files should be put into . gitignore file? -
Creating Single Page App in Django with Polymer
I'm currently working on a singe page app in django that makes use of Polymer Elements. My problem is when I'm changing template views. When I click on a page link to direct me to a new view I want to use the app-route, app-location and the iron-pages elements that Polymer has. This lets me simply change my current views without actually having to reload the whole page again and make requests. Apparently, in Django, whenever I click on a link it instead goes to the urls.py and tries to direct me to that link. Is it possible to create single page apps in django with polymer? -
Whats the `__pycache__` in Django project? [duplicate]
This question already has an answer here: What is __pycache__? 3 answers Whats the __pycache__ in Django project? When I use the git status, it shows the bellow data: The information is bellow: .gitignore .idea/ qiyun_admin_financialmanage_financialmanage/__init__.py qiyun_admin_financialmanage_financialmanage/__pycache__/ qiyun_admin_financialmanage_financialmanage/admin.py qiyun_admin_financialmanage_financialmanage/apps.py qiyun_admin_financialmanage_financialmanage/models.py qiyun_admin_financialmanage_financialmanage/tests.py qiyun_admin_financialmanage_financialmanage/views.py qiyun_admin_financialmanage_ordermanage/__init__.py qiyun_admin_financialmanage_ordermanage/__pycache__/ qiyun_admin_financialmanage_ordermanage/admin.py qiyun_admin_financialmanage_ordermanage/api/__pycache__/ qiyun_admin_financialmanage_ordermanage/apps.py qiyun_admin_financialmanage_ordermanage/models.py qiyun_admin_financialmanage_ordermanage/tests.py qiyun_admin_financialmanage_ordermanage/views.py qiyun_admin_productconfig_common/__pycache__/ qiyun_admin_productconfig_common/api/__pycache__/ I don't know the __pycache__ in my project. and whether it is necessary in my project? because sometimes use git it will get conflicts about the __pycache__. Whether should add the __pycache__ into the .gitignore? -
Django - Pass a list item's id/pk to the view with jQuery ajax
Here is my code, shortened for brevity. HTML Template {% for question in questions %} <div class="upvote"></div> {% endfor %} # lots of code later... <script> $(".upvote").click(function(){ $.ajax({ type: "POST", url: "{% url 'upvote_for_question' %}", data: { 'question': question }, } }) }) </script> My <div class="upvote"> element is an upvote button for a question (think Stack Overflow's upvote button). As the code shows, every question in question_list has an upvote button. My question is, when the user presses an upvote button, how do I pass the associated question's pk/id to the view? -
Using sqlalchemy models in django admin
I am using SQLAlchemy ORM for my models in Django. I would like to register them in Django's admin.site. Is there any way to achieve so. -
Setting default value based on database in DJango
Good evening, I am new to Django and am working on a sort of ticketing app. My app has three models, Ticket, Status, & Notes. When displaying the ticket details, I have a form to add a Note. What I want to do is to add to the form a drop down that is set to the current status value of the ticket. When creating the form, how do I pass in the current status value to the form and use it as the default value? Thanks. -
differences between ModelSerializer.update() and ModelViewSet.update()
I found both ModelSerializer and ModelViewSet have update() method, and I think both are almost same. Is that correct ? from rest_framework import serializers from rest_framework import viewsets class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = '__all__' def update(self, instance, validated_data): # update of model instances instance.save() return instance class FooModelAPI(viewsets.ModelViewSet): serializer_class = MySerializer queryset = my_queryset def update(self, request, *args, **kwargs): # updateds model instances and save return Response("OK") In the above snippet, Can I use either ModelSerializer or ModelViewSet without another for updating model instance ? -
Django After login succeed, redirect again to login page
My Django project has 5 apps: app1, app2 ...... each app has one template index.html and 1 view named index. project/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', include('main.urls')), url(r'^accounts/', include('django.contrib.auth.urls')), app1/urls.py from django.conf.urls import url, include from . import views from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^accounts/login/$', auth_views.login, name='login'), app1/views.py from django.shortcuts import render from django.template import loader from django.http import HttpResponse from django.contrib.auth.decorators import login_required, user_passes_test def is_member(user): return user.groups.filter(name='group1').exists() @login_required @user_passes_test(is_member) def index(request): getting our template template = loader.get_template('app1/index.html') rendering the template in HttpResponse return HttpResponse(template.render()) setting.py LOGIN_URL = '/accounts/login/' LOGIN_REDIRECT_URL = '/' The 5 apps requirer login based on group app one I have no problem to login but the reset of the apps after login succeed, I will be redirected to login page again. The reset of the apps has exactly the same code except the group name and template location. Also the logger result show me that there is no problem with credential. I tried to change the group nae for other app as app1 and still I am getting same result. Please advice me how to solve this problem. -
Adding multiple Date Fields in Django model
I am trying to add a field that would let me add multiple show dates in a Django Model. Sometimes the show date will contain 3 dates, sometimes 1 or sometimes 7. How am I able to add this in a model and have it so I can add multiple dates in the Django admin? -
S3 upload fails in production (Python)
I'm trying to upload an XML file to S3 in my Django app. I have tried tinys3, boto3, and boto original flavor. tinys3 worked like a charm in localhost, but if I'm even importing the file when I load it with Elastic Beanstalk I get an error much like what I get from boto3 when I do the same (except boto3 lets me get as far as launching the server and initiating the xml upload from the client): invalid syntax (_base.py, line 381) Boto original doesn't work at all. I definitely need the ability to upload XML's dynamically to S3. No idea why this won't work. -
AJAX for adding product from a page of multiple products not working in Django templates
I have a template in Django having multiple products for a user to add to cart. The code for the template is below. {% for object in fruits_and_vegetables %} <div class="col-sm-3"> <form class = "submit-form" id = "{{ object.id }}" method="GET" action="{% url 'my_virtual_supermarket_products:my_virtual_supermarket_cart' %}"> <img src="{{ object.image.url }}" width="120" height="120"> <h5 style="color:black">{{ object.name }}</h5> <h5 style="color:black "><i class="fa fa-eur" aria-hidden="true"> {{ object.price }}</i> </h5> <input type="hidden" name="item" value ={{ object.id }}> <input class="form-group" type="number" name="qty" value="1" style="width:25%;text-align: center"/> <input type="submit" class="btn btn-primary submit-btn" id = "{{ object.id }}" value = "Add to cart"> </form> </div> {% endfor %} I am trying to make an AJAX call, so upon adding products to cart the page doesn't need to be refreshed. My jquery code looks like this <script> {% block jquery %} $(".submit-btn").click(function (event) { event.preventDefault(); var formData = $(".submit-form").serialize(); console.log(formData) }); {% endblock %} </script> When I console log the formData, it basically shows me all the products with their item id and quantity. Below is how my console log looks like item=1&qty=1&item=3&qty=4&item=7&qty=1&item=9&qty=1&item=10&qty=1&item=26&qty=1&item=27&qty=1&item=31&qty=1&item=32&qty=1&item=2&qty=1&item=13&qty=1&item=18&qty=1&item=25&qty=1&item=4&qty=1&item=8&qty=1&item=11&qty=1&item=19&qty=1&item=20&qty=1&item=21&qty=1&item=23&qty=1&item=24&qty=1&item=6&qty=1&item=14&qty=1&item=15&qty=1&item=16&qty=1&item=22&qty=1&item=29&qty=1&item=5&qty=1&item=12&qty=1&item=17&qty=1&item=28&qty=1&item=30&qty=1 How can I get only the relevant product chosen through the serialize method ? -
Django Reverse Error: NoReverseMatch at
Hello StackOverFlow Members, before i get down to the point, let me retrace my thought/process here to help further slim down my issue. When i click a location object in "location_tree.html" it would redirect me to a new page, "accounts/location/(?P\d+)/" or "location", displaying the location name and its type. From the very same page, the name would be a hyperlink to another page with more details about the "location". But when i attempt to click the name, it redirects me to this error: NoReverseMatch at /accounts/location/2/ Reverse for 'continent' with keyword arguments '{u'pk': 2}' not found. 1 >pattern(s) tried: ['accounts/location/(?>P\d+)/location_continent/(?P\d+)/'] Some key things to note, i am using python2.7. Here is my working code, App/models.py: class Location(models.Model): title = models.CharField(max_length=255) location_type = models.CharField(max_length=255, choices=LOCATION_TYPES) parent = models.ForeignKey("Location", null=True, blank=True, related_name="parent_location") def __unicode__(self): return self.title class Continent(models.Model): title = models.CharField(max_length=255) location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True) is_an_island = models.BooleanField(default=False) def __unicode__(self): return self.location.title App/views.py: def view_page_location(request, location_id): location = Location.objects.get(id=location_id) if location.location_type == 'Continent': continent = Continent(location=location, is_an_island=False) return render(request, 'accounts/location.html', {'location':location, 'continent':continent}) def view_continent(request, pk): get_continent=get_object_or_404(Continent, pk) return render(request, 'accounts/location_continent.html', {'get_continent':get_continent}) Project/urls.py: from App.views import * url(r'^accounts/location/(?P<location_id>\d+)/', view_page_location, name='location'), url(r'^accounts/location/(?P<location_id>\d+)/location_continent/(?P<pk>\d+)/', view_continent, name='continent'), Templates, location_tree.html: {% for child in locations %} {% … -
How to make migrations only one app inside project using django
I have the follow project structure: MyProject |--myBaseApp | |--migrations | |--__init__.py | |--models.py | |... |--myClientApp | |--migrations | |--__init__.py | |--models.py | |... |--myProject | |--__init__.py | |--settings.py | |--urls.py | |... |--manage.py |... I can import to myClientApp/models.py the models.py from myBaseApp, but when I use the commands on terminal mode: python manage.py makemigrations python manage.py migrate myClienteApp The Django creates, on data base, all tables from models.py, both myClienApp/models.py and myBaseApp/models.py. I'd like to make migrate only the models.py from myClienApp/models.py. It's possible? Or do I need to create other project? -
Learning to work with HTTP requests in Python 3
I would first kindly like to express my gratitude to all people that are taking the time to read this post and/or respond to it! As a novice "developer" I only recently found out about this website and the professional highly skilled members that are present here impress me in every question I read. So thank you for that! For my question; I recently started with python (3.6 in PyCharm Professional) and am in the process of building an web application on the Django framework (although right now I am exploring the Flask framework). My problem is that I can't seem to get my head around HTTP Requests (aka, making my front-end of the web application connect to my serverside and server-hosted Python scripts). I read the Python and Django documentation and watched multiple video tutorials on youtube that were well reviewed but still can't wrap my head around it. What I am looking for is a link to a clear description with preferably a tutorial that focuses solely on HTTP requests so I can make myself familiar with it. Does anybody knows a good source or has had the same problem in the past and overcame it? I would … -
trouble iterating through dictionary keys and values in django template
I am trying to iterate through a context dictionary in a template in django. So far I've been unsuccessful and I'm not understanding what it is wrong. This is my view: def main_view(request): cat_dict = {'Other': 0, 'Meeting': 0, 'Project 1': 0, 'Project 2': 0, 'Project 3': 0, 'Project 4': 0, 'Collaboration 1': 0, 'Collaboration 2': 0, 'Collaboration 3': 0, 'Process 1': 0 } my_dict = gCalScriptMain.gCalScript(cat_dict) return render(request, 'gCalData/gCalData_main.html', context=my_dict) Instead, this is my template: {% extends "base.html" %} {% block content %} <div class="jumbotron index-jumbotron"> <h1 id="main-title">gCalData</h1> <ul style="color:white"> {% for k,v in my_dict.items %} <li>{{ k }}: {{ v }}</li> {% endfor %} </ul> </div> {% endblock %} But I get nothing (not even an error). The only thing I can do is retrieve a single value if I put this in the template: {% extends "base.html" %} {% block content %} <div class="jumbotron index-jumbotron"> <h1 id="main-title">gCalData</h1> <p style="color:white">{{ Other }}</p> </div> {% endblock %} -
Django pass variables to form_class
I am trying to figure out how to access fields from a Model that is used as a ForeignKey within the Model that the forms are querying. Each Room has a form where the user selects a Layout from a dynamic list of possible Layout objects. 1—The HTML forms/room/update/layouts.html <form class="layouts__form form-horizontal" action="" method="post" enctype="multipart/form-data"> <fieldset class="form__options"> {% csrf_token %} {% for field in form.layout %} <div class="layouts__layout"> {{ field.tag }} {{ field.choice_label }} <label for="value_{{ forloop.counter0 }}"> <div class="layouts__layout__thumbnail layouts__layout__thumbnail--{{ field.choice_label }}" style="background-image: url('### (I WOULD LIKE TO LOAD 'Layout.thumbnail' HERE) ###');"></div> </label> </div> {% endfor %} <div class="form__submit"> <button type="submit">Submit</button> </div> </fieldset> </form> 2—The form is being called by this in views.py: class LayoutView(UpdateView): model = Room form_class = LayoutForm template_name = 'forms/room/update/layouts.html' 3—Which is being created by this in forms.py: class RoomLayoutForm(forms.ModelForm): layout = forms.ModelChoiceField( widget=forms.RadioSelect(attrs={'type': 'radio', 'id': 'value',}), queryset=Layout.objects.all(), required=False, empty_label=None) class Meta: model = Room fields = ['layout'] 4—Which uses the Room model from: class Room(models.Model): title = models.CharField(max_length=200, blank=True) layout = models.ForeignKey(Layout, related_name='template_selected', blank=True, null=True) def __str__(self): return self.title 5—Which takes one of the Layout models as a ForeignKey defined here: class Layout(models.Model): title = models.CharField(max_length=200) ... padding_top = models.IntegerField(blank=False, default=0) ... thumbnail = … -
django "MyModel.user" must be a "User" instance
helloo I have in DJANGO app two functions where I want to work in my views.py the second function need the output from the first function to work. my views.py(before) : @login_required(login_url="login/") def app_details(request,slug): if request.method == "POST": b = request.user.id test = request.POST.get('index') test_path_export=test+'add/path' my_task_name(test,test_path_export) save_alg(request.user,test_path_export) return render(request, 'details.html'............................... my_function_name.py def my_function_name(input1,output1): .................................. .................................. return save_alg(user_id,output1) myalg.py from django.contrib.auth.models import User def save_alg(user_id,input1): instance = MyModel.objects.create(user=user_id, field1=input1) .................................. .................................. instance.save() and all work functions(my_task_name,save_alg) works fine ... now I want to create one function from this two functions to work in the some function because I want to add async tasks using celery in the future and if I have one function is very easy to use .delay. I change my_function_name.py to: def my_function_name(user_id,input1,output1): .................................. .................................. return save_alg(user_id,output1) and second try to def my_function_name(user_id,input1,output1): .................................. .................................. save_alg(user_id,output1) and in my views.py: @login_required(login_url="login/") def app_details(request,slug): if request.method == "POST": b = request.user.id test = request.POST.get('index') test_path_export=test+'add/path' my_task_name(request.user,test,test_path_export) return render(request, 'details.html'............................... error message in line instance = MyModel.objects.create(user=user_id, field1=input1) : self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "28": "MyModel.user" must be a "User" instance. I have add : from django.contrib.auth.models import User import user in all python files. any idea how to fix this … -
Numeric value[i] in list Python
In Django template I want get data from some list, example: list pages as data(doc in couch_db): { "_id": "someone", "_rev": "someone", "is_active": true, "priority_questions": 1, "answer_3": "test-data3", "answer_2": "test-data2", "answer_1": "test-data1", "answer_0": "test", "ask_3": "test-ask3", "ask_2": "test-ask2", "ask_1": "test-ask1", "ask_0": "test-ask", "title": "new-test", "extra_field_count": "4", "priority_3": 4, "priority_2": 3, "priority_1": 3, "priority_0": 1, "type": "help" } template: {% for page in pages %} <div class="box"> {{ page.title }} {% for i in page.extra_field_count %} {{ page.ask_<em>[i]</em> }} {{ page.answer_<em>[i]</em> }} {% end_for %} {% end_for %} Please help me, if you can -
Python Social Auth authenticating users to wrong accounts
For some reason users while using Facebook to oath, the user will auth as random users. When I looked into the UserSocialAuth table there was one user who had over 700 UserSocialAuth records, (there were a dozen users with over a hundred Facebook UserSocialAuth instances). At first I thought this might be a symptom of some Facebook users not having emails (emails are our username). I don't think this is the issue any more, because then they would all be authenticating to the same user. Users are reporting being connected to different users. The pipelines we're using is this SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'apps.accounts.pipeline.validate_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) The custom functions in the pipeline are these: def validate_user(strategy, user, response, details, is_new=False, *args, **kwargs): if not user.validated_at: user.validated_at = timezone.now() user.save() We are using the email field as our username, if that matters. We're using Django==1.10 social-auth-app-django==1.2.0 social-auth-core==1.4.0 -
how to get inverse object relation of object in django
I have the following model: class Employee(models.Model): user = models.OneToOneField(User, blank=True, null=True) company = models.ForeignKey('companies.Company', related_name='company', blank=True, null=True) brand = models.OneToOneField('companies.Brand', related_name='brand', blank=True, null=True) I try to get the employee from the Brand like this: attendees = Brand.objects.filter(pk=2) for a in attendees: print a.employee I get the error: 'Brand' object has no attribute 'employee' How can I get the employee from the brand? Thanks -
Django TemplateDoesNotExist : music/index.html
Ok i have this problem in my code when i run the server and go to the http://127.0.0.1:8000 it's run ok but the problem is ( i have a project called website and an app called music ok when i go to the http://127.0.0.1:8000/music it's tell me this Exception Type : TemplateDoesNotExist Exception Value: music/index.html my view.py from django.shortcuts import render from django.http import HttpResponse from .models import Album enter code here enter code here def index(request): all_albums = Album.objects.all() context = { 'all_albums': all_albums } return render(request, 'music/index.html',context) and this is what my server says enter image description here sorry about my English so bad -
Add blog posts without category
I want to be able to add some blog posts with categories and some without categories in django. with this models django admin won't let me add blog posts without a category. Thanks. from django.db import models from django.db.models import permalink class Blog(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) body = models.TextField() pub_date = models.DateField(db_index=True, auto_now_add=True) # Many-to-one relationship. category = models.ForeignKey('blog.Category') class Category(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100)