Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create UpdateView with Django formsets?
I have a couple of models with ForeignKey relation. File and FileRows. One File entry can have multiple FileRows connected to it. I am trying to create and inline form so that I can update and add multiple FileRows to a File entry. I have successfully created the form to add a File with FileRows. Now I am trying to create the UpdateView to update it. But I can't seem to do it. It shows the following error: TypeError at /file/edit/3/ 'File' object does not support indexing The following line from the template is highlighted red: {% for filerow in filerows %} I think this has something to do with my lack of understanding. What am I missing in the following code? models.py class File(TimeStamped): name = models.CharField(max_length=100) def __str__(self): return self.name class FileRow(TimeStamped): file = models.ForeignKey(File) part_no = models.CharField(max_length=30) description = models.CharField(max_length=100, blank=True) quantity = models.PositiveIntegerField() def __str__(self): return "{file} => {part_no}".format(file=self.file.name, part_no=self.part_no) class Meta: unique_together = ('part_no', 'file') forms.py class FileForm(forms.ModelForm): class Meta: model = File fields = ['name'] class FileRowForm(forms.ModelForm): class Meta: model = FileRow fields = ['part_no', 'description', 'quantity'] FileRowFormSet = inlineformset_factory(File, FileRow, form=FileRowForm, extra=2) views.py class FileUpdateView(generic.UpdateView): model = File form_class = FileForm template_name = … -
Deploying a React app on Heroku
I've a React.js application which depends on an API (based on Django Rest Framework). The React and Django applications are decoupled i.e in my local development environment, I run two servers (each using a different port), one for Django and the other for the React. Is it possible to deploy this to a single heroku application or will I need two separate applications? -
Django CMS simple placeholders outside of cms
I have a fully developed Django app and decided to add DjangoCMS to give a content developers a quick way to prototype landing pages etc. It now lives under myurl.com/cms and works quite well. The guys can create new pages, choose a template and add plugins there. When i saw the placeholder template tag I immediately thought about placing it all over the project, outside the cms, everywhere I want the product team to be able to quickly add and change content. I don't want them to create a new page for this from the cms because maybe the site has complex functionality which is only used once in this context (i.e. the search page). So basically I expect to have static placeholders that I can place in the html part of the page using the cms plugins template tags. I already found Placeholders outside the CMS in the DjangoCMS docs. But for this to work I have to grab the related placeholder object for every view that renders a page, which would increase the amount of work to "quickly add a placeholder for this text" considerably. Is there an easy way to do this? I kind of expect to … -
How to display the database value based on categories using Django
I have Column fields are Task Type,Date,Schedule .I need to display the values in templates like Task type and their date, schedule.I have number of date and Schedule for one Task Type. Like this way i need to filter and check condition : I Know the Design to display like this format.But,I need to display data's by Categories wise. Meeting: 1.Date:2017/28/4 -Schedule:With Client 2.Date:2017/29/4 -Schedule:With Team Demo: 1.Date:2017/28/4 -Schedule:demo to Client -
I want to save some values from JS file to database and again retrieve from views
I have a JS file from which I want to save data in database . And after that in a new JS I want to retrieve data again.My JS file is : var geom, strGeom, input, buffer, radius = this.get_radius(), features = mapport.panels.info.current.selection.features.mem; for (var i in features){ geom = features[i].geometry; strGeom = new OpenLayers.Format.WKT(geom); input = reader.read(strGeom.toString()); buffer = input.buffer(radius); buffers[i] = parser.write(buffer); id = models.AutoField(primary_key=True) map = models.ForeignKey(Map, blank=True, null=True) parcel = models.TextField('Parcel') overlay = models.TextField('overlay', default=0) I will make new field in data base buffer_line = models.TextField('buffer_line') And my view is def get_share_permissions(self): privilege = {'map_acl': self.acl.PUBLIC, 'site_acl': self.acl.PUBLIC, 'pro': 'Off'} share = self.request.REQUEST['share'] validate_until = datetime.utcnow()-timedelta(days=30) share = Share.objects.filter(share_id=share, created_at__gte=validate_until).order_by('-id').get() pro_validate = datetime.utcnow() - timedelta(hours=share.expiry_time) if share: pro_share = share.proshare_set.all() if share.snapshot or pro_share.count() == 0: privilege['map_acl'] = share.map_acl privilege['site_acl'] = share.site_acl privilege['pro'] = 'On' # Activate Pro Share if pro_share.count() == 0: share.proshare_set.create(ip=self.get_client_ip(), activated_at=datetime.utcnow()) else: activated = share.proshare_set.filter(activated_at__gte=pro_validate).all() if activated: privilege['map_acl'] = share.map_acl privilege['site_acl'] = share.site_acl privilege['pro'] = 'On' return privilege Now problem is every link on web saying I have to use form to send data back. So I cant do it without using templates ? -
I fail to organize an initialization of my project (python manage.py shell < initialize_project.py)
Django 1.11 Python 3.6.1 In a perfectly flat place (on a billiard table), I have found a pool and drowned in it. Please,have a look at initialize_project.py below and how I run it. And what traceback looks like. If I run it without Django, no exception is risen (below is seen how). Could you give me a kick here? Command and path where it is run: (photoarchive) michael@ThinkPad:~/workspace/photoarchive_project/photoarchive$ python manage.py shell < deployment/initialize_project.py --settings=config.settings.local Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 101, in handle exec(sys.stdin.read()) File "<string>", line 23, in <module> File "<string>", line 17, in initialize NameError: name 'create_users' is not defined This runs perfectly: (photoarchive) michael@ThinkPad:~/workspace/photoarchive_project/photoarchive/deployment$ python initialize_project.py (photoarchive) michael@ThinkPad:~/workspace/photoarchive_project/photoarchive/deployment$ Tree (photoarchive) michael@ThinkPad:~/workspace/photoarchive_project$ tree . └── photoarchive ├── config │ ├── __init__.py │ ├── settings │ │ ├── base.py │ │ ├── __init__.py │ │ ├── local.py │ │ ├── production.py │ │ ├── secrets.json │ ├── urls.py │ └── wsgi.py ├── deployment │ ├── initialize_project.py │ ├── … -
GUI for Django migrations
Is there a web decision to manage django migrations? I couldn't find any. It's a pain even to ssh and run manage.py migrate every time I want to migrate. It would be really nice if at least a part of the migration mechanism would be integrated to django-admin and there would be a web-page with all the pending migrations, an ability to run and rollback them and see the corresponding logs if something goes wrong. -
Django Rest Framework Auth
I'm working on a web application project that uses Django rest framework for its backend and angular 2 for the front end, I want to know if it's recommended to use Django User model for the authentification of my login form (I mean save all user in Django admin), or should I make another User model specifically for the app ? P.S: The application will be using the JWT token for authentification. -
Python Mobile App
I want to develop services or method to send the data over web and to mobile app as well. For now I am using Django Framework (Python code on server side) to get data on web page. I have developed web pages as well. Now I want to send same server data over Mobile App. My mobile app will be developed in Android and iOS. -
Adding a parameter to the fields of a django form which is accessible from the templates
i' ve a Django form which is passed to the templates through the view. In the form' s init i' m trying to add a parameter to each field, which is accessible from code, but not from the template. #forms.py class GenForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(GenForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].dest = 'test_value' help_text = self.fields[field].help_text #template {% for field in form %} {{ field.help_text }} || {{ field.dest }} {% endfor %} #views.py ret_dic['form'] = GenForm(request = request) return render(request, 'template_file', ret_dic) . My goal would be to reach the dest value for the fields from the template, but it' s not displayed at all. What is strange / interesting, is that i can reach the dest value from code: #ipython gen = GenForm() gen.fields['name'].dest #results: test_value . My questions are: how could i reach the dest variable from the template? why is the dest value reachable from code, but not from template? The help_text i can reach from the code and also from the template. Should i somehow register it maybe? Python: 3.4 Django: 1.9 . -
What happens if JSONField has reached maximum storage limit?
This might be a simple question for an experienced (Django) developer. My project's database is PostgreSQL. I intend to use a single protected model instance as a centralised storage for certain data. That instance will have a JSONField which will, in turn, store a dynamic collection of key-value pairs (both are strings). By "dynamic" I mean that new key-value pairs will be added to the collection from time to time, and hence the collection will constantly grow in size. As far as I have read (e.g. Size limit of JSON data type in PostgreSQL), the size limit of JSONField is approximately 1GB. That is quite a lot, but still not infinite. My question is: what exactly will happen if I manage to exhaust the storage capacity of JSONField? And are there any recommendations on how to forecast this kind of situation before it happens (e.g. monitor the instance's storage size)? -
django-autocomplete-light with django-gm2m : how can i do for applying filter for qs?
For applying the filter on all the querysets : qs = qs.filter(EMP-FIRST-NAME__icontain=self.q) My models have a different fields: ** EMP-FIRST-NAME for models Employees. ** FIRST-NAME for models Freecontracts. ** AG_NAME for models Freeagencies. ** FRE_FIRST_NAME for models Freelancers How can i do for applying filter for all models (qs)?? Thanks! Views.py : class RessourceAutocompleteView(Select2QuerySetSequenceView): def get_queryset(self): employees = Employees.objects.all() freecontracts = Frecontract.objects.filter(IS_ACTIVE=True) freeagencies = Freagencies.objects.filter(IS_ACTIVE=True) freelancers = Freelancers.objects.filter(IS_ACTIVE=True) if self.q: employees = Employees.objects.filter(EMP_FIRST_NAME__icontains=self.q) freecontracts = Frecontract.objects.filter(FIRST_NAME__icontains=self.q) freeagencies = Freagencies.objects.filter(AG_NAME__icontains=self.q) freelancers = Freelancers.objects.filter(FRE_FIRST_NAME__icontains=self.q) qs = QuerySetSequence(employees, freecontracts, freeagencies, freelancers) if self.q: # This would apply the filter on all the querysets # this tuple how can i do for apllying filter in all models qs??!!! qs = qs.filter(EMP_FIRST_NAME__icontains=self.q) -
Append does not work in For Loop
first_sale_all_menu = [] for one_product_category in Product_Category.objects.all().filter(slug__in=('3-pack-items-c', '3-pack-items-b', '3-pack-items', '3-pack-items-d')): link_to_mamapedia_cat = link_to_home_page + one_product_category.get_absolute_url() mamapedia_category_name = one_product_category.name if (one_product_category.image_for_top_menu != None): header_image = link_to_home_page + one_product_category.main_picture.url # TODO use thumbnail else: header_image = '' first_sale_all_menu.append({ 'menu_children_url' : link_to_mamapedia_cat, 'menu_children_title' : mamapedia_category_name, 'menu_product_image_src' : header_image }) Somehow that append() method does not work, it is still empty list for first_sale_all_menu. Just to make sure, even this does not work: first_sale_all_menu = [] for one_product_category in Product_Category.objects.all().filter(slug__in=('3-pack-items-c', '3-pack-items-b', '3-pack-items', '3-pack-items-d')): link_to_mamapedia_cat = link_to_home_page + one_product_category.get_absolute_url() mamapedia_category_name = one_product_category.name if (one_product_category.image_for_top_menu != None): header_image = link_to_home_page + one_product_category.main_picture.url # TODO use thumbnail else: header_image = '' first_sale_all_menu.append({ 'menu_children_url': 'link_to_mamapedia_cat', 'menu_children_title': 'mamapedia_category_name', 'menu_product_image_src': 'header_image' }) But this works: first_sale_all_menu = [] first_sale_all_menu.append({ 'menu_children_url': 'link_to_mamapedia_cat', 'menu_children_title': 'mamapedia_category_name', 'menu_product_image_src': 'header_image' }) I don't know why, but append() does not work inside my for loop. And yes, link_to_mamapedia_cat, mamapedia_category_name, header_image all have String values. -
parent calling abstract method in python
I'm new to python. I want to define some abstract methods in my parent class and use them. I wrote a code like this class BaseListAPI(APIView): __metaclass__ = abc.ABCMeta def get(self, request): search_object, start, count = tools.handlers.read_get_request_data(request.GET) order_by = request.GET.get('order_by') return get_successful_response(self.get_query_set.list( without_user_serializer=self.get_serializer, search_object=search_object, start=start, count=count, order_by=order_by )) @abc.abstractmethod def get_query_set(self): """Method that should do something.""" @abc.abstractmethod def get_serializer(self): """this method gets the serializer""" class TourListListAPI(BaseListAPI): def get_query_set(self): return models.Tour.objects def get_serializer(self): return without_user.TourSerializer When i call self.get_query_set() for example i expect the child function call but it never get called. What i'm missing here? -
Authentication for APIs(JWT and OAuth)
APIs are built using Django Rest Framework, Front End is Angular2 and a 3rd party android application. I have a set of APIs which I want to secure. APIs are currently serving angular2 using JWT authentication. Angular2 app is on the same domain as that of our APIs i.e., both are being served by the same server with different proxies. Now I want to authorize android app to use my APIs using OAuth2. I am using django-oauth-toolkit for my OAuth2 setup, but it doesnt support use of JWT as its bearer token currently. After implementing OAuth2, APIs are not being served if the request is from the same domain too. What is the way around this? If the request is from same domain, the apis should be served, if the request is cross domain, OAuth authorization should take place. -
Signals VS Celery task
So i have this scenario and quite not sure whether celery is the right tool for the job. I have to track the fifth order placed by a user to give them a coupon. Currently i have implemented a signal on the @receiver(pre_save, sender=Order) def pre_save_stuff(): #this has overhead on db since am excluding customers not in #loyalty progamme.They are many do_coupon_stuff() method. However i have now to exclude a particular group of customers with a query that has overhead slowing the request cycle for this order. Does it make sense to user celery in this scenario? -
Django modelformset_factory with crispy forms for images
I would like to create a list of all existing images belonging to a model in an UpdateView. This is the model included in the modelformset_factory from imagekit.models import ProcessedImageField class GalleryImage(models.Model): image = ProcessedImageField(upload_to="gallery", # Resize to fit ration 4:3 (Most common for phone camera's) processors=[ResizeToFit(800, 600), ], format="JPEG", options={"quality": 60}, blank=True, null=True, verbose_name="Afbeelding") gallery = models.ForeignKey("gallery.Gallery", related_name="images", on_delete=models.CASCADE) I created a form, with a related modelformset_factory from crispy_forms.helper import FormHelper from django.forms.models import modelformset_factory class GalleryImageFormInline(ModelForm): class Meta: model = GalleryImage fields = ["image", ] def __init__(self, *args, **kwargs): super(GalleryImageFormInline, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.disable_csrf = True GalleryImageFormset = modelformset_factory(GalleryImage, fields=("image", ), can_delete=True, ) An UpdateView class GalleryUpdateView(LoginRequiredMixin, UpdateView): model = Gallery form_class = GalleryForm def get_context_data(self, **kwargs): context = super(GalleryUpdateView, self).get_context_data(**kwargs) context["images"] = GalleryImageForm() context["updateview"] = True current_images = GalleryImage.objects.filter(gallery=self.object) context["current_images"] = GalleryImageFormset(queryset=current_images) return context def form_valid(self, form): http_response_redirect = super(GalleryUpdateView, self).form_valid(form) images = self.request.FILES.getlist("file_field") for image in images: gallery_image = GalleryImage(gallery=self.object, image=image) gallery_image.save() current_images = GalleryImageFormset(self.request.POST, self.request.FILES) current_images.save() return http_response_redirect def get_success_url(self, **kwargs): return reverse_lazy('gallery:update', args=(self.object.id,)) And in the template: <form action="" class="uniForm" method="post" enctype="multipart/form-data"> {% csrf_token %} {% crispy form %} <hr/> {% crispy images %} <input type="submit" class="btn btn-primary" value="Opslaan"/> … -
Unifying Django and Django Rest Framework various reporting formats
We want to unify the format of the various exceptions returned by our Django REST framework-driven API. We've made use of the custom exception handler that DRF provides, however there are tons of different formats in which the different exceptions are returned (specifically DRF's own ValidationError exceptions) and we want to ensure they are all returned in a consistent manner. Then there are Django's own field validation exceptions that come in their own format (and are not even handled by DRF's custom validation handler). I'm thinking of going down the route of using some kind schema validation (supported by voluptuous or something like cerberus) where I go through all the schemas and if a match is found, then have some mapping from that format into the desired one. Is this an overkill? Is there a simpler way to accomplish this? -
Django Rest Framework: writable nested serializer
I need to manage a JSON like this: { "name": "drink_type", "description": "A type of drink", "values": [ { "value": "Coca-Cola", "synonyms": [ "coca cola", "coke" ] }, { "value": "Beer", "synonyms": [ "beer" ] } ] } models.py: class Entity(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) class Value(models.Model): entity = models.ForeignKey(Entity, related_name='values', on_delete=models.CASCADE) value = models.CharField(max_length=50) created = models.DateTimeField(auto_now_add=True) class Synonymous(models.Model): value = models.ForeignKey(Value, related_name='synonyms', on_delete=models.CASCADE) synonymous = models.CharField(max_length=50) created = models.DateTimeField(auto_now_add=True) serializers.py: class ValueSerializer(serializers.ModelSerializer): synonyms = serializers.SlugRelatedField( many=True, slug_field='synonymous', queryset=Synonymous.objects.all() ) class Meta: model = Value fields = ('value', 'synonyms') def create(self, validated_data): synonyms_data = validated_data.pop('synonyms') value = Value.objects.create(**validated_data) for synonyomous_data in synonyms_data: Synonymous.objects.create(value=value, **synonyomous_data) return value class EntitySerializer(serializers.ModelSerializer): values = ValueSerializer(many=True) class Meta: model = Entity fields = ('id', 'name', 'description', 'values') def create(self, validated_data): values_data = validated_data.pop('values') entity = Entity.objects.create(**validated_data) for value_data in values_data: # How can I call the create method of values? pass return entity views.py @api_view(['GET', 'POST']) def entity_list(request, format=None): """ List all entities, or create a new entity. """ if request.method == 'GET': entities = Entity.objects.all() serializer = EntitySerializer(entities, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = EntitySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The … -
Django template keyword `choice_value` in no longer work in 1.11
There is a multiple checkbox in template, if value contain in render the choice will checked by default. It works well with 1.10. form.py: class NewForm(forms.Form): project = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Project.objects.filter(enable=True) ) template: {% for p in form.project %} <label for="{{ p.id_for_label }}"> <input type="checkbox" name="{{ p.name }}" id="{{ p.id_for_label }}" value="{{ p.choice_value }}" {% if p.choice_value|add:"0" in form.project.initial %} checked{% endif %}> <p>{{ p.choice_label }}</p> </label> {% endfor %} views.py: def order_start(request, order_id): if request.method == 'POST': form = NewForm(request.POST) if form.is_valid(): order.end_time = timezone.now() order.save() order.project = form.cleaned_data['project'] order.save() return HttpResponsec(order.id) else: form = NewForm(initial={ 'project': [p.pk for p in order.project.all()], }) return render(request, 'orders/start.html', {'form': form, 'order': orderc}) When I upgrade to Django 1.11, {{ p.name }} and {{ p.choice_value }} return nothing. I know 1.11 has removed choice_value, but how to solve this problem? 1.10 https://docs.djangoproject.com/en/1.10/_modules/django/forms/widgets/ 1.11 https://docs.djangoproject.com/en/1.11/_modules/django/forms/widgets/ -
I can't connect to django server in browser.
Tried running it from local host but in cmd prompt its fine as i see "Quit the server with CTRL-BREAK.". But not connecting in browser. Also tried telnet to connect to that port, but failed. what could be the reason? can't be a proxy as even telnet is not workiingThis is the first basiic beginner level start for django. but the same thing, works in my office computer. pls hhelpenter image description here -
Mobile app for fetching server python data
I want to develop services or method to send the data over web and to mobile app as well.For now I am using Django Framework (Python code on server side) to get data on web page.I have developed web pages as well. Now I want to send same server data over Mobile App.So should I search for new web services or I can achieve the things using Django Framework. Please suggest libraries for REST/SOAP for python My mobile app will be developed in Android and iOS. Regards NM -
How limit a user to save database in django?
How do i restrict the user to save objects in db class model_name(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) user = models.ForeignKey(User) foo = models.CharField(max_length=51) i want to limit the foo only for 10 entries per user i am using mysql as a backend -
How to edit formset that has multiple forms inside related via generic foreign to the model of the current edit view?
In my recent project I had to create a generic model with a single file field, because the idea was to use multiple file uploads across multiple system models. For this I created this generic model with generic foreign key and in the add view I create a formset with the extra = 1 field and in the template via jquery I add forms inside my formset. In addition it works quietly, but I'm not able to adjust my edit view. In my edit view I try it: ModelGenericFormset = modelformset_factory( ModelsFileGeneric, form=AddModelsGenericForm ) query_files = ModelsFileGeneric.objects.filter( object_id=model_related_to_generic_model_with_file_field.id, ) files = ModelGenericFormset(queryset=query_files) and in request.post: files_form_set = ModelGenericFormset( request.POST, request.FILES ) for file_form in files_form_set: file = file_form.save(commit=False) setattr( 'upload_destination', 'path_to_upload' ) file.content_object = model_related_to_generic_model_with_file_field file.save() An observation: As this model where the file field is is an extremely generic model (for this reason the use of the generic foreign key), I also need at runtime (in the save in view after the post) to change the upload_to attribute of the field (this already Was fixed and works ok). I make this edition of the "upload_to" attribute. Because depending on the template to which I am sending multiple files, it … -
Connecting to external DB from django settings.py
We're searching for the best way to use different types of DBs in our Django project without defining them as Django DBs (the frameworks we're using keep changing and we want to have the most low-level client connection as possible). We're using django and would like to open several clients for external DBs which will be alive and available all the time (for example: aws-s3, mongoDB, elasticsearch). Currently, in the settings.py we create these connections and use them across the project. For example: From settings.py: MONGO_CLIENT = pymongo.MongoClient(MONGO_CLIENT_URI) And from views.py: from django.conf import settings Now we have the mongoClient available as: settings.MONGO_CLIENT If we would like to use this client in one of our project modules, we currently send it by reference. For example: res = myModule(mongoClient=settings.MONGO_CLIENT) * Please note that we prefer not to define the DBs as Django DBs. Now to the questions: I'm not sure this is the best way to-do it from memory and resources management perspectives since Django doesn't have any control of the connection to the DB? Is this the best way to send the db-clients between the modules? Thanks!