Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST and ModelViewSet filtering
I was previously using APIViews such as the following: views.py class AllProgramsApi(APIView): def get(self, request): user = self.request.user userprograms = Program.objects.filter(user=user) serializer = ProgramSerializer(userprograms, many=True) return Response(serializer.data) here's my model: class Program(models.Model): program_name = models.CharField(max_length=50) program_description = models.CharField(max_length=250) cycles = models.ManyToManyField(Cycle) is_favourite = models.BooleanField(default="False") user = models.ForeignKey(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('programs:program', kwargs={'pk': self.pk}) def __str__(self): return self.program_name Now I've discovered ModelViewSet, which looks very convenient, but I can't seem to be able to filter for the user as I was previously doing in the APIView. my attempt at views.py with ModelViewSet is the following and it works but I get all the content and not just the content related to a single user. class AllProgramsApi(ModelViewSet): serializer_class = ProgramSerializer queryset = Program.objects.all() How can I tweak the ModelViewSet so that it displays only the content related to the user who sends the request? What is the best method? Thanks. -
Django: Prevent Looping in between the Loop
I have a for loop in django! {% for abc in xyz %} {% endfor %} The variable 'xyz' contains data from 2 separate models! So, Is there a way for printing entire data by looping just once in a way like, Data from first Model DATA DATA etc. Data from second Model Data Data etc. If I'm doing this in just one loop then "Data from first/second Model" is also printed equal number of times as actual data. I wants to print it one without using multiple loops. So, is there any way to break this loop in between the loop itself & add some constant data? -
How to validate / change modelformset information when 2 forms are dependent on each other?
I have a django application which saves some user data using a regular form and a modelformset when the user clicks 'save'. So on a given page the user sees - there is the regular modelform (Benefit) and then below that on the same page is the modelformset with one 'save' button. When the user saves, both the modelform and the formset save their respective information. I have found that when working with modelformsets you should use the clean method for validation. Here is mine: class BaseDependentFormSet(BaseModelFormSet): def clean(self): b = Benefit.objects.get(id=self.data['benefit']) if 'PPO' in b.name: for d in self.cleaned_data: #print(d['has_medical']) #print(d['med_group_id']) d['med_group_id'] = '' print(d['med_group_id']) return self.cleaned_data As you can see - if the user has selected 'PPO' in the Benefit modelform, we eliminate any med_group_id they have associated in the modelformset. This code above does in fact erase the med_group_id as expected, but then when the page reloads, the med_group_id is still listed. My save looks like this: if dep_formset.is_valid(): for form in dep_formset: if form.is_valid(): try: form.save() Which saves fine - except that it's not saving the 'cleaned' values (empty) for med_group_id, it retains the original values. I had read somewhere that altering the data in the … -
Django complex query based on dicts
Tldr of Problem Frontend is a form that requires a complex lookup with ranges and stuff across several models, given in a dict. Best way to do it? Explanation From the view, I receive a dict of the following form (After being processed by something else): {'h_index': {"min": 10,"max":20}, 'rank': "supreme_overlord", 'total_citations': {"min": 10,"max":400}, 'year_began': {"min": 2000} 'year_end': {"max": 3000} The keys are column names from different models (Right now, 2 separate models, Researcher and ResearchMetrics), and the values are the range / exact value that I want to query. Example (Above) Belonging to model Researcher : rank year_began year_end Belonging to model ResearchMetrics total_citations h_index Ideally: I want to show the researchers who fulfill all the criteria above in a list of list format. Researcher ID, name, rank, year_began, year_end, total_citations, h_index [[123, Thomas, professor, 2000, 2012, 15, 20], [ 343 ... ]] What's the best way to go about solving this problem? (Including changes to form, etc?) I'm not very familiar with the whole form query model thing. Thank you for your help! -
How should I write test code?
I wrote test code in tests.py like this: #coding:utf-8 from django.test import TestCase from app.models import User # Create your tests here. class UserModelTests(TestCase): def setUp(self): self.user1 = User.objects.create(name='Tom', group = 'A',age=20,rank=1) def test_user1_name(self): self.assertEqual(self.user1.name, 'Tom') def test_user1_group(self): self.assertEqual(self.user1.group, 'A') def test_user1_age(self): self.assertEqual(self.user1.age, 20) def test_user1_rank(self): self.assertEqual(self.user1.rank, 1) But I thought my test code is meaningless. Arguments Data.objects.create has is really in db. How should I write it to compare the db results and value I want to compare for the test? -
Forbidden (CSRF token missing or incorrect.) Django how to solve?WITH MY CODE
when i press button, this error is blow up Forbidden (CSRF token missing or incorrect.): /orders/basket_adding/ / I take csrf_token from the form on the main page, all the others inherit from the page where the form is, from where I get the token! Pls help me) views def basket_adding(request): print('HER') return_dict = {} session_key = request.session.session_key data = request.POST context = {} return JsonResponse(return_dict) ///// ///// html {% extends "base.html" %} {% load staticfiles %} {% block content %} <div class="single"> <div class="container"> <div class="single-main"> <div class="single-top-main"> <div class="col-md-5 single-top"> <div class="flexslider"> <ul class="slides"> {% for img in images %} <li data-thumb="{{ img.image.url }}"> <div class="thumb-image"> <img src="{{ img.image.url }}" data-imagezoom="true" class="img-responsive"> </div> </li> {% endfor %} </ul> </div> </div> <div class="col-md-7 single-top-left simpleCart_shelfItem"> <h2>{{ product_himself.brand.name_of_brand }}</h2> <h1 class="product_name" action="{% url 'orders:basket_adding' %}" >{{ product_himself.name_of_product }}</h1> <p class="hidden product_id">{{ product_himself.id }}</p> {% if product_himself.discount %} <span>$<strike>{{ product_himself.price_of_product }}</strike>&nbsp;&nbsp;$<span class="item_price">{{ product_himself.price_with_discount }}</span></span> {% else %} $<h6 class="item_price">{{ product_himself.price_of_product }}</h6> {% endif %} <p>{{ product_himself.description }}</p> <h4>Size</h4> <ul class="bann-btns"> <li><select class="bann-size"> <option value="s">Small</option> <option value="m">Medium</option> <option value="l">Large</option> </select> </li> <li><a href="#" class="item_add">Add To Cart</a></li> </ul> </div> <div class="clearfix"> </div> </div> <div class="singlepage-product"> {% for smart in img_bran %} <div class="col-md-3 home-grid"> … -
Change a Django Model with Javascript
So i want to change the Django Module to +1 everytime someone presses the button without reloading the Page. I think its called Ajax. JS: $('.buttonclass').click(function(){ var pk; pk = $(this).attr("data-pk"); }); html: <span data-pk="{{post.pk}}" class="buttonclass"></span> my_views.py def upvote(request): pk = None if request.method == 'GET': pk = request.GET['pk'] obj = models.Post.objects.get(pk=pk) obj.upvotes = obj.upvotes +1 obj.save() return redirect("index") #without this post: class Post(models.Model): upvotes = models.IntegerField(default = 0) So how exactly can i do this? -
replace url in Django template
{% if shelf.script or shelf.log_url %} {% if shelf.log_url %} Log URL: {{ shelf.log_url }}<br /> {% endif %} {% if shelf.log_url %} <b>Another URL:</b> {{ shelf.log_url.replace("/tmp/BOOTLOG/", "http://www.sxp.com") }}<br /> {% endif %} {% endif %} I have already got a log url, I would like to update this url with with a domain address and adding /index.html to at the end. I would like to replace this url shelf.log_url output = /tmp/BOOTLOG/darwin_12345.tgz to something like this. www.sxp.com/darwin_12345/index.html How can I do in Django template ? -
Cannot run PyDev : Django when running with Eclipse Oxygen
New to Python (just learning it). I have the following setup on Windows 10: Python 3.6.2 (pip 9.0.1), Django 1.10 Eclipse IDE and PyDev IDE for Eclipse 6.0.0 (installed using Eclipse Marketplace under Eclipse Oxygen). I had chosen this combination because I wanted to be able to debug any code that was developed. I have created a Django Project (New -> PyDev Djangon) with the settings in the attachment I used the following settings with DJango itself because my goal is to use REST APIs for DB access (and not access the DB directly) - I wanted to use the REST functions with Android apps as well. When doing "right-mouse-click: ProjectName -> PyDev: Django", the internal website does not come up. Why is this the case? When looking for a combination of "Eclipse", "PyDev", "DJango" (to seek out an answer), I see articles that are 2 years old or older. Does anyone use this way of developing web applications under Python anymore? If not, is there a better option? TIA -
django oscar dashboard default credentials
I would like to know whats Django's Oscar dashboard default credentials. (since I couldn't enter it). In addition, Is there any alternative more recommended for Django e-commerce? Thank you. -
How to test import image into cloudinary with django?
I started creating django unit tests for my project referring to the django documentation. But in my case I can't find documentation on how to test an upload of a picture into cloudinary, how to know if the import is succeeded. I have created this unit test to test the upload of a picture : def test_upload_profile_picture(self): url = self.reverse('save_profile_picture') img = '/images/img.jpg' self.client.login(username=self.username, password=self.password) with open(img, 'rb') as infile: response = self.client.post(url, {'picture': infile}) self.assertRedirects(response, self.reverse('edit_profile')) But I guess this is not correct since I really don't know if the image is really uploaded to cloudinary or not . Has someone an idea about how to do this ? Thanks in advance. -
django-statsy seem to be a doubtful app
I have a bit of difficulties to understand how django-statsy works. Does anyone be able to tell me if it works well for them? I am a new programmer in Django and using the template, but it is unclear that we could use the following structure in a .html template : var statsy = new Statsy() statsy.send({ 'group': 'post', 'event': 'subscription' }); Am I right? Otherwise, how could we use that code in a .html file? Could anyone be able to tell me what is this writing, because I am not familiar with it? -
Unable to re-authenticate evernote
This is a bit embarrassing. Several years ago I set up some productivity scripts in python etc on the evernote production sdk. My authentication token expired today and the method I was using (PHP) to get a token has stopped working on my server. Yes, I used PHP to get the token and python to do the work. That's a long story in itself. Anyway I got a django instance up and running and can get the evernote sample script listing my production notebooks. But how do I grab the actual authentication token so I can store it and deploy it into my scripts? Sorry for asking such a dumb question but I'm too busy to dig at the moment and I need to access those scripts! -
Django REST framework HyperlinkedModelSerializer
I'm working on streamlining how I include different models in the API for my Djangp app. Previously I had it set it where each model had a Viewset and a Serializer separately defined for it. Instead I'm working on a more generic method whereby I just pass in a Model and a list of relevant fields, and will be added to the API automatically. The problem I'm running in to currently is with defining the serializer_class: from myapp import MyModel from rest_framework.serializers import HyperlinkedModelSerializer from rest_framework.viewsets import ModelViewSet app_name = 'myapp' fields = ('field1', 'field2', 'field3') queryset = MyModel.objects.all() # Problem is here serializer_class = HyperlinkedModelSerializer(model=MyModel, fields=fields) viewset = ModelViewSet(queryset=queryset, serializer_class=serializer_class) # Then to register it all with the router: self.register(app_name + '/' + model.__name__, viewset) I get the error: TypeError: __init__() got an unexpected keyword argument 'fields' The problem seems to be that in HyperlinkedModelSerializer, 'model' and 'fields' are normally defined as Meta options so it doesn't seem to accept them when they are provided in this way. Is there a way to achieve this? Thanks. -
Validate special character while entering text in Django model field
I have a django model class Order(AbstractOrder): number = models.CharField( _("Order Number"), max_length=40, db_index=True, unique=True, validators = [ RegexValidator( regex=r'^[-,_\w]*$', message=_("Only AlphaNumerics and , - _ are allowed"))]) I have added the regex check for number field and on click of save it is properly validating, but my requirement is i want to validate it while entering itself, How i can achieve it, how can i integrate js to validate it. -
Invalid column name 'id' in Django
Before you guys start down voting my question, please read the description. So i'm using Django models in a different way, I have existing tables in MS SQL server and I would like to access them for my application. I've been following some tutorials in pluralsights and also https://docs.djangoproject.com/en/1.11/howto/legacy-databases/. I followed the steps accordingly and got my models ready and,when i used 'migrate' command, I got this error “AssertionError: A model can't have more than one AutoField.” So I looked up SO and got another documentation by Django By default, Django gives each model the following field: id = models.AutoField(primary_key=True) This is an auto-incrementing primary key. If you’d like to specify a custom primary key, just specify primary_key=True on one of your fields. If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added). So by his solution, i've added 'id' column to the tables which don't have a primary key and skipped the ones which had. And my 'migrate' command worked smooth. But When I'm trying to test if i can get values from it, it shows Invalid column 'ID' Now, … -
django implement filter on in template
i m buiding an in terface (something like phpmyadmin) but more userfriendly...i ve imported all tables but now i want to add sort,filter and search on every table. this is my tables/views.py def table_base(request): table_name = Crawledtables._meta.db_table list_tables = Crawledtables.objects.order_by('id') return render(request, 'tables/table_base.html', {'table_name': table_name, 'list_tables': list_tables}) class AboutDetail(DetailView): model = Crawledtables pk_url_kwarg = 'table_id' template_name = 'tables/table_list.html' def __init__(self, **kwargs): super(AboutDetail, self).__init__(**kwargs) def get_object(self): if 'table_id' not in self.kwargs: return Crawledtables.objects.get(id=1) else: return Crawledtables.objects.get(id=self.kwargs['table_id']) def addview(request, table_id): table_name = Crawledtables.objects.get(id=table_id) tbl_details = "SELECT * FROM " + table_name.name tbl_detail = AllTables.objects.raw(tbl_details) paginator = Paginator(list(tbl_detail), 100) page = request.GET.get('page') try: details = paginator.page(page) except PageNotAnInteger: details = paginator.page(1) except EmptyPage: details = paginator.page(paginator.num_pages) crawled_tables = AllTablesFilter(request.GET, queryset=tbl_detail) return render(request, 'tables/table_list.html', {'tbl_name': table_name, 'details': tbl_detail, 'filter': crawled_tables, 'detail_page': details}) def GeneralSearch(request): table_list = Crawledtables.objects.all() crawled_tables = GeneralFilter(request.GET, queryset=table_list) return render(request, 'tables/table_search.html', {'filter': crawled_tables}) def AllTablesSearch(request, table_id): table_name = Crawledtables.objects.get(id=table_id) tbl_details = "SELECT * FROM " + table_name.name table_list = AllTables.objects.raw(tbl_details) # table_list = Crawledtables.objects.all() crawled_tables = AllTablesFilter(request.GET, queryset=table_list) return render(request, 'tables/alltables_search.html', {'tbl_name': table_name, 'filter': crawled_tables}) this is my tables/filter.py class GeneralFilter(django_filters.FilterSet): class Meta: model = Crawledtables fields = ['name', 'date'] class AllTablesFilter(django_filters.FilterSet): class Meta: model = AllTables fields = ['id','title', 'url','description'] … -
django form widget, compound select
I'm trying to create a form field in django where the user can select the number of years and months, (to ultimately store the number of months - will convert years to months). However I'm not sure of the relevant widget to use in django to achieve this. (or if this needs to be done via more than one widget?) The SelectMultiple widget doesn't appear to be multiple select form fields but instead used to select multiple option in one select. eg see the pic -
Django admin: many-to-one relationships and creation of new "many" object from existing "one"
Django==1.11.5 I have two models: class Sheet(models.Model): canonical_image = models.ForeignKey('images.Image', blank=True, null=True, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_related", verbose_name=_("canonical image")) class Image(models.Model): sheet = models.ForeignKey(Sheet, on_delete=models.PROTECT, verbose_name=_("sheet")) pass I registered the models for Django admin. Now when I change the sheet in admin, I see "Canonical image" and a plus button to add an image. If I press the plus button, a form for creating a new Image appear. And there is going to be a drop down list with choices sheets. There is a bunch of sheets there. This is clumsy. I press a plus sign from a definite sheet. That very sheet should be selected for creation a new image. Could you tell me how to cope with this problem. Maybe to limit the choice to that particular sheet. Or remove the sheet from image creation form and substitute it in input type="hidden". Or something else. The easier the better. -
how to implement django-easycart in django
how do you implement this https://github.com/nevimov/django-easycart to show items in it. As at now it is showing and empty -
python-memcached installation failed using pip and conda in Python 3.6
python-memcached library failed to installed in Python 3.6 Commands: pip install python-memcached Trace: Collecting python-memcached Downloading python-memcached-1.58.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\JSR\AppData\Local\Temp\pip-build-j63q50jp\python-memcached\setup.py", line 8, in <module> version=get_module_constant('memcache', '__version__'), File "F:\installed\conda2_installed\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\depends.py", line 164, in get_module_constant File "F:\installed\conda2_installed\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\depends.py", line 195, in extract_constant IndexError: tuple index out of range ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\JSR\AppData\Local\Temp\pip-build-j63q50jp\python-memcached\ Commands: conda install -c anaconda python-memcached Trace: Fetching package metadata ............. Solving package specifications: . UnsatisfiableError: The following specifications were found to be in conflict: - python 3.6* - python-memcached -> python 2.7* Use "conda info <package>" to see the dependencies for each package. Command For Info Dependencies: conda info python-memcached Output: python-memcached 1.57 py35_0 file name : python-memcached-1.57-py35_0.tar.bz2 name : python-memcached version : 1.57 build string: py35_0 build number: 0 channel : defaults size : 45 KB arch : x86_64 date : 2015-10-01 license : OSI license_family: PSF md5 : ce80c762e4fcd7aa7b7c1d3aa1e74424 noarch : None platform : win32 url : https://repo.continuum.io/pkgs/free/win-64/python-memcached-1.57-py35_0.tar.bz2 dependencies: python 3.5* six -
Why am I getting ' when AJAX saving (and repopulating) my form in Django
I'm saving a draft of my form using AJAX (and a bit of Angular). <!-- index.html --> ... <input id="id_title" name="title" ng-model="title" placeholder="Question Title" type="text" value="" required /> ... <script> app.controller("addQuestionCtrl", function($http) { $scope.title = '{% if form.title.value is not None %}{{ form.title.value }}{% endif %}'; ... $interval(function() { ... data = {title:''+$scope.title, ...}; $http.post("{% url 'save_draft' %}", data).then(function(response) { ... }, function failureCallback(error) { ... }); }, 10000); }); </script> This is all works fine and sends a ' as a '. In my view.py I convert the data and store it in the session: def save_draft(request): .... posted = json.loads(request.body.decode("utf-8")) ... request.session['draft'] = { 'title': posted.get('title', None), ... } and then populate the relevant fields when the page loads def question_add(request): .... if request.method == 'POST': .... else: draft_question = request.session.get('draft', False) if draft_question: form = QuestionAddForm(initial={ 'title':draft_question['title'], ... }) Unfortunately this turns this into this it's not an encoding issue on the client end as the field renders as <input id="id_title" name="title" ng-model="title" ... value="&#39;title in quotes&#39;" /> I'm not to sure why this is happening :( -
How return list to Json objects with dictionaries?
I have a python list which is structured as l = [{ "Letter": "A", "Freq": 20 }, { "Letter" : "B", "Freq": 12 }] When I return this as a json with json.dumps(l) and parse it in js with JSON.parse(data) I am getting an array. But what I am aiming for is that js parses it as an object. My goal is to render the json part of this tutorial in Django. -
Memory management in Django
I'm doing some analysis on my Django database. I do many queries in a loop and some of these queries may return big results. So, after a while the whole 8 GB of RAM on my EC2 instance is eaten and I cannot even ssh to the machine any longer. I have to reboot the instance then start over again. I tried the solution mentioned here: https://baxeico.wordpress.com/2014/09/30/optimize-django-memory-usage/ But the queryset_iterator method seems not to work with aggregated queries. I'm pretty sure that any single query cannot consume all 8 GB of RAM. So, this means that the old results are not deleted from memory. How do I force a query out of the memory before the end of its loop iteration and before executing the next query? -
How to translate djangocontrib.messages
I'm using django-admin to add and update few models. I translated the django-admin successfully to arabic.( the page, modal names and fields....) The only problem is that django.contrib.messges don't get translated. For example: when I add a new object , I get "%name was changed successfully " in english. Right now, I figured this method: def save_model(self, request, obj, form, change): messages.sucess(request, _('%name changed successfully.')) self.save() But I have to do it to every model, and to every message level (success, info, warning....) Is there a better way ?