Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to apply postman filters in django?
I am trying to implement a POST method from a JSON object in Django but I do not know how to apply this POST method. I have the following code: Method POST from Postman { "filter": { "filters": [ { "field": "CreatedOn", "operator": "gte", "value": "2017-02-12 00:00:00" }, { "field": "CreatedOn", "operator": "lte", "value": "2017-03-12 00:00:00" }, { "field": "VIP", "operator": "eq", "value": "YES" } ], "logic": "and" } } Code Snippet to parse a JSON to Python def get_data(request, *args, **kwargs): with urllib.request.urlopen("http://10.61.202.98:8081/T/ansdb/api/rows/dev/ect/tickets",timeout=15) as url: response_data = json.loads(url.read().decode()) user_id = [value['user_id'] for value in response_data] print(user_id) return JsonResponse(response_data, safe=False) JSON object that I want to filter [{ id: 1003384, user_id : 0001 CreatedOn: "2017-02-16 15:54:48", Problem: "AVAILABILILTY", VIP: "YES", Vendor_CODE: "XYZ12345", Week_id: "07", }, { id: 1003338, user_id: 0002 CreatedOn: "2017-02-15 13:49:16", Problem: "AVAILABILILTY", VIP: "NO", Vendor_CODE: "XYZ67890", Week_id: "09", }] -
Prevent PyCharm from opening the browser/new tab on run
I found a number of people who want PyCharm to open the browser/a new tab every time you click run. https://intellij-support.jetbrains.com/hc/en-us/community/posts/206590705-How-do-I-setup-Run-Debug-Config-to-open-browser-automatically-for-Flask- Django manage.py runserver doesn't open browser Well, I click run often and already have the tabs open I need. It's quite frustrating to have to close the new ones, and I want to turn it off. I have looked thru all the menus and I can't find the Run browser setting some people talk about. I also tried disabling all Django support for browsers in Settings -> Tools -> Browsers, but this made no difference. Versions: PyCharm 2017.1.1 Python 3.5.x Django 1.10 -
Django Url pattern (add paramether), and view
There is urls.py pattern. url(r'^notice/(?P<article>[0-9]\d+)/', web.views.notice), Here is views.py def notice(request, article): data = article return render(request, "notice.html") However, web brower shows 404 Error. If I remove add parameter, it is ok. What I am wrong? -
How will django datadump overwrite existing records in database?
My production database currently contains 4k MyModels (loaded from the dev database last year). I started working on this project again. I now have 270k MyModels (including the original 4k MyModels). I want to export this new datadump to my production database. What will happen to the 4k MyModels already there (doing a simple dumpdata/loaddata)? How will the records be overwritten? -
Replicate part of production django database to local or staging
I have a Django website with 3 environments (Local, Staging, Production). Production contains some data that I don't want my developers to have access to (Personal data and financial data of users). Doing a DB backup restore is not an option for compliance reason. However we also have some content pages on this website that we manage with Wagtail CMS. I am looking for a way to sync production data (only some models but specifically the wagtail pages) back to Staging and Developers local environment when they need to. Ideally I would have a manage command that I can run in another environment to copy data: Ex: ./manage.py sync_from_prod BlogPost this would find all missing blog post in the local or staging environment and would create them in the database. I cannot find any library doing this for Wagtail or Django doing this. This seams like a common problem and I am surprised to find no Stackoverflow questions or opensource libraries fixing this problem. If nothing exist I will probably try to write my own django-model-sync (Found this project, but is 3 year old and compatible until django 1.7 and I am on python3 django 1.11) In order to manage … -
Multiple django sites with mod_wsgi on apache
I had some headaches setting up Apache24 with Python27 and wsgi (for django 1.11.1) for multiple sites on Windows Server 2012. The setup was 64-bit. Web searches are contradictory, so I thought I'd give it a try (I'm in the process of learning django). Now that I've set it up, I thought I'd post about it in case it will help some other django newbie. I found that you can use the vc10 msvcrt dll msvcr100.dll in this setup, which supposedly requires vc9 (numerous posts). I put it in the apache bin directory and it works fine for me. It is downloadable from https://www.dll-files.com/msvcr100.dll.html . My setup is as follows. project/ is the project directory, and I have 2 sites site1 and site2 each with its own database. Directory structure: ./src: project/ site1.sqlite3 site2.sqlite3 ./src/project: __init__.py manage.py site1/ site2/ settings.py static/ urls.py wsgi.py settings.py: ... BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ... INSTALLED_APPS = [ 'site1.apps.Site1Config', 'site2.apps.Site2Config', ... ] ... ROOT_URLCONF = 'urls' ... WSGI_APPLICATION = 'wsgi.application' ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'site1.sqlite3'), }, 'site1': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'site1.sqlite3'), }, 'site2': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'site2.sqlite3'), } } The default is used for everything that … -
Django Cannot assign "[<Customers: wewew>]": "Sites.customers_id" must be a "Customers" instance
Python, Django. I'm trying to create a form for inserting data into database. Getting error while trying to add a new customers site via form: ValueError at /new_site/ Cannot assign "[]": "Sites.customers_id" must be a "Customers" instance. Model: class Customers(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey('auth.User', null=True) name = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.name class Meta: verbose_name_plural = "Customers" class Sites(models.Model): id = models.AutoField(primary_key=True) customers_id = models.ForeignKey(Customers,null=True) author = models.ForeignKey('auth.User',blank=True, null=True) adress = models.CharField(max_length=100, help_text="Example: http://stackoverflow.com/") s_login = models.CharField(max_length=100, blank=True, default='', help_text="Login and password if required." ) s_password = models.CharField(max_length=100, blank=True, default='') certificate = models.CharField(max_length=100,blank=True, default='',help_text="File's name") def __str__(self): return self.adress class Meta: verbose_name_plural = "Sites" Forms: class SitesForm(forms.ModelForm): customers_id = forms.ModelMultipleChoiceField(queryset=Customers.objects.filter(author_id=1)) adress = forms.CharField(max_length=100, help_text="Example: http://www.stackoverflow.com/") s_login = forms.CharField(max_length=100, required=False, help_text="Login and password if required.") s_password = forms.CharField(max_length=100, required=False) certificate = forms.CharField(max_length=100, required=False, help_text="File's name if required") class Meta: model = Sites fields = ( 'customers_id','adress','s_login', 's_password', 'certificate') def __init__(self, user, *args, **kwargs): self.user = user super(SitesForm,self).__init__(*args, **kwargs) cust = Customers.objects.filter(author_id=user.id) self.fields['customers_id'].queryset = cust View: def new_site(request): if request.method == 'POST': form = SitesForm( request.user, request.POST) if form.is_valid(): site = form.save(commit=False) site.author = request.user cusomer.customers_id = request.customers_id site.save() return redirect('/customers/') else: form = SitesForm( request.user) return … -
Why use VueJs data-binding vs Django?
Why use VueJs data-binding vs Django? It seems there is no advantage using VueJs in this instance. -
How to pass argument to Django model field while creating object?
I have models like this :- class ModelA: id = CustomizedIDField(my_type='cat') class ModelB: id = CustomizedIDField(my_type='dog') class ModelC: id = CustomizedIDField() from python shell, I want to create a ModelC where I want to pass my_type='cat' while creating object. so that I can store the customized ID of some object of ModelA into ModelC. So my question is how can I pass my_type argument while creating an object. What I tried but didn't work. ModelC.objects.create(id__my_type='cat') Let me know If my question is unclear to you. Thanks in advance :) -
Create a popup for confirming delete action using django-popup-view-field
I'm trying to create a popup for confirming delete action using django-popup-view-field. I have been following an example given in https://pydigger.com/pypi/django-popup-view-field. The challenge I face is for me to pass a primary key for the user I want to delete when I click on the delete button in he drivers_list.html. Here's my code:` drivers_list.html {% for driver in object_list %} <tr> <td>{{ driver.first_name }} </td> <td>{{ driver.last_name }}</td> <td>{{ driver.licence_category }}</td> <td>{{ driver.phone }}</td> <td>{{ driver.email }}</td> <td>{{ driver.status }}</td> <td align="center"> <a href="{% url 'view_driver' pk=driver.id %}"><button class="btn btn-success btn-sm">View</button></a> <a href="{% url 'edit_driver' pk=driver.id %}"><button class="btn btn-primary btn-sm">Edit</button></a> <a href="{% url "django_popup_view_field:get_popup_view" 'delete_driver' pk=driver.id %}"><button class="btn btn-danger btn-sm">Delete</button></a> </td> </tr> {% endfor %} **driver_confirm_delete.html** <h4><span class="label label-warning">Are you sure you want to delete {{ driver.first_name }} {{ driver.last_name }}?</span></h4> <div class="row"> <div class="col-md-4"> <form action="{{ target }}" method='POST'> {% csrf_token %} <h4><span class="label label-warning">NOTE:This action cannot be reversed!</span></h4> <ul> {{ form.as_ul }} </ul> <input type="submit" class="btn btn-danger btn-md" value="Confirm delete"/> <a href="{% url 'drivers_list' %}"><button type="button" class="btn btn-info btn-md">Cancel</button></a> </form> </div> </div> urls.py urlpatterns = [ url(r'^delete_driver/(?P<pk>\d+)/$', d_views.DeleteDriverView.as_view(), name='delete_driver'), url(r'^django_popup_view_field/', include('django_popup_view_field.urls', namespace="django_popup_view_field")),] views.py class DeleteDriverView(FormMessagesMixin, DeleteView): model = Driver template_name = 'drivers/driver_confirm_delete.html' success_url = reverse_lazy('drivers_list') form_valid_message = 'Driver … -
NginX permission denied 13
I have come upon a permissions problem with my engine-X when following the tutorial on http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html I've tried the suggested workarounds found in simillar questions but none of them was any help. (setting Selinux to permissive, adding chmods for uwsgi or even running nginx as root) Here's a dump of the error from nginx error.log Anyone got any ideas? I probably won't be using nginx with virtualenv if this cannot be fixed. [crit] 3123#0: *3 connect() to unix:///home/mb/uwsgi-tutorial/mysite mysite.sock failed (13: Permission denied) while connecting to upstream, client: 127.0.0.1, server: 127.0.0.1, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:///home/mb/uwsgi-tutorial/mysite/mysite.sock:", host: "localhost:8000" -
No reverse match django class based views
I m new to Django and I am learning it through a project but m stuck with this error which says that NoReverseMatch at /product/create/ here is my model.py file from django.db import models from django.conf import settings from django.core.urlresolvers import reverse # Create your models here. class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='category_created') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='product_created', null= True,blank=True) category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) negiotiable = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='product_liked', blank=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('products_detail', args=[self.slug]) This is my views.py but I m not sure if there is something wrong with my views from django.views.generic import * from django.core.urlresolvers import reverse_lazy from .models import Category, Product class CategoryList(ListView): model = Category class CategoryDetail(DetailView): model = Category class ProductList(ListView): model = Product class ProductDetail(DetailView): model = Product class ProductCreate(CreateView): model = … -
Django post 403 from frontend app
I can't manage to make a successful post request to my database, I keep getting post url 403 (Forbidden). I think it's because of my csrf token since from the admin I can make the post requests without any problem. My setup is: Api View: class ContactFormViewSet(viewsets.ModelViewSet): queryset = ContactForm.objects.all() serializer_class = ContactFormSerializer def post(self): # This returns metrics only for the logged in user user_id = self.request.user.id return GoogleProperty.objects.filter(user_id=user_id) Serializer: class ContactFormSerializer(serializers.ModelSerializer): class Meta: fields = ( 'google_email', 'property_name', 'url', 'message', 'created' ) model = ContactForm My Settings look like this: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', ), } Finally my axios call looks like this: var url = '/api/v2/messages/' let token = document.head.querySelector("[name=_token]").content console.log(token) axios.post(url,{ headers: {"X-CSRFToken": token}, data: { google_email:'vm.email', property_name:'vm.property', url: 'sss', message: vm.message, xsrfHeaderName: token } }) And I have a meta tag like this <meta name="_token" content="{{ csrf_token }}"> The token get's print-out fine in my console, I prefer this method because I'm not using jquery. I've followed this answer/question but it doesn't seem to work for me. Why my post requests fail? -
Django render: How to instance selected items in Select2 Jquery plugin
I'm filtering some data using Raw method, it allows the user to select multiple values in a field using Select2 plugin, I get request.POST of each field, do filtering stuff, then I return the context like this: context = { 'form': MyForm(request.POST), 'results': results, } return render(request, self.template_name, context) It's suppossed to show the user which fields were selected when I get back the results to show them, but when the form renders I get selected only the first value of the list (retrieved from POST). Do I have to set something else? Or am I doing something wrong? -
django-rest-swagger can't seem to work for me. I can't get it to document anything beyond a title
IT seems like Django + Swagger for DRF dropped support for the YAML documentation, and replaced it with a vague non-documented way to do things. I've spent the last 48 hours trying to understand how I can have it document the parameters that go into my post methods. For instance: I have this: @api_view(['GET', 'POST']) @permission_classes([AllowAny]) @authentication_classes([]) def address_view(request): """ This text is the description for this API. """ print(request.user.id) print(request.user.email) if request.method == 'GET': addresses = Address.objects.all() serializer = AddressSerializer(addresses, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = AddressSerializer(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) But the Django-Swagger will show it as: in my code comment. Can someone point me in the direction of something that works where I can define all the rich data that swagger allows, like the post field names, if they're mandatory or not. etc. i'm just going crazy here running in circle and can't find anything but complaints that there's no way to do this. -
How to filter queries by using other queries in django
I am trying to apply a filter using another queryset as the filter parameter. para = Parameters.objects.filter(somecode) Now this para is to be used as a parameter for another filter. Something like (I know this won't work, but) qs = Colums.objects.filter(fieldname = para) As in qs should have objects from para[0] and para[1]. I tried to concatenate by for loop but I couldn't work it out. Is there any way I can get qs as a combined results of para[0] and para[1]? -
Django submitting a model form and Stipe checkout form
I am learning Django and I am trying to learn how integrate Stripe into my current setup. I have two forms in my template: <form id="user-input-form" enctype="multipart/form-data" method="POST"> {% csrf_token %} {{form.link.errors}} {{form.link}} {{ form.video }} {{form.video.errors}} <button name="submit" id="customButton" class="btn btn-primary">Buy</button> </form> <form action="" method="POST"> {% csrf_token %} <button id="customButton" class="center btn btn-primary">Buy</button> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key=stripe-key </script> </form> user-input-form (a model form) takes a link and a video and then stores it into a database and the second form is not attached to a model and it is used to retrieve the Stripe token to use Stripe's checkout. However, I would like to somehow use them together so that I can submit a link and video after I have completed stripe's checkout. But for that I need to get both the stripe token and the link and video file together. How can I achieve this? This is what I am trying now without success: class BuyView(View): def get(self, request): submit_form = SubmitLink() return render(request, 'buy/buy.html', {'form': submit_form}) def post(self, request): submit_form = SubmitLink(request.POST, request.FILES) if 'submit' in request.POST: if submit_form.is_valid(): channel.save() token = request.POST.get("stripeToken") stripe.api_key = settings.STRIPE_API_KEY; # Charge the user's card: charge = stripe.Charge.create( amount=0, currency="usd", source=token, … -
Getting Django's staticfiles includes working inside Vue.js .vue templates
I have a Django SPA built with Vue.js v2 / webpack. I want to be able to use Django static template tags to add in references to images, etc inside Vue.js template .vue files. Right now in my base.html template for Django: {% load static %} {% load render_bundle from webpack_loader %} <html> <head> <!-- This works fine here! --> <link rel="stylesheet" href="{% static 'css/test.css' %}" /> ... </head> <body> <div id="app"> <!-- Vue.js app gets mounted here --> </div> </body> </html> and that is of course the HTML page I use for the SPA (single page application). But when I try to use static tags in my .vue template files like so: {% static 'js/test.js' %} It doesn't work - it never gets interpolated because of course Django is server-side and Vue is client-side. I want to keep using the staticfiles tags (and not hard links) because I use different storage backends for static files, media, and even from local/staging/prod environments. Any ideas for how to handle this with Django/Vue.js? What's a good solution here to get staticfiles linking into templates clientside? -
Overriding Djangorest ViewSets Delete Behavior
I have defined a Model like this: class Doctor(models.Model): name = models.CharField(max_length=100) is_active = models.BooleanField(default=True) My Serializer: class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = ('id', 'name', ) In View: class DoctorViewSet(viewsets.ModelViewSet): queryset = Doctor.objects.all() serializer_class = DoctorSerializer Now, I can delete a doctor by calling the url: 'servername/doctors/id/', with the http method DELETE. However, I want to override the delete behavior for this model. I want that, when the user deletes a record, it's is_active field is set to false, without actually deleting the record from the database. I also want to keep the other behaviors of Viewset like the list, put, create as they are. How do I do that? Where do I write the code for overriding this delete behavior? -
Vue.js / webpack: how do I clear out old bundle main-*.js files when hot-reload transpiles them?
I'm using Vue.js to make an SPA application with Django and I transpile, uglify, and bundle the code using webpack (specifically webpack-simple from vue-cli setup). I use the following to "watch" and hot-reload the code: $ ./node_modules/.bin/webpack --config webpack.config.js --watch The problem is every time I change the code and it gets built it generates a new bundle .js file and updates webpack-stats.json to point to that one, but doesn't delete the old ones. How do I have it delete the old (useless) files? webpack.config.js: var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') function resolve (dir) { return path.join(__dirname, dir) } module.exports = { context: __dirname, // entry point of our app. // assets/js/index.js should require other js modules and dependencies it needs entry: './src/main', output: { path: path.resolve('./static/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, sourceMap: true }), ], module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader'}, // to transform JSX into JS {test: /\.vue$/, loader: 'vue-loader'} ], }, resolve: { extensions: ['.js', '.vue', '.json'], alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src') } }, } webpack-stats.json: { "status":"done", "chunks":{ "main":[ { "name":"main-faa72a69b29c1decd182.js", "path":"/Users/me/Code/projectname/static/bundles/main-faa72a69b29c1decd182.js" } ] … -
using django with celery can increase request per second?
I read this page And I was disappointed about the django request per second Question: using django with celery can increase request per second? -
ModelForms & DRY placeholders
So I wanted a DRY way to specify the placeholders for my form fields. So whipped up this Mixin: class FormPlaceholderMixin(object): def __init__(self, *args, **kwargs): super(FormPlaceholderMixin, self).__init__(*args,**kwargs) for index, placeholder in self.PLACEHOLDERS.iteritems(): self.fields[index].widget.attrs['placeholder'] = placeholder This works great as it allows me to do this: class PostcardOrderForm(FormPlaceholderMixin, forms.ModelForm): PLACEHOLDERS = { 'name': 'Order Name', 'order_contacts': 'Send it only to contacts in this group...', } class Meta: model = PostcardOrder fields = ['name', 'order_contacts'] Although this is kinda ugly. I would rather do this: class Meta: # ... placeholders = { 'name': 'Order Name', 'order_contacts': 'Send it only to contacts in this group...', } But when I inspect self._meta, the placeholders dict is no where to be found. Why is this and I can I make that work? -
How to obtain csrf token for a python POST request to Django server
Without the csrf token I am getting a 403 Response, so it looks like I need it. I am currently trying to do this: import requests import sys URL = 'http://127.0.0.1:8000/toasterinfo' client = requests.session() # Retrieve the CSRF token first client.get(URL) # sets cookie csrftoken = client.cookies['csrf'] r = client.post(URL, data={'number': 12524, 'type': 'issue', 'action': 'show', "csrfmiddlewaretoken": csrftoken}, headers=dict(Referer=URL)) print(r) Yet I am getting an error: Traceback (most recent call last): File "django_client.py", line 10, in <module> csrftoken = client.cookies['csrftoken'] File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/cookies.py", line 327, in __getitem__ return self._find_no_duplicates(name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/cookies.py", line 398, in _find_no_duplicates raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) KeyError: "name='csrftoken', domain=None, path=None" What am I doing wrong? -
Python: __str__method causes "must be str, not NoneType" error only for one of two identical fields
I am working on Django app, but one of my model is causing must be str, not NoneType error when trying to edit its field in admin. Stacktrace shows that the cause is my __str__ method, defined as: def __str__(self): return self.restaurant.name + " ==> Looks for " + self.container_tag + \ " with class: " + self.container_class or "[Not set]" + " , with id: " + self.container_id or "[Not set]" Here are the fields as defined in my model class: container_tag = models.CharField(max_length=15) container_class = models.CharField(max_length=25, null=True, blank=True) container_id = models.CharField(max_length=25, null=True, blank=True) As you can see, the last two are exactly the same. When I enter value into container_class (while ignoring container_id) and save, then everything works fine. But when I enter value into container_id and not container_class then I get the error above. As far as I know the or operator should do the job and just "ignore" the field if it is empty. For the sake of completeness, here is the line that triggers the error: " with class: " + self.container_class or "[Not set]" + " , with id: " + self.container_id or "[Not set]" -
Forward url arguments to view in Django
I am trying to forward projects/1 to the view, for purpose of getting the project based on the id. I have tried to change the regex, and the name. Urls related to the 'Project': urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^project/(?P<project_id>([0-9]+))$', views.project, name='project'), ] The view for the 'Project': def project(request, project_id=1): template = loader.get_template("project.html") context = { 'project': Project.objects.filter(project_id=project_id) } return HttpResponse(template.render(context, request))