Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework, using multiple model queries
I am quite new in using the REST Framework and I did not find in the tutorial how to achieve what I am looking for; In my serialiser.py I have a class that is used to serialized MyUser models class MyUserSerializer(ModelSerializer): class Meta: model = MyUser fields = ( 'email', 'first_name', 'last_name' ) and in my view I am serializing a query that retrieve the user member in a team: class EmployeeChartData(APIView): #import pdb; pdb.set_trace() authentication_classes = [] permission_classes = [] serializer_class = MyUserSerializer def get_serializer_class(self): return self.serializer_class def get(self, request, format=None, *args, **kwargs): team_name_list2 = Project.objects.get(id=kwargs['pk1']).team_id.members.all() serializer=self.serializer_class team_name_data = serializer(team_name_list2, many=True) team_name_data = team_name_data.data data = { "team_name_list2":team_name_data, } Which give me an output for example: "team_name_list2": [ { "email": "johndoe@gmail.com", "first_name": "John", "last_name": "Doe" }, My question is how can I add to that dict custom data and data from other models that are linked to MyUser Model. For example I have a Team Model class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) members = models.ManyToManyField(MyUser, related_name="members") How can I add all the team that the specific user is linked to ? Thx you very much -
csrf token is missing or incorrect
followed a lot of the stuff recommended on StackOverflow. Also I tried to put {% csrf_token %} in the html in various places but none seemed to work. Any suggestions? Here is my django templates input button <input id=saveWaypoints type=button value='Save your Location' disabled=disabled> Which calls this javascript $('#saveWaypoints').click(function () { var waypointStrings = []; for (id in waypointByID) { waypoint = waypointByID[id]; waypointStrings.push(id + ' ' + waypoint.lng + ' ' + waypoint.lat); }; $.post("{% url 'waypoints-save' %}", { csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), waypointsPayload: waypointStrings.join('\n') }, function (data) { if (data.isOk) { $('#saveWaypoints').attr('disabled', 'disabled'); } else { alert(data.message); } }); }); My complete javascript code is <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Maps | {% block title %}{% endblock %}</title> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <script src="http://maps.google.com/maps/api/js?sensor=false"></script> <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script> <script> var map, marker, waypointByID = {}; var currentObject; var map; var geocoder; function initialize() { map = new google.maps.Map(document.getElementById('map'), { zoom: 5, center: new google.maps.LatLng(41.879535, -87.624333), mapTypeId: google.maps.MapTypeId.ROADMAP }); geocoder = new google.maps.Geocoder(); } $(function () { }); {% for waypoint in waypoints %} waypointByID[{{waypoint.id}}] = { name: "{{waypoint.name}}", lat: {{waypoint.geometry.y}}, lng: {{waypoint.geometry.x}} }; {% endfor %} var currentObject; $(document).ready(function () { function activateWaypoints() { // Add … -
Django get_or_create with many_to_many field
I'm making a Populate Script to transfer data from a Mysql Database to a Sqlite Database. I did some research, it came out with that what I have should work... NOT^^ I just want to add the categories in the PortalTechnology ManyToManyField This are the structures of my models... # Category model class Category(models.Model): name = models.CharField(max_length=25) description = models.CharField(max_length=255, blank=True, null=True) parent = models.ForeignKey('self', null=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class PortalTechnology(models.Model): basetech = models.ForeignKey(Technology) category = models.ManyToManyField(Category) thumbnail = models.ImageField(blank=True, null=True) application = models.CharField(max_length=255, blank=True, null=True) selling_point = models.CharField(max_length=255, blank=True, null=True) cost_benefits = models.CharField(max_length=255, blank=True, null=True) case_study = models.CharField(max_length=255, blank=True, null=True) risk = models.CharField(max_length=255, blank=True, null=True) business_model = models.CharField(max_length=255, blank=True, null=True) tag_outcome = models.CharField(max_length=255, blank=True, null=True) media = models.ManyToManyField(Media) author = models.ForeignKey(User, related_name="technology_author") reviewer = models.ForeignKey(User, related_name="technology_reviewer", blank=True, null=True) reviewed_date = models.DateTimeField("Reviewed date", blank=True, null=True) class Meta: verbose_name_plural = "TechPortal technologies" def __str__(self): return self.basetech.name First I'm transferring technologies... # Insert all technologies def technologies(): current = con_mysql.cursor() current_query = ("SELECT " "technology_id, " "title, " "description, " "c_description, " "c_application, " "c_unique_selling_point, " "c_cost_and_financial_benefits, " "c_stage_of_development_and_case_study, " "c_technical_risk, " "c_business_model, " "c_preferred_outcomes_from_tag, " "company_id, " "author, " "contactor, " "publish_date, " "edit_date, " … -
Is there a better way to design the Message model?
Is there a better way to design the Message model ? I have a Message model: class Message(models.Model): """ message """ title = models.CharField(max_length=64, help_text="title") content = models.CharField(max_length=1024, help_text="content") is_read = models.BooleanField(default=False, help_text="whether message is read") create_user = models.ForeignKey(User, related_name="messages",help_text="creator") receive_user = models.CharField(max_length=1024, help_text="receive users' id") def __str__(self): return self.title def __unicode__(self): return self.title You see, I use models.CharField to store the users' id, so I can know the users who should receive this row message. I don't know whether this design type is good. or is there a better way to do that? I have considered use ManyToMany Field, but I think if user is too many, the admin create one message will create as many as users count, so I think this is not a good idea. -
Django Rest Framework: Nested Serializers not appearing
I am having trouble with nested serializers and the Django rest framework. When setting serializer_class to "UserSerializer", the nested data from the "NameSerializer" class isn't appearing. However, when I set serializer_class to "NameSerializer", the data does appear. The API returns when using UserSerializer: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "userName": "admin@admin.com" }, { "id": 2, "userName": "2@admin.com" }, { "id": 3, "userName": "3@admin.com" }, { "id": 4, "userName": "4@admin.com" } ] What I want it to return: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "userName": "admin@admin.com" "name": { "familyName": "Joe", "givenName": "admin", "formated": "admin Joe" }, }, { "id": 2, "userName": "jane@admin.com" "name": { "familyName": "Doe", "givenName": "Jane", "formated": "Jane Doe" }, }, { "id": 3, "userName": "Billy@admin.com" "name": { "familyName": "Idol", "givenName": "Billy", "formated": "Billy Idol" }, }, { "id": 4, "userName": "User@admin.com" "name": { "familyName": "B", "givenName": "User", "formated": "User B" }, } ] views.py from API.models import Person from API.serializers import * from rest_framework import viewsets class UserViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = NameSerializer models.py class Person(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=254, … -
Prevent Superuser from deleting/removing/editing User Email in Django Admin
I am using django-allauth for User signup and login purposes. Users can login using both username and email. # settings.py # Custom User Model AUTH_USER_MODEL = 'users.User' # ask for either username or email during login ACCOUNT_AUTHENTICATION_METHOD = 'username_email' # Set Email field as required during signup ACCOUNT_EMAIL_REQUIRED = True # Set email versification necessary before creating account ACCOUNT_EMAIL_VERIFICATION = 'mandatory' # Don't ask for username while signing up. # Users can later edit/change username in their profile. # If username is not set, use email to log in. ACCOUNT_USERNAME_REQUIRED = False # Login the user after email-confirmations ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True I have a users app which implements a custom User Model as shown. # users/models.py class User(AbstractUser): name = models.CharField(blank=True, max_length=255) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) Using this setup, I am able to make user login via both email and username. However, the problem being the fact that Superuser is able to edit/remove 'email' in Django Admin. I don't want such behaviours. (An attempt to remove username however gives an "field required" error.) My question now is, How to prevent the Admin from editing the user information. i.e make 'username' and 'email' read-only fields. -
How to Filter table by column in django
I was trying to filter my columns in my django project template Currently I am able to search in the table and display the rows that have that that value But I would like to add a dropdown menu that would ask for a particular column value and then filter based on that value currently my code is views.py def user_profile(request): q = request.GET.get('q','') custom = Customer.objects.all() if q: custom1=custom.filter(name__contains=q) custom2=custom.filter(Product__contains=q) custom3=custom.filter(L3__contains=q) custom4=custom.filter(Server_Type__contains=q) custom5=custom.filter(Version__contains=q) custom6=custom.filter(Status__contains=q) custom7=custom.filter(PM__contains=q) custom8=custom.filter(CDM__contains=q) custom = custom1 | custom2 | custom3 | custom4 | custom5 | custom6 | custom7 | custom8 here name product l3 are my fields from my model that I would like to filter from in my home.html <input type="text" class="text_field" id="search" placeholder="Search for..." required> <input type="button" class="button" onclick="go()" value="go" id="submit"> my js.js function go(){ // alert("hellonikhar"); var q = document.getElementById("search").value; window.open("/?q="+q,"_self"); } I am storing the value entered in the textbox in var q and displaying the data but i would like to add a dropdown first which would choose the field and then q should filter based on only that column -
Django ImportError: No module named 'culqipy'
I made a modulo for python https://github.com/culqi/culqi-python but I don't know the reason why I cannot import in django project File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/willyaguirre/PycharmProjects/e-s/tienda/urls.py", line 4, in <module> from . import views File "/Users/willyaguirre/PycharmProjects/e-s/tienda/views.py", line 13, in <module> import culqipy as culqi ImportError: No module named culqipy maybe my module is wrong =/ -
How can I put json's data to form?
I wanna put json's data to form.I wrote in index.html {% load staticfiles %} <html lang="ja"> <head> <meta charset="utf-8"> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script> </head> <body> <main> <form class="form-horizontal" action="/accounts/regist_save/" method="POST"> <label for="id_email">Email</label> {{ regist_form.email }} {% include 'registration/sex.html' %} <button type="submit" class="regist">REGIST</button> <input name="next" type="hidden"/> {% csrf_token %} </form> </main> </body> </html> in forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm from .models import User from .models import NewUser class RegisterForm(UserCreationForm): class Meta: model = User fields = ('email',) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs['class'] = 'form-control' class ProfileForm(forms.ModelForm): class Meta: model = NewUser fields = ( "sex" ) in models.py #coding:utf-8 from django.db import models from django.contrib.auth.models import User class NewUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) sex = models.CharField(max_length=100,null=True, blank=True, default=None) in sex.html <form class="form-horizontal" method="post" action="#"> <div class="form-group-lg"> <label for="sex">SEX</label> <select class="form-control sex" name="sex"> <option value="">--</option> <option value="male">MAN</option> <option value="female">FEMALE</option> </select> </div> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> function showSex() { var num = document.forms[0].sex.selectedIndex; var sex = document.forms[0].sex.options[num].value; console.log(sex); } document.addEventListener("DOMContentLoaded", showSex); for (var i = 0, e = document.querySelectorAll(".form-horizontal select"); i < e.length; i++) { e[i].addEventListener("change", showSex); } </script> Now REGIST button cannot be sent,so I cannot regist these data.Why … -
apache creates more then one process
I am running django application in apache using mod wsgi. I have set server limit to 1 as of the following configuration. 00-mpm.conf <IfModule worker.c> StartServers 1 ServerLimit 1 #MaxClients 300 MinSpareThreads 25 MaxSpareThreads 75 ThreadsPerChild 25 MaxRequestsPerChild 0 </IfModule> At beginning apache runs with one server. But after some time when i am checking it runs with two servers. And i got the following error in the error.log [mpm_worker:notice] [pid 46754:tid 139924109117568] AH00297: SIGUSR1 received. Doing graceful restart. How can i make sure that apache to run with only one server. And not doing restart. -
how to pass argument in django serializer?
I have email variable in view and i want to access this in ManageSerializer, how can i pass this argument in serializer and get there? views.py email = 'xyz@gmail.com' interviewData = Manage.objects. filter(catcher_id = userCheck['id'], acceptation = '1'). filter(invitation_date__gte = dateToday)[:5]; serializer = ManageSerializers(interviewData, many = True) Please let me know -
after redirect - is there a way to remove the form field from the URL in Django?
After sending a form, i'm redirected to another page. The URL of that page will contain the URL + form field name + form field value. Is there a way to redirect (or maybe manipulating data without redirect) in a way that the URL won't show the form field name and value? my project (no apps): urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^translate/', views.translate, name='translate'), ] views.py from django.shortcuts import render def home(request): return render(request, 'hello.html') def translate(request): original = request.GET['originaltext'].lower() translation = '' for word in original.split(): if word[0] in ['a','e','i','o','u']: translation += word translation +='yay ' else: translation += word[1:] translation += word[0] translation += 'ay ' return render(request, 'translate.html', {'original':original, 'translate':translation}) hello.html <h1> heading title </h1> <form action="{% url 'translate' %}"> <input type="text" name="originaltext"/> <br/> <input type="submit" value="Translate" /> </form> translate.html {{ original }} <br> {{ translate }} <br><br> <a href="{% url 'home' %}">Home</a> So whenever i'm sending the form, i'm redirected and the URL becomes: http://127.0.0.1:8000/translate/?originaltext=user_text -
queryset.update is not working in for loop
I want to change the name for any database variable if its match abc. def icall(modeladmin, request, queryset): for pri in queryset: print('from test:', pri.name, pri.title) # priting if working fine if pri.name == 'abc': # loop is matching the condition pri.update(name='zzz') ## the value is not getting update in DB else: print("gg not mached") the pri.update(name='zzz') os not working here. can someone please help me to know the correct statement to update the database based on the if else condition. -
django carousal not working
I spend two days trying to fixed carousal in my website. Since i am new to django i manage to get a navbar from bootstrap cdn but unable to load carousal in my browser. Please help Here is my base.html looks like <!--Carousal-slider--> <main role= "main"> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Indicators--> <ol class="carousel-indicators"> {% for item in slider %} <li data-target="#carousel-example-generic" data-slide-to="{{ item.id }}" class="{% if forloop.first %}active{% endif %}"></li> {% endfor %} </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> {% for item in slider %} <div class="item{% if forloop.first %} active {% endif %}"> {% if item.slider %}<img src="{{ item.slider_image.url }}" alt="test">{% endif %} <div class="carousel-caption"> {% if item.display_title %}<h3>{{ item.display_title }}</h3>{% endif %} {{ item.display_content|safe }} </div> </div> <!-- <div class="item"> <img src="..." alt="..."> <div class="carousel-caption"> ... </div> </div> ... --> </div> {%endfor%} <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </main> </body> After viewing source code of my website it looks like carousel is not taking my images from folder as i mention. Here what it looks like <!--Carousal-slider--> <main role= … -
Django query passing parameters into values()
I have a Django query like this and I want to be able to pass the "values" param from a variable. Reason for this I can standardize all my list values otherwise it will be hardcoded on every values. So for example, this works: employee_list = Employee.objects.all().values("id", "username").order_by('id') But I cannot do this. It doesnt work: val_params = ["id", "username"] employee_list = Employee.objects.all().values(val_params).order_by('id') what kind of val_params can i use to pass into values() ? Is there a way to do this ? -
Report_tools in django 1.11
I am trying to use report_tools package written for django 1.6 in django 1.11. I am trying to make changes in that according to django 1.11. when i try to run the code: from django.utils.encoding import python_2_unicode_compatible class BaseReport(python_2_unicode_compatible): it shows error: class BaseReport(python_2_unicode_compatible): TypeError: Error when calling the metaclass bases function() argument 1 must be code, not str earlier version used from django.utils.encoding import StrAndUnicode class BaseReport(StrAndUnicode): which is depreciated in newer django version Please help. -
Django - Paginate with another GET request; not working with just pagination page number
I'm building a page with pagination and a filter form (2 GET requests). If the URL includes both pagination and filter results, something like /questions/?page=2&all_questions=on, it works fine. It also works if it just has filter results, something like /questions/?all_questions=on. However if it only has the pagination page result, something like /questions/?page=1, no results are shown. So I figured I need to do something in the views so that if there is only page number in the URL, a default filter will be given. I know I probably need to add something to the Try and Except section of pagination, but I'm stumped as the actual code I need to write. def questions_index(request): user = request.user form = QuestionFilterForm(request.GET or None) question_list = [] if not form.is_bound: question_list = Question.objects.all().order_by('-date_created') if form.is_valid(): if form.cleaned_data['all_questions'] | (form.cleaned_data['general_questions'] & form.cleaned_data['location_all_gta']) == True: question_list = Question.objects.all().order_by('-date_created') elif form.cleaned_data['location_all_gta'] == True: question_list += Question.objects.filter(question_type=1).order_by('-date_created') else: if form.cleaned_data['general_questions'] == True: question_list += Question.objects.filter(question_type=2).order_by('-date_created') if form.cleaned_data['location_toronto'] == True: question_list += Question.objects.filter(location='1').order_by('-date_created') paginator = Paginator(question_list, 15) # Pagination page = request.GET.get('page') try: questions = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. questions = paginator.page(1) except EmptyPage: # If page is out … -
Unexpected keyword argument when providing correct arguments
I am trying to create a new row for my model model_name in Django 1.11.2 My model looks like class model_name(models.Model): attribute = models.CharField( max_length = 255, null = True, ) Inside my views I am trying to do something like variable = model_name(attribute="String Value") But I am getting an the error "model_name() got an unexpected keyword argument 'attribute'" I have done something similar in the past and had it working but for some reason it isn't now. Any ideas as to why? Any help in the right direction would be very much appreciated. -
Possibility of having variable parameter names in Django model updates
I'd like to shorten the following code from if field == 'favorite_food': model_instance.update(favorite_food=value) elif field == 'favorite_drink': model_instance.update(favorite_drink=value) elif field == 'favorite_color': model_instance.update(favorite_color=value) to something like: if field in list: model_instance.update(field=value) So I'm just wondering if it's possible. -
Get highest count and corresponding value in Django query
I have a patient model with "disease" as one of the fields. I want to count the top 5 diseases in all patient objects and return the counts for each of them. How could I do that? -
Send Email in Django From Gmail Account
In my settings.py file I have the following: ACCOUNT_EMAIL_VERIFICATION = "none" EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = "thatotherbatman@gmail.com" EMAIL_HOST_PASSWORD = "supersecretstring" EMAIL_PORT = 587 EMAIL_USE_TLS = True Then I run python manage.py shell And do: from django.conf import settings from django.core.mail import send_mail send_mail("foo", "bar", settings.EMAIL_HOST_USER, ["otheruser@gmail.com"]) Which produces this: socket.gaierror: [Errno 8] nodename nor servname provided, or not known I've also enabled less secure apps in my google account. What am I doing wrong? -
Django Rest API, return json list of a model with only required fields - lambda did not work
In my Django Rest API, I have problem trying to do a query list and return json response based on the fields that I require (like just id, username instead of all in the model). One way is trying with lambda but it didnt work. This is a continuation for this: Django API list with pagination - Page is not JSON serializable I have an API query where I want to list model record of specific fields. For example (just id and username) instead of all the fields in the model. I am trying to use lambda to generate the json fields according to a helper function .as_dict() defined in the model. But it causes an error as show in the traceback below. Here is my function based rest API, see the lambda part at the bottom that is the problem: @api_view(['POST']) def employee_management_employee_get_list_by_page(request): # ----- YAML below for Swagger ----- """ description: employee_management_employee_get_list_by_page parameters: - name: token type: string required: true location: form - name: page type: string required: true location: form - name: page_limit type: string required: true location: form """ token = request.POST['token'] try: auth_employee = AuthEmployeeSessionToken.objects.get(token=token) except AuthEmployeeSessionToken.DoesNotExist: return Response("Invalid Token", status=status.HTTP_406_NOT_ACCEPTABLE) employee_list = Employee.objects.filter(company = … -
django authentication package: 'auth' not registered as a namespace
I'm trying to build a simple website with user authentication based on this tutorial, but I'm running into the above error. As per the instructions I set a url as folllows: url('^accounts/', include('django.contrib.auth.urls')) I got this error in response: 'auth' is not a registered namespace So I tried to register a namespace as the tutorial repo shows: url('^accounts/', include('django.contrib.auth.urls', namespace="auth")), then I get the error : Specifying a namespace in include() without providing an app_name I realised that the tutorial is using django 1.8.3, but I'm on 2.0. The issue is resolved when I switch to the same django version in virtualenv, but I'm now having to a change a number of other things across the project to keep it from breaking. Any way to fix without require django 1.8? Thanks. -
Temporary list of users that sent request
My scenario is like a game matchmaking, Django gets the users ID that wants to play and queue or cache them. then match those who are in queue together. How do i create a global list of users that requested to play, users can request with GET or POST method. How do i retrieve users from that global list? so i can match them together. -
Client Authentication in Django rest framework powered App using django-oauth-toolkit
I am creating a project in django for my mobile app. The django project is the API backend for the mobile App. I have created a signup for the user model using django rest framework. The signup API works fine. Now, i want to let only the request from my mobile app to be served. For this i created an oauth application Authorization grant type " client-credentials " class UserSerializer(ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(min_length=8) def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user class Meta: model = User fields = ('id', 'username', 'email', 'password') read_only_fields = ('id',) write_only_fields = ('password',) This is the user serializer and the view is class UserCreateAPIView(CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAuthenticatedOrCreate, TokenHasScope) But the problem is I can make direct calls to the signup api without using the toke. How to make sure that the User Create API is called when only the token is passed or the post request to be valid when the token is passed.