Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to constraint the together value in Serializer?
I have a EmailCreateSerializer, I can let creator pass receive_group id or receive_user id for send to them: class EmailCreateSerializer(Serializer): receive_group = serializers.IntegerField(allow_null=True) receive_user = serializers.IntegerField(allow_null=True) Either pass the receive_group (send to a group), or receive_user (send to single user). But I want to one of them (receive_group, receive_user) must be not null. Is there a way to realize it in Serializer? -
Django multiple template rendering
At the moment I'm working on a pretty complex page with multiple areas that need to be updated upon user input. My thought is to render multiple extend/include templates that are each responsible for their own part of the webpage.However, I face a few problems: I need multiple view functions to process data for all templates. I need to pass the request to multiple view functions so that they return the template with the correct data One of the functions not only takes the request but also the slug of a model object to update data on the page. Questions: How do I send responses/data from different view functions to each other? How do I pass the request to multiple functions? Does the rendering of the extends also make sure that the base.html is rendered? Are extends the right thing to use or should I use includes? So far I have thought of this system: base.html <body> {% block extend1 %} {% endblock %} {% block extend2 %} {% endblock %} {% block extend3 %} {% endblock %} </body> extend1.html (example for the 3 extends) {% extends base.html %} {% block extend1 %} #html code {% endblock views.py def extend1(request): … -
error while filtering data as per columns in django template
I am using Django template to display a table and I wish to filter data based on columns In order to do so, I have taken two var q and r in my javascript function go(){ // alert("hellonikhar"); var q = document.getElementById("search").value; var r=document.getElementById("columnName").value; window.open("/?q="+q+r,"_self"); (i guess some error is here only) } In my home.html I have made a text-field and a dropdown menu <input type="text" class="text_field" id="search" placeholder="Search for..." required> <select name="columns" id="columnName"> { <option value="{{column.name}}"> Customer Name</option> <option value="{{column.name}}"> Status</option> <option value="{{column.name}}"> Product</option> <option value="{{column.name}}"> OS Type</option> <option value="{{column.name}}"> Server Type</option> <option value="{{column.name}}"> L3</option> <option value="{{column.name}}"> Version</option> <option value="{{column.name}}"> PM</option> <option value="{{column.name}}"> CDM</option> } </select> <input type="button" class="button" onclick="go()" value="go" id="submit"> <input type="button" class="button" onclick="exp()" value="export" id="exp"> I have defined a function in my views.py to check the value of r from the dropdown and q when the go button is clicked but the data is not filtered based on those columns def user_profile(request): q = request.GET.get('q','') custom = Customer.objects.all() r= request.GET.get('r','') if (q and r=="Status"): custom1=custom.filter(name__contains=q) currently i am just testing when the value in the dropdown is status -
Save user language in a model through default() with Django
I would like to save the language of the user each time a new model instance is created: models.py: def getlanguage(request): lang = request.LANGUAGE_CODE return lang class Comment(models.Model): language = models.CharField(max_length=100, blank=True, default=getlanguage) Django generates the following error: TypeError: getlanguage() takes exactly 1 argument (0 given) How to pass the request to the function? Thank you! -
Django redirect from inside a view
I'm using django 1.11.8. I need to perform some check on the requested view and inside it redirect the user to another Http page, but this code fail, as the redirect is ignored. What am I missing? class ThisCreateView(CreateView): def get_form_kwargs(self): if self.kwargs['x'] == 1: return redirect(reverse('this_app:this_list')) return kwargs -
django rest framework installation fails
How do I install the REST framework in django? The following command throws an error on Mac OSx: pip install djangorestframework-jsonapi Could not find a version that satisfies the requirementdjangorestframework-jsonapi (from versions: ) No matching distribution found for djangorestframework-jsonapi -
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.