Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django User, setting a user's is_active to false for a minute then reactivating again
I have a receiver for post_save signal that detects and restricts multiple active access tokens from the same user. In addition to this, I want to lock that detected user for a minute and reactivate the user once again by using the is_active field of the user. Is there a way to do this without creating and using a new model? -
What does the character "s" in related name of models depict?
Creating a model Foreign Key and using "%(app_label)s_%(class)s_related" to add a related_name. But what does the char "s" will do? class User(models.Model): user = models.ForeignKey( USER, related_name="%(app_label)s_%(class)s_related" ) class Meta: abstract = True class TestModel(User): title = models.CharField(max_length=80) -
Manage.py sqlall doesn't create tables for models in my app
I want to create a table for my models in my app, apparently the "python manage.py sqlall myapp" doesn't work I tried using the "python manage.py sqlmigrate myapp", i still get errors what is the proper command to use? i am using django 1.11.7 thanks -
Error running manage.py file in django 1.10 (struct.error: unpack requires a string argument of length 4)
I was playing around with my Django app today trying to transition from sqlite3 to postgresql. After running out of patience i changed my database settings back to my original sqlite3 db file. However, now when I run any command in the manage.py file I receive this error code: Unhandled exception in thread started by <function wrapper at 0x10960c2a8> Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Python/2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Library/Python/2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Library/Python/2.7/site-packages/django/contrib/auth/models.py", line 101, in <module> class Group(models.Model): File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 157, in __new__ new_class.add_to_class(obj_name, obj) File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "/Library/Python/2.7/site-packages/django/db/models/fields/related.py", line 1535, in contribute_to_class self.remote_field.through = create_many_to_many_intermediary_model(self, cls) File "/Library/Python/2.7/site-packages/django/db/models/fields/related.py", line 1049, in create_many_to_many_intermediary_model 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to}, File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 159, in __mod__ return six.text_type(self) % rhs File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 116, in __text_cast return func(*self.__args, **self.__kw) File "/Library/Python/2.7/site-packages/django/utils/translation/__init__.py", line 85, in ugettext return _trans.ugettext(message) File … -
NoReverseMatch Error on Server
I'm using Django 1.11, and python 2.7. I've been stuck for hours now on an error I can't find its origin. The error is: Internal Server Error: / NoReverseMatch at / Reverse for 'show_news' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['general/show_news/(?P<news_id>\\d+)/$'] My view: def list_news(request): news_items = NewsItem.objects.all().order_by('-submission_date') return render(request, 'general/news_list.html', {'news_items': news_items}) def show_newsitem(request, news_id): news_item = get_object_or_404(NewsItem, pk=news_id) return render(request, 'general/news_item.html', {'news_item': news_item}) My news_list.html template: {% block content %} {% if news_items %} {% for i in news_items %} <div onclick="location.href='{% url 'show_news' news_id=i.pk %}'"> <div class="panel panel-default"> <div class="panel-heading">{{ i.title }}</div> <div class="panel-body">{{ i.body|truncatewords:20 }} <img height="100px" align="left" src="{{i.picture.url}}" alt="here"> </div> <div class="panel-footer">{{ i.submission_date }}</div> </div> </div> {% endfor %} {% endif %} {% endblock %} Locally, everything works just fine, but on the server, nothing works! I'm really stuck. Please help. Thank you in advance. -
Editing as dataset like in admin site
I am trying a pretty simple thing. I have a database with customers. Now I am building a site where I choose one of the customers and edit the information about it. Exactly the same like in the admin pages where you choose one of your 'views' and you can change the values. Unfortunately I am making somewhere a mistake. Here my code: urls.py from django.conf.urls import url from django.contrib import admin from Customer import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^customerDetails/(?P<pk>\d+)/$', views.customer_details, name='customer_details'), url(r'^customerDetails/(?P<pk>\d+)/edit/$', views.edit_customer, name='edit_customer'), url(r'^admin/', admin.site.urls), ] views.py def home(request): customers = Customer.objects.all() return render(request, 'home.html', {'customers': customers}) def customer_details(request, pk): customerDetails = get_object_or_404(Customer, pk=pk) return render(request, 'customerDetails.html', {'customerDetails': customerDetails}) def edit_customer(request, pk): user = User.objects.first() customerDataSet = get_object_or_404(Customer, pk=pk) if request.method == 'POST': form = EditCustomerForm(request.POST, instance=customerDataSet) if form.is_valid(): form.save() return redirect('customer_details', pk=customerDataSet.pk) else: form = EditCustomerForm(instance=customerDataSet) return render(request, 'edit_customer.html', {'customerDataSet': customerDataSet, 'form': form}) modely.py class Customer(models.Model): someId = models.IntegerField() customerName = models.CharField(max_length=50) #with some more fields class customerDetails(models.Model): customerName = models.CharField(max_length=50) #with some more fields formy.py from django import forms from .models import Customer class EditCustomerForm(forms.ModelForm): class Meta: model = Customer fields = ['someId', 'customerName'] edit_customer.html {% extends 'base.html' %} {% block title %}Edit … -
Defining GUI filtering options in custom detail_route
The context is a geopositioning system to track devices. In this context we have hosts (devices) and we want to have an endpoint that returns a list of positions for a particular host. So far we have defined this as a @detail_route at the resource Host, so that GET /host/{pk}/track/ does this job. The code is roughly like this. class HostViewSet(HostViewSetMixin, viewsets.ModelViewSet): """Views for the Host resource.""" http_method_names = ['get', 'put', 'patch', 'delete'] model = Host # ... class HostViewSetMixin(object): """Mixin for the Host related ViewSets. HostViewSet, AssetViewSet, PersonViewSet """ filter_backends = (filters.SearchFilter, filters.OrderingFilter,) http_method_names = ['get', 'post', 'put', 'patch', 'delete'] @detail_route(methods=['get']) def track(self, request, pk=None): """Get host's track.""" # ... if request.GET.get('date_from', 0): # ... filter In def track we can check if there is a query_param, in which case we filter the positions to be returned (for instance, based on the time registered for each position). So we can do something like this: /host/{pk}/track/?date_from={date1}&date_to={date2} So far so good, now the problem is we would like the DRF documentation GUI to be aware of the existence of this query parameter for the track endpoint (and for this endpoint only). We want an input form in the GUI where we … -
Compare values from cx_oracle cursor with django queryset
In my project I collect data from an oracle database using cx_Oracle and then I need to compare the result from the cx_Oracle cursor with data from a SQLite database for which I have models. I have the following code which works for adding missing parameters: def GetParams(self): repo_params = Parameters.objects.filter(dbid=self.dbid).only('name','value') sql = ("select name, value from v$parameter") self.cur.execute(sql) res = self.cur.fetchall() repo_params = list(repo_params) parameters = [] for i in res: if i[1] not in repo_params: new_param = Parameters(name=i[1],value=i[2]) parameters.append(new_param) if len(parameters) > 0: Parameters.objects.bulk_create(parameters) But what I actually want to do is to merge existing content in my SQLite database with the one from the cursor. If an existing parameter exists with a different values then I need to update its value. If it's a new parameter, then it need to be created. What is the best way to do this? Should I do a MERGE using RAW sql? Thanks -
Turn off redundant output in manage.py in PyCharm
I see lots of redundant output from libraries like Pillow or requests when using them in management command in PyCharm 2017.2.4: I did not configure any additional logging for this libraries. Is it possible to turn it off? -
Optimizing front-end loading through this technique
I was reading about facebook's pageltes and Quora's Faster Paint. The best I understood is: start sending as soon as possible (chunked transfer) send basic layout of page first with inline css and page divisions in form of 'pagelets' keep filling these pagelets (along with css) as response is fetched and then download scripts and other resources. This approach seems efficient. What more could be added/ omitted in this? I understand this is broad but How can such a thing be implemented? do we need to send streaming response for this? and how does the front-end handle response? would be grateful if you can also share some articles to read further. -
How to use django autocomplete with field related to ContentType?
Good day, I am using django-autocomplete-light 3.2.10 for field that is related to ContentType model with ForeignKey relation inside django admin. I need to filter ContentType over its name but it is really a @property. So is there a way to do this? -
best way to learn django as early as possible
I am interested a lot in learning django but i couldn't found an easy way to learn it...Can any one please suggest the best website or any pdf for learning Django.. Thankyou in advance.. -
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.