Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set initial value in Django UsercreationForm
I am beginner in Django and developing a user registration page using the UserCreationForm from django.contrib.auth.forms. But, unable to set the initial values for password1 and password2 fields. My requirement is when opening the usercreation form the password and re-enter password fields should get filled with an default password. I have tried this way but unable to achieve this requirement. views/user.py if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() else: form = UserCreationForm(initial={'password1':'testing123','password2':'testing123'}) Any help would be appreciated. -
Copying user-uploaded media for local Django development
When I'm developing my apps locally, I obviously need to use local storage for all my media. In production, I am using S3 for these files. Is there any way to sync between these two? Or is the only way for my local site to see the latest images that users have uploaded on to the live site to regularly copy the media from S3 to my local storage? -
How to trigger clean method from model when updating?
When I save my form I perform validation of data that is defined in my model def clean(self): model = self.__class__ if self.unit and (self.is_active == True) and model.objects.filter(unit=self.unit, is_terminated = False , is_active = True).exclude(id=self.id).count() > 0: raise ValidationError('Unit has active lease already, Terminate existing one prior to creation of new one or create a not active lease '.format(self.unit)) How can I trigger same clean method during simple update without a need to duplicate clean logic in my update view?(In my view I just perform update without any form) Unit.objects.filter(pk=term.id).update(is_active=False) -
Django deployement with mysqldb
Hello for some time I was using sqlite db for local trsting and deployement but I found that it isn't the better solution for some project that's why I have some question about mysql db how you can associate it with django project and how you can deploy your project with this db -
Django signals not working
I have a custom function that runs when a credit is added to the CreditsHistory table, which is called by a signal: def update_credits(sender, instance=None, **kwargs): if instance is None: return sum = CreditsHistory.objects.filter(member=instance.member).aggregate(Sum('credits_amount')) instance.member.n_credits = sum['credits_amount__sum'] instance.member.save() post_save.connect(update_credits, sender=CreditsHistory) post_delete.connect(update_credits, sender=CreditsHistory) Credits are updated everyday for certain members, but the n_credits field in the Members model is not updated for all members who get a new CreditHistory instance. I guess there is some sort of time out happening, or the database can't cope with the aggregation of the large CreditsHistory table for multiple members.. How can I debug this? -
Django templates {% regroup %} : prevent regrouping if grouper value is None
Currently working on a e-commerce project (with django-oscar), I have an issue regarding products display on the basket template. I use the {% regroup %} tag because I have several types of products : standalone, parent or children. Each basket line corresponds to a product, and if several of them are children sharing the same parent product, I want them to be regrouped under their common parent. However, I want standalone products to stand on their own. My queryset is the following : in_stock_lines = request.basket \ .all_lines() \ .order_by('product__parent', 'date_created') \ .filter(attached_to=None, product__product_class__name='Produit standard', is_customized=False) In basket.html: {% regroup in_stock_lines by product.parent as parent_list %} {% for parent in parent_list %} {% if parent.grouper %} {% include "basket/partials/_basket_non_customized_product.html" %} {% else %} {% include "basket/partials/_basket_non_customized_standalone_product.html" %} {% endif %} {% endfor %} The thing is that I don't want the regroup to act in the {% else %} part, because they are standalone products and are not supposed to be regrouped. But as their product.parent, i.e. the grouper is None, they are. Is there way to prevent the {% regroup %} to act for a certain grouper value ? I could make two distinct queries in my views.py to … -
How to get objects by State in REST API
I am working on an SPA angular/django, I have designed action ressources to be retrieved by Id (this way I can better handle cache in front). However, front needs for some features to retrieve actions by state instead of id : Option 1 Create new root api/actions/:state Option 2 Return list of action ids by state in GET: api/projects/:id route. fetch state related ids using existing root api/actions/:id Whis option would be cleaner ? -
Django custom manager to filter nearby through related model
I have two models shop and address. class Shop(BaseModel): name = models.CharField(max_length=100, blank=True, null=True) address = models.ForeignKey(Address, blank=True, null=True, on_delete=models.SET_NULL) objects = LocationManager() Address Model class Address(BaseModel): latitude = models.DecimalField(max_digits=16, decimal_places=14, blank=True, null=True) longitude = models.DecimalField(max_digits=16, decimal_places=14, blank=True, null=True) status = models.NullBooleanField(null=True) I have created a custom Manager for Shop model class LocationManager(models.Manager): def nearby(self, latitude, longitude, proximity): """ Return all object which distance to specified coordinates is less than proximity given in kilometers """ # Great circle distance formula # acos will not work in sqlite gcd = """ 6371 * acos( cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) ) """ queryset = self.get_queryset().select_related('address') \ .exclude(latitude=None) \ .exclude(longitude=None) \ .annotate(distance=RawSQL(gcd, (latitude, longitude, latitude))) \ .filter(distance__lt=proximity) \ .order_by('distance') return queryset Now I want to find nearby shops using custom manager: Shop.objects.nearby(13.244334,72.329832,20) But i am getting error Cannot resolve keyword 'latitude' into field. Choices are: address, address_id, name How can i use address field to find nearby shop? -
FIle/Path selection dialogue in Django Project
for my bachelor thesis I´ll have to code a tool in Django, which will have to select a file / filepath to work with it. I´v been searching for that for a while now, but haven´t found anything: I´d like to have a GUI selection method for browsing to a location on the filesystem, select a file and store it with its corresponding path in an object containing the filecontents (will be XML) and the filepath of the file in a FilePathField. I´m new to Django development, so take it easy on my poor soul, please :) .......... -
Django Model: Meta: how to have default ordering case-insensitive
I am having a Django Model as shown below: I know that we can set the default ordering in the Meta class. class Ingredient(models.Model): name = models.CharField(max_length=200,unique=True,null=False) slug = models.SlugField(unique=True) class Meta: ordering = ["name"] As the ordering is set to name here. What i found is, it is ordering by case-sensitive. So how to make it case-insensitive -
slow on a queryset. Is this my way of doing things? Or the return of the base that is ready
I think I do not do things right on one of my views. My model: class FacebookBien(models.Model): uid = models.IntegerField(primary_key=True) ref_agence = models.ForeignKey(FacebookAgence, db_column='ref_agence') loyer = models.FloatField() prix = models.FloatField() ville = models.CharField(max_length=200) code_postal = models.CharField(max_length=200) ref_type_bien = models.IntegerField() surface_totale = models.FloatField() source = models.CharField(max_length=200) nombre_de_pieces = models.IntegerField() date_creation = models.DateTimeField() list_source = models.TextField() class Meta: managed = False db_table = 'recette_facebook\".\"vue_facebook_bien_recherche' My serializer: class FacebookBienSerializer(serializers.ModelSerializer): ref_agence = FacebookAgenceBienSerializer(read_only=True) class Meta: model = FacebookBien fields = '__all__' extra_fields = ['ref_agence'] class FacebookAgenceBienSerializer(serializers.ModelSerializer): class Meta: model = FacebookAgence fields = ['site_web'] My pagination: class SmallPagesPagination(PageNumberPagination): def get_paginated_response(self, data): return Response({ 'pagination': { 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'count': self.page.paginator.count, 'total_pages': self.page.paginator.num_pages, 'current': self.page.number, }, 'results': data, }) def get_page_size(self, request): return 6 When I use this view it's perfect I have all the objects instantly: class Test(generics.ListAPIView): queryset = FacebookBien.objects.all() pagination_class = SmallPagesPagination serializer_class = FacebookBienSerializer This view return 63 600 objects When i use this view it's the same it's instantly: class BienAgence(generics.ListAPIView): queryset = FacebookBien.objects pagination_class = SmallPagesPagination def get(self, request, *args, **kwargs): ras = request.GET res = ras.dict() if FacebookBien.objects.filter(ref_agence=int(kwargs['ref_agence'])).exists(): requete = self.queryset.filter(ref_agence=int(kwargs['ref_agence'])) if (res['type'] == 'bien'): requete = requete.filter(prix__gte=int(res['p_mini'])) if res['p_maxi'] != '5000000': requete = requete.filter(prix__lte=int(res['p_maxi'])) if (res['prix'] … -
How can I achieve one single form, pre-populated with data from two different Profile instances?
I have a model, Pair, and another model Profile. An instance of the model Pair will be made with a form that draws from two different Profile instances. So, how do I pre-populate a single form with bits of information from two Profiles and also create it? Two models: Profile & Pair: class Profile(models.Model): ... favorites = models.CharField(max_length=150) class Pair(models.Model): requester = models.ForeignKey(Profile) accepter = models.ForeignKey(Profile) requester_favorite = models.CharField(max_length=50) accepter_favorite = models.CharField(max_length=50) The form so far: class PairRequestForm(forms.Form): your_favorites = forms.CharField(max_length=50) partners_favorites = forms.CharField(max_length=50) Code Explanation: The way it works is, a user(requester) will request the initiation of a pair with the PairRequestForm to the potential accepter. The form should be pre-populated with the "favorite" of each individual user. I'm not sure how to wire up the views.py since I need to obtain two objects. class PairRequestView(FormView): form_class = PairRequestForm template_name = 'profile/pair_request.html' success_url = "/" def is_valid(self, form): return note: The pair must be pre-populated with current information from the Profile. However, the form will not update any old information(will not save() any Profiles)--it will simply create a new Pair instance. -
How to restructuring the data by the data's property in Django-Rest-Framework?
I have a Disk serializer, my Disk serializer is bellow : class DiskSerializer(ModelSerializer): diskessencetype_name = serializers.ReadOnlyField(source='diskEssenceType.name') diskostype_name = serializers.ReadOnlyField(source='diskOsType.name') class Meta: model = Disk fields = [ "id", "price", "diskessencetype_name", "diskostype_name", ] The views.py is bellow: class DiskListAPIView(ListAPIView): serializer_class = DiskSerializer permission_classes = [] queryset = Disk.objects.all() And that generate the data like bellow: [ { "id": 4, "price": "5.00", "diskessencetype_name": "ssd", "diskostype_name": "系统盘" }, { "id": 5, "price": "6.00", "diskessencetype_name": "sas", "diskostype_name": "系统盘" }, { "id": 6, "price": "5.00", "diskessencetype_name": "sas", "diskostype_name": "数据盘" }, { "id": 7, "price": "6.00", "diskessencetype_name": "sas", "diskostype_name": "系统盘" }, { "id": 8, "price": "6.00", "diskessencetype_name": "sas", "diskostype_name": "系统盘" }, ..... ] But I want to search out and constraints to bellow data: { "系统盘":[{"id":5, "diskessencetype_name":"sas", "price":5.00},.....] "数据盘":[{"id":7, "diskessencetype_name":"ssd", "price":7.00},.....] } You see, they are restructuring by the instance's property(diskostype_name), is there a build-in method to realizer it? How can I rebuild them? -
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..