Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django TypeError: authenticate() takes exactly 0 arguments (3 given)
Django version 1.10.7 I'm getting TypeError: authenticate() takes exactly 0 arguments (3 given) Importing the authenticate() like this: from django.contrib.auth import authenticate, login Calling authenticate() like this : authenticate(request, username=request.POST['username'] ,password=request.POST['password']) -
How to do unit testing of REST API's of a Python Django project
I'm new to Python and Django. Please help me with info/examples of unit testing the REST API's of a django project. Can we do that using Pytest? -
Web programming: Python PowerShell errors
I'm at the beginning of learning to code in Python (and second or third time using PowerShell but first time it appears to me so I wish help). PS E:\website> python manage.py shell python : Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 At line:1 char:1 + python manage.py shell + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (Python 3.6.2 (v...ntel)] on win32:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) -
404 error for popup modal form in django
I am getting 404 error for a popup form, I am trying to open on clicking a text link. accounts/urls.py url("_/user-popup/(?P<key>\w+)/$", views.user_popup_form, name="user_popup_form"), url("_/user-popup/(?P<key>\w+)/(?P<pk>[^/]+)/$", views.user_popup_form, name="user_popup_form"), accounts/views.py-- POPUP_FORMS = { "profile": { "form": forms.UserProfileForm, "templates": { ".nav_user_name": "user/nav_user_name.html", ".profile_info": "user/profile_info.html", ".about_text": "user/about_text.html", } } # etc. } def user_popup_form(request, key, pk=None): """ Handle any form with a "user" field pointing back to the logged in user. Otherwise return a HttpResponseForbidden response. """ if (not request.user.is_authenticated) or (not key in POPUP_FORMS): raise HttpResponseForbidden() content = {} instance = POPUP_FORMS[key]['form']._meta.model.objects.filter(user=request.user) if pk: instance = instance.filter(pk=Hasher.decode(pk)[0]) else: if not isinstance(POPUP_FORMS[key]['form']._meta.model.user.field, OneToOneField): instance = None instance = instance[0] if instance else None if request.POST or request.FILES: form = POPUP_FORMS[key]['form'](request.POST, request.FILES, instance=instance, initial={"user": request.user}) success = form.is_valid() if success: instance = form.save(commit=False) instance.user = request.user try: instance.save() except IntegrityError: success = False form.errors['__all__'] = ["Form data not unique - have you already added one of these?"] except Exception as e: success = False form.errors['__all__'] = [e] else: models.User.objects.update() request.user.refresh_from_db() POPUP_FORMS[key]['form']._meta.model.objects.update() for name, template in POPUP_FORMS[key]['templates'].items(): content[name] = render_to_string(template, {"profile": request.user.profile}, request) else: form = POPUP_FORMS[key]['form'](instance=instance, initial={"user": request.user}) success = False return JsonResponse({ "form": Template("{% load crispy_forms_tags %}{% crispy form %}").render(Context({"request": request, "form": form})), "title": capfirst(key), … -
Converting Tuple inside of an array into a dictionary in Python
I have been trying to solve this problem but I cannot get it right :( I am querying mySQL database in Django, and my results comes back as a tuple inside of an array. Please see dummy data below; query_results = [ (500, datetime.date(2017, 1, 1)), (302, datetime.date(2017, 1, 2)), (550, datetime.date(2017, 1, 3)), (180, datetime.date(2017, 1, 4)), (645, datetime.date(2017, 1, 5)), (465, datetime.date(2017, 1,6)) ] 500, 302, 550 etc... are my records. The next element are the date of those records. I would like to append them into a dictionary using a loop, but I always get an error of: TypeError: list indices must be integers, not tuple. Can anyone please give me some advise on how to append these into something like this: myDict = { "record": "", "date": "" } All help is greatly appreciated! -
How to custom Ckeditor image uploader
So guys i'am using Ckeditor in my django project but i notice on the image/file uploader modal some useless tabs and fields the question is how can i remove them for the user experience and thanks in advance -
Django m2m signal, retrieving which element was added to the m2m field
This is my m2m signal def new_pet_added_to_hooman(instance, **kwrags): for pet in instance.pets.all(): pet.become_jelly() And I'm connecting it by using signals.m2m_changed.connect This is triggered by hooman.add(pet). But this will also make my "new" pet jelly. Ideally I want to set all pets EXCEPT for the recently added one to jelly, and then perform some other stuff to the newly added pet def new_pet_added_to_hooman(instance, **kwrags): for pet in instance.pets.exclude(id=new_pet): pet.become_jelly() new_pet.pamper() Something like this. Is it possible to retrieve which entry triggered the signal? i.e. Which new pet -
django - static css file 404 error not loading
I'm trying to figure out the static files part of building a django website. My static css file "base.css" is not loading in any way by my website and I can't figure out why. settings.py STATIC_URL = '/static/' STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'), ) template base.html {% load static %} ... <link rel='stylesheet' type='text/css' href='{% static "css/base.css" %}' /> ... I have a 'static' folder on the same level as my django app, with base.css as a file there. cms --blog --cms --static ----css ------base.css --db.sqlite3 --manage.py When I use the inspect tool in chrome, on the console tab it says that the file is not found (404 error). What am I missing here? Why is it not loading? -
Google App Engine (GAE) Improperly Configured Database
I have a working Django project that will deploy using Heroku. I am having trouble getting the app to deploy on GAE. When I run it locally, I get an error referring to an Improperly Configured database backend. Any help would be appreciated. Error: ... raise ImproperlyConfigured(error_msg) ImproperlyConfigured: 'postgresql' isn't an available database backend. Try using django.db.backends.XXX, where XXX is one of: 'dummy', 'mysql', 'oracle', 'postgresql_psycopg2', 'sqlite3' <br> Error was: No module named postgresql.base ... app.yaml runtime: python27 api_version: 1 threadsafe: true handlers: - url: /.* script: main.app libraries: - name: django version: "latest" beta_settings: cloud_sql_instances: <cloudsql-connection-string> settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'xxx', 'USER': '*****', 'PASSWORD': '******', 'HOST': 'xx.xx.xx.xx', 'PORT': '5432', } } If I change the Engine to 'ENGINE': 'django.db.backends.postgresql_psycopg2' I get the error: ImportError: No module named psycopg2.extensions pip freeze returns: Django==1.11.4 psycopg2==2.7.3.1 pytz==2017.2 -
Remove hardcoded values from settings
Code Snippet LIFECYCLE_TYPES = { 'viaf:personal': "986a7cc9-c0c1-4720-b344-853f08c136ab", # E21 Person 'viaf:corporate': "3fc436d0-26e7-472c-94de-0b712b66b3f3", # E40 Legal Body 'viaf:geographic': "dfc95f97-f128-42ae-b54c-ee40333eae8c", # E53 Place } Problem Currently these types are hardcoded into the settings.py file in my django project. I want to keep these types configurable while not having them hardcoded into my settings file. They are used only for development purposes and do need to be changed frequently. I do not want to make them available to regular users of my site. Any ideas on how I could do this? I was thinking possibly some sort of CLI tool. -
block UI or MSG doesn't work in Safari
I have a Django project in which the input is a text and two dates. When I click on "See Metrics", validate() fires up which validates if all fields are filled. If the validation returns "true then I want to give a "Please wait" message to my users where Python script finds the results. I used MSG plugin (also the blockUI plugin previously). The functionality works fine in Chrome and Firefox but I am not able to get the desired results in safari. When I press "See Metrics" I don't see any message but after I press back button(of browser) then I see the message on the index page. Please help. Here is the code for my index page <meta charset="UTF-8" /> <title>ARM Datastream Usage Metrics Tool</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {% load static %} <!-- All the style sheets --> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/font-awesome.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/jquery-ui.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/metricsToolcss.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/jquery.msg.css' %}" /> <!-- All the JS Libraries --> <script type="text/javascript" src="{% static 'js/jquery.min.js' %}"></script> <script type = "text/javascript" src = … -
How to assert django uses certain template in pytest
In the unittest style, I can test that a page uses a particular template by calling assertTemplateUsed. This is useful, for example, when Django inserts values through a template, so that I can't just test string equality. How should I write the equivalent statement in pytest? I've been looking in pytest-django but don't see how to do it. -
How to pass JWT token through header in react native to django rest api?
enter code hereI am passing token(already i known from console) in header as in below code and want data from that localhost after that user get authenticated but on my android emulator it showing error Cannot convert undefined or null to object Login.js componentDidMount() { return fetch('http://10.42.0.1:8000/stocks/', { method: "GET", headers: { 'Authorization': `Bearer ${"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNhbSIsInVzZXJfaWQiOjYxLCJlbWFpbCI6IiIsImV4cCI6MTUwMzk0ODYyMH0.l4VLMLXcSZ7nOmKmjblLKFr0lTSpgYeFks_JeYiO7cU"}` } }) ... } In views.py class Stocks(APIView): permissions_classes = [IsAuthenticated] authentication_classes= (TokenAuthentication,) def get(self,request): stocks=stock.objects.all() serailizer=serial(stocks,many=True) return Response(serailizer.data) here the token is not reaching at the server and hence permission is not granted. we are using Django rest jwt token. Thank You -
User.objects.create() does nothing. (Django)
I have a view that should run User.objects.create() for the user registration. User.objects.create(name="request.POST['name']", username="request.POST['username']", password="request.POST['password']") It obviously passes the conditionals into this code because it runs the redirect I put after it. But When testing the registration, it just doesn't create a new entry in the database. What's wrong with it? -
django multi-tenancy and wildcard subdomains
I want to offer client.domain.com for every client on the site. In practice, client.domain.com is equivalent to www.domain.com/client/ (which I know how to handle in urls but isn't what I want). Can I use django-subdomains to allow this sort of wildcarding without defining SUBDOMAIN_URLCONFS since I don't want to try and enumerate for all clients. I'm currently using Apache. I don't want to create a new virtual host for each client as well. Is there a generic way to make client.mydomain.com work? Appreciate all pointers to executing #1 and #2. Thanks. -
How to reuse a Django template?
Currently, I have almost two exact same templates and they use the same Django form, but there is only 1 parameter that changes in these two forms which is the action method, that is, Django form class DropDownMenu(forms.Form): week = forms.ChoiceField(choices=[(x,x) for x in range(1,53)] year = forms.ChoiceField(choices=[(x,x) for x in range(2015,2030)] template 1 <form id="search_dates" method="POST" action="/tickets_per_day/"> <div class="row"> <div style="display:inline-block"> <h6>Select year</h6> <select name="select_year"> <option value={{form.year}}></option> </select> </div> <button type="submit">Search</button> </div> </form> template 2 <form id="search_dates" method="POST" action="/quantitative_analysis/"> <div class="row"> <div style="display:inline-block"> <h6>Select year</h6> <select name="select_year"> <option value={{form.year}}></option> </select> </div> <button type="submit">Search</button> </div> </form> The only thing that varies is the action method, so I would like to know if it is possible to re-use one template that varies only in the action method. If it is possible, can you help me with the code? I checked this question django - how to reuse a template for nearly identical models? but I am not using any model here with my templates. -
django templates Unclosed tag on line 10: 'if'. Looking for one of: endif
I am getting the following error message in my django template: Unclosed tag on line 10: 'if'. Looking for one of: endif. I use endif on line 20 to close the if category. if pages is closed on line 16. Not sure if it is a syntax issue? <!DOCTYPE html> <html> <head> <title>Rango</title> </head> <body> <div> {% if category %} {{ category.name }} <ul> {% if pages %} {% for page in pages %} <li> {{ page.title }} </li> {% endfor %} </ul> {% else %} <strong>No Pages</strong> {% endif %} {% else %} <strong>The specified category does not exist!</strong> <% endif %} </div> </body> -
Python, Django and Pycharm - function resolution order - exist?
I'm using Django with Pycharm. I'm trying to find a way in Pycharm to have a function resolution order similar to class mro For example in Django a method like is_valid calls full_clean, clean_field, to python etc, or form save, then model_save. What I want to see is starting from a method/function to see what happens what other function is called that the next one until the end, like an mro. I know there is ccbv.co.uk and Django/Python documentation but I want to investigate something fast, plus the documentation is some cases doesn't cover everything in detail. -
django server sending stale js file
In dev mode django server seems to be sending a stale version of a js file, which has an outdated url used in an ajax request. After hitting the relevant url and using chrome dev tools I can see the outdated file being sent by django. (aside: when I use my IDE's js debugger it uses the updated file correctly) The template is: % extends "layout/focused_form_layout.html" %} {% load staticfiles %} {% block inner %} <h2 class="title text-center">Sign up now</h2> <p class="intro text-center">Enter your cursadfasdfsadfrent energy supply details</p> <div class="row"> {% include "components/form.html" % </div> {% endblock %} {% block inner_js %} <script defer type="text/javascript" src="{% static 'js/supplier.js' %}"> {% endblock inner_js %} And the js file is: $(document).ready(function () { $('#id_supplier').change(function () { var supplier = $(this).val() console.log(supplier) $.ajax({ url: '/users/current_supply_services/', data: { 'supplier': supplier }, dataType: 'json', success: function (data) { console.log(data) options = data.tariff_choices.map(function(subarray) { return '<option value="' + subarray[0] + '">' + subarray[1] + '</option>' }) $('#id_service').html(options) } }) }) }) -
django - Get the exact GET url that was used to call a django view (including params)
I have a view which accepts GET params (accessible via the request.GET and that are present in the uri) Inside the view I want to get the exact uri that was used to call that view maintaining order Example: If a call was made to http://best.site.ever/?this=that&that=this I want to be able to fetch it in the view def best_view_ever(request): calling_uri = get_calling_uri(request) calling_uri # this should be http://best.site.ever/?this=that&that=this Is this achievable in any way? -
Writable nested Django serializer with string instead of dict
The Django Rest Framework docs have an example for writable nested serializers, see http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers. I am interested in the case where the related Track model has only one field (title) besides the foreign key field. I thus modified it to read: models.py class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) title = models.CharField(max_length=100) class Meta: unique_together = ('album', 'title') serializers.py class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('title',) class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') def create(self, validated_data): tracks_data = validated_data.pop('tracks') album = Album.objects.create(**validated_data) for track_data in tracks_data: Track.objects.create(album=album, **track_data) return album now run: >>> data = { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ {'title': 'Public Service Announcement'}, {'title': 'What More Can I Say'}, {'title': 'Encore'}, ], } >>> serializer = AlbumSerializer(data=data) >>> serializer.is_valid() True >>> serializer.save() <Album: Album object> This works all very well. However, I need the tracks in the serialized data to be structured as a list of track title strings, instead of a list of dicts {'title': title}, like this: >>> data = { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ 'Public Service Announcement', … -
make a change to date fields automatically in django
i have 2 date fields and i want to update the date automatically you will understand more when u read my codes. the codes won't work untill i update the updated field by myself how can i make it update itself (updated fields) automatically STATUS_CHOICES = ( ('P', 'Paid'), ('U', 'UNPAID'), ) status = models.CharField( max_length=1, choices=STATUS_CHOICES) updated = models.DateTimeField(default=datetime.now() ) expiry = models.DateTimeField(default=datetime.now() + timedelta(days=30) ) def save(self): if(self.expiry >= self.updated): self.status = default = "P" else: self.status = default = "U" self.expiry = default=self.updated+timedelta(days=1) super(Users, self).save() -
Closing bokeh server
I'm working with multiple bokeh servers and i want to close a bokeh server when a session on this server closes (preferably the last session on this server). The server is opened via a subprocess (bokehServercreation.py): cmd5101 = subprocess.Popen('bokeh serve results --show --args csvPath', shell=False, encoding='utf8') In the same .py file this works to close the server: os.kill(cmd5101.pid, signal.SIGTERM) But when adding this via the bokeh Lifecycle Hooks (in server_lifecycle.py)nothing happens, the server lives on. I'm not sure on how to pass the server pid correctly to server_lifecycle.py, or if there is another way for closing the server. def on_session_destroyed(session_context): os.kill(cmd5101.pid, signal.SIGTERM) pass My folder structure: bokehServerCreation.py results ( with main.py and server_lifecycle.py) -
Override the save() method in Django ModelForm to create or update
Intro: I want to override the save() method in my custom ModelForm to create a new row in a model or to update some data if it is exist. I have already found some solutions but it is implemented in the view function like this link Django form INSERTs when I want it to UPDATE, but I want to implement it in the form save() method. My Models: I have the default auth.User Model and my Author model as shown below, also I have another model called UserAuthor for the ManyToMany relationship between them as it is mandatory in my case for adding other fields like 'is_follow' and 'review' class Author(models.Model): name = models.CharField(max_length=50) class UserAuthor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) author = models.ForeignKey(Author, on_delete=models.CASCADE) is_follow = models.BooleanField(default=0) review = models.TextField(max_length=500, blank=True, null=True) My Form: class ReviewFollowAuthorForm(forms.ModelForm): class Meta: model = UserAuthor fields = ("is_follow", "review") def save(self, commit=True, user=None, author=None): user_author = super(ReviewFollowAuthorForm, self).save(commit=False) user_author.user = user user_author.author = author if commit: user_author.save() return user_author My View: class ReviewFollowAuthor(View): def post(self, request, **kwargs): user = request.user author = get_object_or_404(Author, id=kwargs['pk']) f = ReviewFollowAuthorForm(request.POST) if(f.is_valid()): f.save(user=user,userx=userx) return JsonResponse({'success':1}) else: return JsonResponse({'success':0}) In that case, it create a new row in the … -
ImprtError in Django
When I try to run my projects server i get this error: File "manage.py", line 14, in <module> import django File "C:/.../.../.../..../..." from django.utils.version import get_version ImportError: No module named utils.version Help, Please.