Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dictionary update sequence element #0 has length 1; 2 is required in Django
I'm using Python 3.5.4 with Django 2.0.0 final 0. I'm trying create a Django blog web application. I received error after I had created Django view and template. Here's my error: Internal Server Error: /blog Traceback (most recent call last): File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/utils/deprecation.py", line 93, in __call__ response = self.process_request(request) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/middleware/common.py", line 60, in process_request if self.should_redirect_with_slash(request): File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/middleware/common.py", line 79, in should_redirect_with_slash is_valid_path('%s/' % request.path_info, urlconf) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/base.py", line 155, in is_valid_path resolve(path, urlconf) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/base.py", line 24, in resolve return get_resolver(urlconf).resolve(path) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 496, in resolve sub_match = pattern.resolve(new_path) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 496, in resolve sub_match = pattern.resolve(new_path) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 345, in resolve kwargs.update(self.default_args) ValueError: dictionary update sequence element #0 has length 1; 2 is required [01/Jan/2018 21:12:43] "GET /blog HTTP/1.1" 500 88570 Here's autisticstory/urls.py file: """autisticstory URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the … -
django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with no arguments not found
I have a fairly simple retrieve test: def test_user_retrieve(self): factory = APIRequestFactory() User.objects.create_superuser(username='test', password='Welcome2', email='test@test.com') user = User.objects.get(username='test') view = UserViewSet.as_view({'get': 'retrieve'}) url = reverse('core:user-detail') request = factory.get(url) force_authenticate(request, user=user) response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) It gives the following traceback: Traceback (most recent call last): File "D:\Projects\enterpass\api\core\tests.py", line 54, in test_user_retrieve url = reverse('core:user-detail') File "D:\Python36\lib\site-packages\django\urls\base.py", line 88, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "D:\Python36\lib\site-packages\django\urls\resolvers.py", line 632, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with no arguments not found. 2 pattern(s) tried: ['api/v1/core/users/(?P<pk>[^/.]+)\\.(?P<format>[a-z0-9]+)/?$', 'api/v1/core/users/(?P<pk>[^/.]+)/$'] If I hit the URL using postman there's no issue: http://localhost:8000/api/v1/core/users/1/ The view is being registered via a router like so: app_name = 'core' router.register(r'users', views.UserViewSet, base_name='user') here is the part of the view that's pertinent: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes_by_action = {'list': [CanListUser], 'create': [CanCreateUser], 'retrieve': [CanRetrieveUser], 'update': [CanUpdateUser], 'destroy': [CanDestroyUser]} def retrieve(self, request, pk=None, **kwargs): try: instance = self.get_object() self.check_object_permissions(self.request, instance) serializer = UserSerializer(instance, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) except User.DoesNotExist: return Response(status=status.HTTP_204_NO_CONTENT) Found the solution but I'd love someone to explain for me based on this working view: def test_user_retrieve(self): factory = APIRequestFactory() User.objects.create_superuser(username='test', password='Welcome2', email='test@test.com') user = User.objects.get(username='test') view = UserViewSet.as_view({'get': 'retrieve'}) url = … -
Wagtail allow users to edit page
Is there a way in wagtail to allow specific users to access the admin interface and only be able to edit / create certain pages? Browsing around the docs I don't see anything like this discussed. Example: I want to take advantage of streamfields to allow users to create / edit page with dynamic content / layouts. However, I don't want the users to be able to access the entire interface to where they could change other parts of the site just this one specific page for editing / creating. How would I go about this? Add them to a group with editing permissions? But, since this is the wagtail admin.... Doesn't that require tehse users to be an "admin"? -
Updating package on Anaconda environment
Is there a way to update only the django package on the python 3 environment to version 2.0? My base version of python is 2.7.14. Anaconda 4.4.4. I created a new environment for python 3.6.3. I installed django 1.11.8 (as this is the latest version available for python 2.7) on both environments but I need django 2.0 on my python 3 environment. When I try: conda install django=2.0 PackagesNotFoundError: The following packages are not available from current channels: django=2.0 Current channels: https://repo.continuum.io/pkgs/main/win-64 https://repo.continuum.io/pkgs/main/noarch ... with a few more similar links Am I missing something? Is this even possible to do within an environment in the python 2 Anaconda? -
Django: How can I create a dynamic form that changes on user click?
I'm making a workout calendar website where a user can add workouts with varying amounts of lift, sets and reps, etc. Thus, I need a form that adds a field when a user clicks a button. I've made a template and some javascript to describe what it is I want to achieve exactly: url: url(r'^add/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/$', views.add_workout, name = 'add_workout') template: {% block hidden %} {% include "workoutcal/liftrow.html" %} {# To be used by Javascript #} {% include "workoutcal/cardiorow.html" %} {% endblock %} <form action="{% url 'add_workout' date.year date.month date.day %}" method="post"> <div class="row"> <div class="col-xs-2"> <p id="date">{{ date.year }}-{{ date.month }}-{{ date.day }}</p> <input type="hidden" name="date" value="{{ date }}"> </div> </div> <h2 class="col-xs-12">Lifts</h2> <div id="liftrows"> {% for i in range %} {% include "workoutcal/liftrow.html" %} {% endblock %} </div> <div class="row"> <div class="col-xs-0"></div> <label class="col-xs-2"><button type="button" id="addliftbutton">One more lift</button></label> </div> <h2 class="col-xs-12">Cardio</h2> <div id="cardiorows"> {% include "workoutcal/cardiorow.html" %} </div> <div class="row"> <label class="col-xs-2"><button type="button" id="addcardiobutton">One more cardio</button></label> </div> <div class="row"> <div class="col-xs-10"></div> <label class="col-xs-2"><input type="submit" id="submitbutton" value="Save Workout"></label> </div> </form> javascript: //Adding onclick to buttons document.getElementById('addliftbutton').onclick = addLiftRow; document.getElementById('addcardiobutton').onclick = addCardioRow; for (var i=0; i<setsBoxes.length; i++){ setsBox = setsBoxes[i]; setsBox.onchange = insertRepFields; } function addLiftRow(){ var liftRowElements = document.getElementById('liftrows'); var … -
How to solve inefficient code?
The following are my two serialization classes. #1 class CoverLetterSearchSerializer(serializers.ModelSerializer): application_type = serializers.SerializerMethodField() quarter_type = serializers.SerializerMethodField() class Meta: model = models.Coverletter fields = ( 'id', 'company', 'application_year', 'quarter_type', 'application_type', ) def get_application_type(self, obj): return obj.get_application_type_display() def get_quarter_type(self, obj): return obj.get_quarter_type_display() #2 class CoverletterListSerializer(serializers.ModelSerializer): application_type = serializers.SerializerMethodField() quarter_type = serializers.SerializerMethodField() class Meta: model = models.Coverletter fields = ( 'id', 'company', 'application_year', 'application_type', 'application_deadline', 'quarter_type', 'application_flag', 'pass_flag', ) I made two serializers for the data to show in VIEW. However, if I change the field of the model class used in the serializer, should I change the fields of this serializer class all the time? Please tell me about this problem. -
Removing Django allauth change email page
I'd like to remove the Django allauth change email page and all of its functionalities that come with it. I know I can make a template for allauth and use my custom pages and deleting that page and removing all the functionalities associated with it manually, but I was wondering if there was a better way to solve this. I am afraid once I start removing the change email page functionalities something will start breaking. Is there a way to remove this page without breaking anything? -
Bootstrap "default" navbar example inconsistent
While playing with Django, I've added a basic home-page example from the Bootstrap navbar example. My Django app simply redirects any link to the home page with the following template: {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> {# <link rel="icon" href="../../favicon.ico">#} <title>Navbar Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'css/navbar.css' %}" rel="stylesheet"> <script src="{% static "js/jquery.js" %}"></script> <script>window.jQuery || document.write('<script src="{% static 'js/jquery.js' %}"><\/script>')</script> <script src="{% static 'js/bootstrap.js' %}"></script> </head> {% load bootstrap3 %} {% bootstrap_javascript %} {% bootstrap_css %} <body> <div class="container"> <!-- Static navbar --> <nav class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Project name</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> … -
Do I need to create forms.py for my forms in Django?
I'm about to create a form in my website made in Django with elements that have complex input types from different plugins (like calendar plugins). Also, I'll be using a Validator plugin which validates the input before submission. My question is do I need to create forms.py and like model the form or can I just create the form manually? The former seems like a very hassle process. Which one is more efficient and recommended? -
Django rest nested serializer fails
My model relationships are: A 'Reader' will have a single 'Wishlist' and a 'Wishlist' will contain many 'Book's. I want to create an empty Wishlist automatically during Reader object instance creation. My Models: class Wishlist(models.Model): wishlist_id = models.AutoField(primary_key=True) class Reader(models.Model): user = models.OneToOneField(User) phone = models.CharField(max_length=30) address = models.CharField(max_length=80) dob = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) # A library has many readers which_library = models.ForeignKey('Library', related_name='readers', on_delete=models.CASCADE) wishlist = models.OneToOneField(Wishlist, null=True, blank=True) class Book(models.Model): book_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) which_wishlist = models.ForeignKey('Wishlist', related_name='my_wishlist', on_delete=models.CASCADE, null=True, blank=True) And serializer: class ReaderSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') email = serializers.CharField(source='user.email') password = serializers.CharField(source='user.password') class Meta: model = Reader #fields = '__all__' #depth = 1 fields = ('id', 'username', 'email', 'password', 'phone', 'address', 'dob', 'which_library', 'wishlist') def update(self, instance, validated_data): instance.user.email = validated_data.get('user.email', instance.user.email) instance.user.password = validated_data.get('user.password', instance.user.password) instance.phone = validated_data.get('phone', instance.phone) instance.address = validated_data.get('address', instance.address) instance.dob = validated_data.get('dob', instance.dob) instance.which_library = validated_data.get('which_library', instance.which_library) instance.wishlist = validated_data.get('wishlist', instance.wishlist) instance.save() return instance def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) user.set_password(user_data['password']) user.save() wishlist_data = validated_data.pop('wishlist') reader = Reader.objects.create(**validated_data) Wishlist.objects.create(reader=reader, **wishlist_data) return reader My view that handles the creation: @api_view(['GET', 'POST']) def reader(request, library_id): """ List all readers in a specific library, or create a new … -
How to store user customizable queries?
I would like to allow a bunch of my users to run arbitrary and periodical queries. So far, I've managed to create this model: class BasicQuery(models.Model): id = models.AutoField(primary_key=True) target_entity = models.CharField(max_length=255) target_field = models.CharField(max_length=255) operator = models.CharField(max_length=10) compare_value = models.CharField(max_length=10) active = models.BooleanField() run_every = models.ForeignKey(QueryFrequency) and the function which executes it : def rule_runner(rule): target_entity = rule.target_entity fieldname = rule.target_field val = rule.compare_value if rule.operator: cmd = '{}.objects.filter({}__{}={})'.format(rule.target_entity, rule.target_field, rule.operator, rule.compare_value) else: cmd = '{}.objects.filter({}={})'.format(rule.target_entity, rule.target_field, rule.compare_value) return eval(cmd) But because of the eval(cmd), the code is way too dangerous to go to production, no matter how many tests I'll do before calling this function I'll never feel safe about it. Any suggestions on how I can achieve this purpose in a clean way? -
Count occurrences of values on a single column grouped by week
I'm trying to accomplish this using Django 2.0 ORM, but if you can solve this with a raw SQL query that would be very helpful too. Say for example I have a table with the column "destination", which will always be the name of a city, such as "Los Angeles", "New York", "San Francisco", or "Seattle" (but we don't know in advance how many different cities there could be). I need a SQL query (or Django ORM code) that will get me a count of all the cities for a specified date range, grouped by the record's week (based on created_at timestamp, with weeks starting on Mondays). Here is an example of the output, structured as JSON: { "2017-06-05-2017-06-11": { "Los Angeles": 100, "New York": 50, "Copenhagen": 20 }, "2017-06-12-2017-06-18": { "Los Angeles": 10, "Toronto": 23, "Las Vegas": 21, "Carson City": 8, "Raleigh": 1 }, "2017-06-19-2017-06-25": { "Toronto": 24, "Tokyo": 75, "Kansas City": 123, "Salem": 84, "Bismarck": 22, "Boise": 77, "Las Vegas": 123 } } Note that the results can vary in size, the date ranges all start on a Monday and end on a Sunday (both inclusive), and the city names are variable and unknown. I know there are … -
Django: How to test view with two forms in it
I want to write tests to make sure that if: If product does not exist, if save a new product as well as the item If product does exist, it was just feed in the existing product into the item If there is a problem force the user to fix it. Please note that item has as product foreign key. My addItem function might be incorrect to do meet the above 'targets'. view def addItem(request, **kwargs): template_name = 'app/add.html' product_form = ProductForm(request.POST or None) item_form = ItemForm(request.POST or None) forms = [product_form, item_form] if all([form.is_valid() for form in forms]): instance_product = product_form.save() instance_item = item_form.save(commit=False) instance_item.product = instance_product instance_item.save() return #redirect else: #return blank forms return render(request, template_name, {'forms':forms} html <form method="POST"> {% csrf_token %} {% for form in forms %} {{form.as_p}} {% endform %} <input type='submit'/> </form> Thank you for your time. -
cx_oracle 6 for Oracle 12C version error
I am trying to use oracle 12c as database for my application using Django framework. But I am struck in version related issue Following are the version of library used: Python 3.6 cx_Oracle 6 Oracle instant client 12.2 Oracle 12 C database on server Oracle 10 g on local machine where the cx_oracle is installed OS is windows 7 Following are the steps which I did to install cx_oracle 1. pip install cx_Oracle 2. Download Oracle instant client 12.2 zip file for windows 3. Extracted the zip file 3. Added the above unzipped folder to user PATH variable From CMD I try to execute python import cx_Oracle con = cx_Oracle.connect(uname, pwd, server_ip:port/name) I am getting the error: cx_oracle.databaseerror: dpi-1050: oracle client library must be at version 11.2 or higher Is cx_Oracle having any conflict with oracle 10 g installed at local machine I cannot upgrade the local oracle 10g db because(no rights given) How do I resolved the above issue. How can I make sure cx_Oracle uses the correct Oracle instant client( i.e, 12.2) to connect to server db. -
Django: Use text box data and write that text a file
I am super new to Django and web development. Right now my objective is to create a google like interface and take the text from search box and write it to a file (in other words just want to access text data in the search box). I have created a search page like below search.html {% extends "header.html" %} {% block content %} <div style="display: flex; justify-content: center;"> <img src="/static/images/logo.jpg" class="responsive-img" style='max-height:300px;' alt="face" > </div> <form method="get" action=""> {% csrf_token %} <div style="display: flex; justify-content: center;"> <input type="text" name="query" placeholder="Search here..." required size="70" > <button type="submit">Go!</button> </div> <button type="submit">Search</button> </form> {% endblock %} views.py from django.shortcuts import render def index(request): return render(request, 'search.html') urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index') ] Please give me a hint/example of how to go forward from here ? Thanks. -
Why when I add @api_view to my view that I get a 403
I was following along with the Django REST Framework tutorial, http://www.django-rest-framework.org/tutorial/2-requests-and-responses/. However when I add the @api_view decorator I get a 403 when I do a GET on the view. GET /attendance/api/youths/ HTTP 403 Forbidden Allow: OPTIONS, GET Content-Type: application/json Vary: Accept { "detail": "Invalid username/password." } This is my code. @api_view(['GET']) def youths_json(request, format=None): youths = Youth.objects.filter(attending=True) serializer = YouthSerializer(youths, many=True) return Response(serializer.data) When I add the AllowAny permission it still doesn't work. @permission_classes((AllowAny, )) Any ideas? I would like to get this to work and I would really like to use the ListAPIView. -
AuthFailed at /oauth/complete/github/ login social django
Please help me for this problem. AuthFailed at /oauth/complete/github/ Authentication failed: The redirect_uri MUST match the registered callback URL for this application. Request Method: GET Request URL: http://localhost:8000/oauth/complete/github/?error=redirect_uri_mismatch&error_description=The+redirect_uri+MUST+match+the+registered+callback+URL+for+this+application.&error_uri=https%3A%2F%2Fdeveloper.github.com%2Fv3%2Foauth%2F%23redirect-uri-mismatch&state=WoKzByClduyC14Q1sjY0PeB8ZFIdf2I9 Django Version: 1.11 Exception Type: AuthFailed Exception Value: -
django redirect after form submission not working
new to django so this one probably has a very simple answer but i cannot for the life of me find the specific solution to this. I am simply trying to redirect to a new URL after a form submission with a FileField. I can navigate to the URL separately and it works fine. The file uploads correctly so I know it is validated correctly. But the redirect returns the following error: Reverse for 'success' not found. 'success' is not a valid view function or pattern name. I have tried a bunch of different naming conventions, but none has worked. It looks to me like I have setup the URL and passed it correctly. Would really appreciate some help with this. The simplest problems are the most frustrating! Here are the views. from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from .forms import InvestmentReportForm def upload(request): if request.method == 'POST': form = InvestmentReportForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('success') else: form = InvestmentReportForm() return render(request, 'app/upload.html', {'form': form}) def success(request): return HttpResponse("File successfully uploaded") And my urls.py: urlpatterns = [ path('', views.index, name='index'), path('upload/', views.upload, name='upload'), path('success/', views.success, name='success'), path('performance/', views.performance, name='performance'), ] -
django error "The value of 'fieldsets[0][1]' must contain the key 'fields'." when trying link model to admin panel
i am trying to hook up django admin panel to a model using following code in admin.py under my django app after which i got error admin.E011, appreciate your help please to clear this error "SystemCheckError: System check identified some issues: ERRORS: : (admin.E011) The value of 'fieldsets[0][1]' must contain the key 'fields'. : (admin.E011) The value of 'fieldsets[1][1]' must contain the key 'fields'." my code: from django.contrib import admin from .models import Entry Register your models here. @admin.register(Entry) class EntryAdmin(admin.ModelAdmin): fieldsets = [ ('Regular Expressions', {'feilds' : ['pattern', 'test_string', 'user']}), ('Other Information', {'feilds' : ['user', 'date_added']}), ] list_display = ['pattern', 'test_string', 'user'] list_filter = ['user'] search_fields = ['test_string'] -
How to find ids that requires action based on 3 tables?
I'm working on my first django project which is a sport betting app. My models are: class Game(models.Model): home_team = models.CharField(max_length=100) away_team = models.CharField(max_length=100) class GameResult(models.Model): gameid = models.ForeignKey(Game) result = models.IntegerField(default=None) class GameBet(models.Model): gameid = models.ForeignKey(Game) bet = models.IntegerField(default=None) userid = models.ForeignKey(User) I'm trying to create a view that shows only pending games, which means they have no result (easy part) and no bet placed yet. Here the problem is - in my database I have only bets that was made, like: gameid| userid | userbet 23 | 10 | 2 23 | 11 | 1 23 | 12 | 0 and I'm looking for somethig like this: gameid| userid | userbet 24 | 10 | 1 24 | 11 | 0 When userid #12 hasn't made his bet yet - so it is missing in the database and game should be in his pending games list. My current logic is that I know ids of all games, I know ids of games with result and I know ids of games that I placed my bet. How do I connect these dots and find out games that I still have to bet? all_games = Game.objects.get() games_with_result = GameResult.objects.filter(result__isnull=False) games_with_players_bet … -
How to pass a value from model to view in django?
How to pass codeval variable from models.py to views.py: in models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save import random from django.core.mail import send_mail class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') mobile = models.IntegerField(default=0) code = models.IntegerField(default=0) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) codeval = random.randint(111111,999999) user_profile.code = codeval user_profile.save() receiver = User.objects.get(id=user_profile.user_id).email send_mail(' Confirm your account on Abolombon', 'Thanks for signing up with Abolombon! Your Abolombon verification code is:\n %s\n\n Thank you\nAbolombon.com'%(codeval), 'testpurpose2040@gmail.com', [receiver]) post_save.connect(create_profile, sender=User) in views.py def verification(request, args=codeval): return render(request,'website/verification.html',{'args':args}) I am making an e-commerce site in django where I need user registration option. For this purpose I am using django's build in user registration form. But I need to store some additional info about user like contact number, city etc. I also want to verify user sending a 6 digit code to their corresponding email address. But in django's build in form their is no field to store verification code. So I have created UserProfile model to serve this purpose. And have created code field to store 6 digit random number. I want to store this random number into … -
Django rest custom model creation fails
I have a custom user model as following: class Librarian(models.Model): user = models.OneToOneField(User) phone = models.CharField(max_length=30, blank=True) # A library has many librarians which_library = models.ForeignKey('Library', related_name='librarians', on_delete=models.CASCADE) I have written serializer as following: class LibrarianSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') email = serializers.CharField(source='user.email') password = serializers.CharField(source='user.password') class Meta: model = Librarian #fields = '__all__' fields = ('id', 'username', 'email', 'password', 'phone', 'which_library') def update(self, instance, validated_data): instance.user.email = validated_data.get('user.email', instance.user.email) instance.user.password = validated_data.get('user.password', instance.user.password) instance.phone = validated_data.get('phone', instance.phone) instance.which_library = validated_data.get('which_library', instance.which_library) instance.save() return instance def create(self, validated_data): print('ok') return Librarian.objects.create(**validated_data) It's view: @api_view(['POST']) def librarian(request, library_id): """ Create a new librarian for a specific library """ if request.method == 'POST': print('View') serializer = LibrarianSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) And I am making a POST request to the corresponding URL with following JSON data: { "username": "sample", "email": "sample@gmail.com", "password": "12345678", "phone": "12345", "which_library": "1" } It throws me Cannot assign "{u'username': u'sample', u'password': u'12345678', u'email': u'sample@gmail.com'}": "Librarian.user" must be a "User" instance error. My goal is to create a Librarian (a user must be automatically created), that's why I am sending username, password, email fields as well. What am I doing wrong? -
Django - call def on button click?
SO I have this simple button in my template: <form method="get"> <input type="text" value="8" name="mytextbox" size="1" /> <input type="submit" class="btn" value="Click" name="print_btn"> </form> In my views.py i have this function: def print_from_button(request): if(request.GET.get('print_btn')): print( int(request.GET.get('mytextbox')) ) print('Button clicked') this prints to console: "GET /myview/mytextbox=8&print_btn=Click HTTP 1.1" 200 I also want 'Button clicked' to be printed, i.e. I want the function executed, not just one statement in the function. -
NoReverseMatch for url in Django template
I'm getting this error: NoReverseMatch at /workoutcal/add/2017/11/1/ Reverse for 'add_workout' not found. 'add_workout' is not a valid view function or pattern name. Because of this template code: <form action="{% url 'add_workout' date.year date.month date.day %}" method="post"> From the urls.py: url(r'^add/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/$', views.AddWorkoutView.as_view(), name = 'add_workout'), I've followed the docs. Don't know why my URL name isn't found. Any ideas? -
Query related to mastodon oauth service
I have one website. I used mastodon oauth service for login to my website and it works fine. Now I want to migrate users of my website to mastodon server, can anybody tell me how to do it?