Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Mysql Database Rename Error even after deleting table
I am using mysql in my django project. In model.py i changed my primary key.For that i got an error. django.db.utils.OperationalError: (1025, "Error on rename of './newdb /#sql- 4ac_29' to './newdb/companies2_album' (errno: 150)") From model.py i deleted the table and the corresponding table also. And now i dont have any song table. from __future__ import unicode_literals from django.db import models class Stock(models.Model): ticker=models.CharField(max_length=10) open=models.FloatField() close=models.FloatField() volume=models.IntegerField() def __str__(self): return self.ticker class Stock2(models.Model): ticker = models.CharField(max_length=10) open = models.FloatField() close = models.FloatField() volume = models.IntegerField() def __str__(self): return self.ticker ''' (deleted) class Band(models.Model): id = models.AutoField(primary_key=True) ticker = models.CharField(max_length=10) genre=models.CharField(max_length=10) formationyear=models.IntegerField() country=models.CharField(max_length=20) lineup = models.CharField(max_length=80) image = models.ImageField(upload_to="bandimages") def __str__(self): return self.ticker class Album(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=20) 'bandid=models.ForeignKey(Band,on_delete=models.CASCADE)' releaseyear=models.IntegerField() songscount= models.IntegerField() image = models.ImageField() def __str__(self): return self.name class Song(models.Model): id = models.AutoField(primary_key=True) name=models.CharField(max_length=20) 'albumid=models.ForeignKey(Album,on_delete=models.CASCADE)' lyric=models.CharField(max_length=200) like=models.IntegerField() dislike=models.IntegerField() utubelink=models.CharField(max_length=100) def __str__(self): return self.name (deleted) ''' Still i get this error. I cant understand how it happens. I changed the database also.Reinstall mysqlserver.But nothing can fix this. -
(VUE.js2 + DJANGO) How to run npm run dev as https (secure server)?
I run two servers: Node server responsible for front end. Django server responsible for back end. On front end I am using Vue2 which redirects via proxy all request to backend. However, I would like my connection to be secure connection (https). I try to run npm run dev --https but it returns error: npm WARN invalid config Must be a full url with 'http://' -
Django | Displaying events grouped by month in custom format?
I have the following models: class Event(Page) # my fields start_date = models.DateField() end_date = models.DateField() class EventsIndex(Page): # my fields def get_events(self): events = Event.objects.all().sort_by("start_date") return events In my EventsIndex template I have 4 tabs which show the current month, the next month, the month after next and then a final tab called "Later" which should display the individual Events grouped by month: I'm trying to figure out the logic for which to get these events to display. The individual month tabs should only display the events, whereas the "Later" tab should display a heading of the month of the events and then the events themselves. Initially I thought about creating a function for each tab, so something like: def current_month_events(self): current_month, current_year = datetime.now().month, datetime.now().year events = Event.objects.filter(start_date__year=current_year, start_date__month=current_month).order_by("start_date") return events # Repeat for all required tabs However this seems to go against the DRY principle. Is there a more pythonic way to handle this logic? -
The requested URL /music/1/favorite/ method= was not found on this server django
I am getting this error- The requested URL /music/1/favorite/ method= was not found on this server django url that I am is using to star mark my favorite song is working fine. this is the url- https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Gold_Star.svg/2000px-Gold_Star.svg.png and this is the code- from .models import Album,Song from django.shortcuts import render,get_object_or_404 def index(request): all_albums=Album.objects.all() context= {'all_albums':all_albums } return render(request,'music/index.html',context) def detail(request,album_id): album=get_object_or_404(Album,pk=album_id) return render(request,'music/detail.html',{'album':album}) def favorite(request,album_id): album=get_object_or_404(Album,pk=album_id) try: selected_song= album.song_set.get(pk=request.POST['song']) except(KeyError,Song.DoesNotExist): return render(request,'music/index.html',{'album':album,'error_message':"you have not selected valid song"}) else: selected_song.is_favorite=True selected_song.save() return render(request, 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Gold_Star.svg/2000px-Gold_Star.svg.png', {'album': album}) -
All aspects of web application in Django
I am currently in process of making a Django enterprise web application but am relatively new to this field. This web app requires real time connection with multiple social media APIs and collects their data. I am using mongoDB database. I want to know all aspects and all the things I need to do to make a full functioning web application. For example, I found out that I need to make async calls to APIs and use cron jobs/ celery for API requests. What do I need to do for security concerns and speed? -
Cannot get object DateTimeField gte issue
I have an object class Promo( models.Model ): name = models.CharField(verbose_name="Name")) promo_name = models.CharField(verbose_name="Promo Name", max_length=255, null=True, default='') status = models.CharField( max_length=255, choices=( ('publish', 'Published'), ('draft', 'Drafted') ), default='publish',) start_date = models.DateTimeField(editable=True, auto_now=False, null=True, ) expire_date = models.DateTimeField(editable=True, auto_now=False, null=True, ) def __str__(self): return "%s" % (self.name, ) Timezone in settings.py is 'Asia/Jakarta', One of the object value is: When i filter only the status, it has no problem, but when i want to "get the Promo that have start_date greater than current_datetime, i keep failing, i don't know why, i tried to make the datetime into UTC format since Django seems to return the start_date as UTC timezone. But still fail. My code: import pytz from django.utils import timezone the_promo = Promo.objects.all().filter(status='publish').first() # test start_date = the_promo.start_date start_date_utc = start_date coupon_expire_date_in_asia_jakarta = timezone.localtime(start_date_utc) current_datetime = datetime.now(pytz.timezone('Asia/Jakarta') current_datetime_utc = datetime.now(pytz.timezone('UTC')) the_promo_to_be_used2 = Promo.objects.all().filter(start_date__gte=current_datetime_utc, status='publish').first() -
Didnt return a response - Duplicate django users
I have a django project. I have integrated djangos signup and login system into my application. I have a method for creating a user and logging them into the current session. I notices that when I try to create a record for a users with an existing username in the database, instead of giving a unique constraint fail or redirecting to another page, it just throws the following error: ValueError at /signup/ The view users.views.user_signup didn't return an HttpResponse object. It returned None instead. Request Method: POST Request URL: http://127.0.0.1:8000/signup/ Django Version: 1.11.5 Exception Type: ValueError Exception Value: The view users.views.user_signup didn't return an HttpResponse object. It returned None instead. Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response, line 198 Python Executable: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 Python Version: 3.6.2 Python Path: ['/Users/omarjandali/Desktop/split/split', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages'] Now I am using printing and logging to see where this issue is occuring and there is nothing printing. I feel like the form is not going to the method it was called from... I have no idea what is going on with this. Can anyone help... process = if form not submitted -> display from fill out for -> grab info from form -> grab useranem and see if … -
Run python script inside my views file in django
below is my views file class View(TemplateView): template_name = 'webapp/base.html' def post(self, request): form = Form(request.POST, request.FILES) #form = HomeForm() if request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() uploaded_file_url = fs.url(filename) args = {'form': form, 'uploaded_file_url': uploaded_file_url} return render(request, self.template_name, args) I want to include functions inside the post function and run them when the file has been uploaded. i have linked it already to html file, the html has a button which when clicked the file gets uploaded to BASE_DIR/media/. i'm new to django so any help is appreciated. -
Got AttributeError when attempting to get a value for field `data_params` on serializer `OrderCreateSerializer`.
This is my models: 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 This is my serializer: class OrderCreateSerializer(ModelSerializer): data_params = serializers.DictField() # 根据产品数据模型不同而异 class Meta: model = Order fields = ( "product_describe", # 产品描述 (购买xx产品 + 参数) "billing_type", # 计费类型 ("包年包月") # "buytime", # "购买时间" # "count", # 数量 # "paytype", # 支付方式 "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"] = "未支付" data_dic = validated_data.pop("data_params") # validated_data["buytime"] = data_dic["data"]["buytime"] validated_data["count"] = data_dic["data"]["count"] validated_data["paytype"] = "" # 支付类型 validated_data["cost"] = 0.00 # 所需钱 validated_data["account"] = user.account # 是哪个账户 return Order.objects.create(**validated_data) You see, in my serializer I have pop the data_params: data_dic = validated_data.pop("data_params") But when I access this API, I get: AttributeError at /api/financialmanage/order/add/ Got AttributeError when attempting … -
Django (DRF): How to do case-insensitive ordering
I have an api with ?ordering=name,type I want both the name and the type to be as case-insensitive class IngredientListAPIView(ListAPIView): queryset = Ingredient.objects.all() serializer_class = IngredientListSerializer filter_backends = [OrderingFilter] -
How to remove django crispy form feild validation error?
I want to hide the default crispy form field(username) validation error because I am using clean method for validation already. -
Attritube error when running the server
everything works quite well,so i presumed anyways but when i runserver and click the title of my blog,i get an AttributeError saying 'unicode object has no attribute tags' heres the the piece of code handling the tags def post_detail(request, year, month, day, post): post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4] post = get_object_or_404(Post, slug=post,status='published',publish__year=year,publish__month=month,publish__day=day) return render(request,'blog/post/detail.html',{'post': post,'comments': comments,'comment_form': comment_form,'similar_posts': similar_posts}) -
django REST swagger function based api does not have input PARAMETERS
I am trying to do Django REST function based API with swagger following these instructions. https://github.com/m-haziq/django-rest-swagger-docs However, I am unable to get any parameters shown in the function. This is the screenshot of swagger NOT displaying any parameters. https://imgur.com/a/fDITT Here is my API code, I want to have "name" parameters shown in swagger https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py @api_view(['POST']) def test_post(request): # ----- YAML below for Swagger ----- """ description: This API deletes/uninstalls a device. parameters: - name: name type: string required: true location: form """ name = request.POST.get('name') return Response("Data Saved!", status=status.HTTP_201_CREATED) What is the problem, you can view the whole source code in gitlab. Thanks. -
Reverse for '' with no arguments not found when passing and retrieving parameters between views
Basically i want users who are logged in to goto the page with their own data. So, when the user provides login credentials, redirect to some other page by passing 'pk' so the page will have only data related to that 'pk'. I have seen other posts in stackoverflow about Reverse for '' with no arguments not found but I don't know why this is not working for me so any insights and solutions are highly appreciated In urls.py, url(r'^class/(?P<pk>\d+)/$',views.ClassroomView,name='classroom_list'), In views.py, I have a user login view which should send parameters as def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request,user) # then send the user to Classroom view with 'pk' as parameter return redirect(reverse('basic_app:classroom_list'), {'pk': user.id}) I should get 'pk' from LoginView in the following ClassroomView: def ClassroomView(request,pk): classroom_list = Classroom.objects\ .filter(school__user=User.objects.get(pk=request.session.get('user_id','0'))) class_dict = {'class_records': classroom_list} return render(request, 'basic_app/classroom_list.html', context=class_dict) But, it says Reverse for 'classroom_list' with no arguments not found. 1 pattern(s) tried: ['basic_app/class/(?P<pk>\\d+)/$'] And, the url shows the following without 'pk' http://127.0.0.1:8000/basic_app/login/ -
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.