Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UserCreateForm bypassing UserManager, regular users created through UserCreateForm CAN authenticate but superuser created in shell CAN NOT?
I have a custom user model and a user manager defined as follows: /accounts/models.py from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, username=None, password=None): if not email: raise ValueError("Users must have a valid email address") if not first_name and last_name: raise ValueError("Users must have a first and last name") created_username = ''.join([first_name.lower(), last_name[:1].lower()]) i=2 while User.objects.filter(username=created_username).exists(): created_username = ''.join([first_name.lower(), last_name[:i].lower()]) i+=1 user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, username=created_username ) user.set_password(password) user.save() return user def create_superuser(self, email, first_name, last_name, password): user = self.create_user( email, first_name, last_name, password ) user.is_staff = True user.is_admin = True user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=40, blank=True) last_name = models.CharField(max_length=40, blank=True) username = models.CharField(max_length=40, unique=True, blank=True, editable=False) # display_name = models.CharField(max_length=150) bio = models.TextField(blank=True, null=True) avatar = models.ImageField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name'] def __str__(self): return "{} @{}".format(self.email, self.username) def get_short_name(self): return self.first_name def get_full_name(self): return ' '.join([self.first_name, self.last_name]) This seems to work perfectly when registering a superuser from the shell. I have β¦ -
Post via (ajax/javascript) to django view printing empty queryset
I'm trying to use more vanilla javascript instead if jquery. I have no problem making ajax calls with $.post but I can't seem to get it to work with vanilla javascript. This is my ajax call: $(document).ready(function () { $('#addAssignment').click(function () { $('#addAssignmentModal').modal('toggle'); }); $('#submitAssignment').click(function () { if(checkModal()){ var assignment = { title: $('#newAssignmentTitle').val(), type: $('#assignmentSelection').val(), date: $('#newAssignmentDate').val(), details: $('#newAssignmentDetails').val() } console.log(assignment); submitAssignment(assignment); } }); }); function submitAssignment(assignment) { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { //Do stuff } }; request.open("POST", '/data/api/create-assignment/', true); request.setRequestHeader('X-CSRFToken', cookies['csrftoken']); //assignment is equal to: {title: "Title", type: "Homework", date: "02/18/2017", details: "Detais"} request.send(JSON.stringify(assignment)); } When I try and print out the data in my Djano view, it prints out an empty queryset every time. def createAssignment(request): if request.method == 'POST': print(request.POST) # this prints an empty queryset # assignment = Assignments() # assignment = request.POST.get('assignment') # assignment.save() data = {} data['status'] = "Success" return HttpResponse(json.dumps(data), content_type="application/json") else: data = {} data['status'] = "Data must be sent via POST" return HttpResponse(json.dumps(data), content_type="application/json") How do I prepare my data and receive it properly? -
Gunicorn ImportError: No module name myApp
I am trying to deploy my code on Heroku but gunicorn is giving error ImportError: No module named inventory. My Directory Structure --server | |--server βββ __init__.py βββ home β βββ __init__.py β βββ admin.py β βββ migrations β β βββ __init__.py β βββ models.py β βββ tests.py β βββ views.py βββ inventory β βββ __init__.py β βββ admin.py β βββ migrations β β βββ 0001_initial.py β β βββ __init__.py β βββ models.py β βββ serializer.py β βββ tests.py β βββ views.py βββ manage.py βββ server βββ __init__.py βββ settings.py βββ urls.py βββ wsgi.py wsgi.py import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.server.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) Basically my main server Django project is in /server/server/settings.py Need Help here -
Incorrect DatetimeInput format on Django Form
I try to populate the fields for editing an event. But this is how the date field is shown when trying to edit it: class EventForm(forms.ModelForm): ... date = forms.DateTimeField(widget=forms.widgets.DateTimeInput(format=["%d/%m/%Y %H:%M:%S"], attrs={'placeholder':"DD/MM/YY HH:MM:SS"})) ... class Meta: model = Event views.py def event(request, category_slug, event_slug): ... event = Event.objects.get(slug=event_slug) form = EventForm(instance=my_event) context_dict["edit_event_form"] = form ... return render(request, 'handsup/event.html', context=context_dict) This is how the field is called in event.html: <div class="form-group"> {{ edit_event_form.date.errors }} {{ edit_event_form.date.label_tag }} {{ edit_event_form.date|addclass:"form-control form-style"}} </div> Any comment or suggestion is greatly appreciated. Thank you. -
Django extended user model not saving password
I need to change the user model field id's type from integer to uuid. So I have extended the base django model as follows. Now the user details saving without the password. Password field remains blank. Following is my user model. import uuid from django.contrib.auth.models import Group, Permission from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from django.utils.translation import ugettext_lazy as _ from django.utils import six, timezone from django.core import validators class MyUserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=256, blank=True) last_name = models.CharField(max_length=256, blank=True) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) """ Some fields commented """ objects = MyUserManager() USERNAME_FIELD = 'email' def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is β¦ -
django settings after mongodb setup
I had a project which I was working on happily, then I wanted to switch from sqlite to mongodb just to try things. Well, I only followed these instructions https://django-mongodb-engine.readthedocs.io/en/latest/topics/setup.html, but now my whole Django doesn't work. I can't do anything, no "python manage.py check", nor python manage.py runserver, not even django-admin stratproject to make a new one. I also rolled back to previous my commit, before I started to modify things, however, it seems that environmental variables are screwed, so it doesn't work either. I keep getting ImportError: No module named myapp.settings. I went into manage.py and modified it to settings which worked, but the problem went down, so it keeps telling me now that django.db.models.fields import (DateTimeField, DateField, ImportError: cannot import name BinaryField django.apps import AppConfig ImportError: cannot import name apps etc... I also tried to export DJANGO_SETTINGS_MODULE=myapp.settings as it's described here https://docs.djangoproject.com/en/1.10/topics/settings/, but this didn't change anything. Any try to call python manage.py check, which worked perfectly before, results in Unknown command: 'check' My question is: wtf? Do I just remove Django and install again? -
How to insert data in mysql db using sqlalchemy from django framework?
I am new in django framework and I am trying to make an api for "register" where i want to insert data into db after execution but unable to do so . I am trying to create the object of auth_user and trying to do session.add(auth_user_object) but it is not giving any error and even not adding data to mysql db. I am able to get(fetch) data from db . all the tables are created . then i am doing inspect db and get the db table class and modify it according to sqlalchemy. but I am unable to add data to the db tables using sqlalchemy . please help me. what is best approach to do so. my models.py from __future__ import unicode_literals from django.db import models from sqlalchemy import * from sqlalchemy import types from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import * # Create your models here. Base = declarative_base() class Designation(Base): __tablename__='designation' id = Column(autoincrement=True,primary_key=True) designation_name = Column(String) designation_desc = Column(String) class UAuthUser(Base): __tablename__='auth_user' id = Column(autoincrement=True,primary_key=True) password = Column(String) last_login = Column(DateTime) is_superuser = Column(Integer) username = Column(String) first_name = Column(String) last_name = Column(String) email = Column(String) β¦ -
Python - Django - Model BooleanField Dependent On Other BooleanField In Same Model
I am using Django to write a web application and would like to know if it is possible to have a BooleanField within a model for which the value will be based on other BooleanFields in the same model. Basically, I would like one BooleanField in the model to be True only if all other BooleanFields in the model are True. For example, with the Model below: class ModelEx(models.Model): booleanA = models.BooleanField(default=False) booleanB = models.BooleanField(default=False) booleanC = models.BooleanField(default=False) booleanD = models.BooleanField(default=False) I would like booleanA to be True only if booleanB and booleanC and booleanD are True. I have not found any information about this so it would be great if anyone knew if there is a solution for this. Thanks. -
Posting a default value with serializer for drf
I am attempting to post a default value. In english: 1. If data has no "tag" field (s) 2. Check to see if tag "none" exists 3. If tag "none" exists, create the m2m 4. If tag "none' doesn't exist, create the tag none with owner I keep getting the error 'tag field is required' My post data will not contain the field tag in the JSON data being posted. This code works perfectly EXCEPT when there is no tag field Example data being posted {title: "Testing"} Models.py class Tag(models.Model): name = models.CharField("Name", max_length=5000, blank=True) taglevel = models.IntegerField("Tag level", null=True, blank=True) class Item(models.Model): title = models.CharField("Title", max_length=10000, blank=True) tag = models.ManyToManyField('Tag', blank=True) Serializer class ItemSerializer(serializers.ModelSerializer): tag = TagSerializer(many=True, read_only=False) info = InfoSerializer(many=True, read_only=True) class Meta: model = Item ordering = ('-created',) fields = ('title', 'pk', 'tag') def create(self, validated_data): tags_data = validated_data.pop('tag') owner = self.context['request'].user item = Item.objects.create(owner=owner, **validated_data) for tag_data in tags_data: tag_data['owner'] = owner tag_qs = Tag.objects.filter(name__iexact=tag_data['name']) if not tag_data: Tag.objects.get_or_create(tags_name="None") if tag_qs.exists(): tag = tag_qs.first() else: tag = Tag.objects.create(**tag_data) item.tag.add(tag) return item -
how to serialize choicefield by display?
i have a model that contains a choice field similar to this: class Person(models.Model): gender = models.IntegerField(choices=((1, "male"), (2, "female"))) now i want to get/set the field by it's display name, and not by the id. for example, set object: Person.objects.create(gender="male") I found this answer helpful for get, but its not working for set. how can i do such a thing? is their a built-in serializer for this? -
Django delete a file
I have the following template that allows me to upload a file and also show the images with a delete button underneath: <div class="col-md-12 col-md-offset-0"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="col-xs-12 col-md-5 col-md-offset-0">{{ form.document }}</div> <div class="col-xs-12 col-md-1 col-md-offset-0"><button type="submit" >Upload</button></div> </form> {% for image in images %} <div class="col-md-1 col-md-offset-0"> <img style="width: 100%;" src='{{MEDIA_URL}}/{{ username }}/{{image}}' alt="ID Image"/> <div style="text-align: center;"><button type = "button" class = "btn btn-danger btn-sm">Delete</button></div> </div> <!-- Indicates a dangerous or potentially negative action --> {% endfor %} </div> The view for this template is as follows: @login_required def profile(request, extra_context={}): path="media/" + request.user.username + "/" # insert the path to your directory if (os.path.isdir(path)): num_files = len([f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]) img_list =os.listdir(path) else: num_files = 0 img_list = "" username = request.user.username if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.save() return redirect('profile') else: form = DocumentForm() form_address = ProfileFormAddress() return render(request, 'meta/profile.html', { 'form': form, 'images': img_list, 'username': username, 'num_files': num_files, 'form_address': form_address, }) As it stands the delete button does not do anything. I feel I should be create a form for each button that when clicked will β¦ -
Redirect not able to send response
I'm using redirect in Django to send the user to another page but it is not able to do so. views.py def func1(request): if not request.user.is_authenticated(): return render(request, 'login/login/login.html') else: if request.method == "POST": return redirect('base:func2') return render(request, 'base/home/index.html') def func2(request): if not request.user.is_authenticated(): return render(request, 'login/login/login.html') else: if request.method == "POST": .... return render(request, 'bla_bla_bla.html', {'location': location}) elif request.method == 'GET': print('COntrol is here') some_details_form = SomeDetailsForm() return render(request, 'some_url/index.html', {'some_details_form': some_details_form}) urls.py app_name = 'base' url(r'^another_url/$', views.func2, name='func2'), url(r'^some_url/$', views.func1, name='func1'), base/home/index.html <div class="button" onclick="clicked_it()"> <span id="forward"> Go Further </span> </div> index.js function clicked_it() { $.post( "/base/some_url/"); }; So the control does go to func2 since I can see the print statement output COntrol is here but I don't see that the func2 is able to render the page in the return statement. Where is the control getting stuck? -
django and d3.tsv, not working
I am totally confused now, it just does not work! my django views: def data_tsv(request): event = Event.objects.get(pk=request.GET.get('epk')) occurrences = event.occurrences.all() response = HttpResponse(content_type='text/tsv') response['Content-Disposition'] = 'filename="data.tsv"' for occ in occurrences: response.write('%s %s\n' % (occ.timestamp, occ.counter)) return response my js: var svg = d3.select("svg"), margin = {top: 20, right: 20, bottom: 30, left: 50}, width = +svg.attr("width") - margin.left - margin.right, height = +svg.attr("height") - margin.top - margin.bottom, g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var parseTime = d3.timeParse("%d-%b-%y"); var x = d3.scaleTime().rangeRound([0, width]); var y = d3.scaleLinear().rangeRound([height, 0]); var line = d3.line() .x(function (d) { return x(d.date); }) .y(function (d) { return y(d.close); }); d3.tsv("{% url 'data_tsv' %}?epk={{ event.id }}", function (d) { d.date = parseTime(d.date); d.close = +d.close; return d; }, function (error, data) { if (error) throw error; x.domain(d3.extent(data, function (d) { return d.date; })); y.domain(d3.extent(data, function (d) { return d.close; })); g.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)) .select(".domain") .remove(); g.append("g") .call(d3.axisLeft(y)) .append("text") .attr("fill", "#000") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", "0.71em") .attr("text-anchor", "end") .text("Price ($)"); g.append("path") .datum(data) .attr("fill", "none") .attr("stroke", "steelblue") .attr("stroke-linejoin", "round") .attr("stroke-linecap", "round") .attr("stroke-width", 1.5) .attr("d", line); }); and I am getting my data.tsv looks like this: 2017-02-12 β¦ -
python Url translation on django authentication
this is a url after sign out localhost:8000/en/Users/sign-in/?next=/en/Users/ but if i change language preference and log in language doesn't change because when i change language preference url becomes localhost:8000/ru/Users/sign-in/?next=/en/Users/ after login localhost:8000/en/Users/ then after pressing log out it changes localhost:8000/ru/Users/sign-in/?next=/ru/Users/ url.py urlpatterns = [ url(r'^i18n/', include('django.conf.urls.i18n')), ] urlpatterns += solid_i18n_patterns( url(r'^rosetta/', include('rosetta.urls')), url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^Users/sign-in/$', auth_views.login, {'template_name': 'Users/sign_in.html'}, name='Users-sign-in'), url(r'^Users/sign-out/$', auth_views.logout, {'next_page': '/'}, name='Users-sign-out'), url(r'^Users/$', views.Users_home, name= 'Users-home'), ) -
how to use tornado and django on open swift
Recently I have been working on openswift Django(1.8) with Python(3.3). I was woundering is it possible to work with Websocket along tornado and django beacuse using of tornado will be handling the request in Asynchronous IO handler. Any good suggestions. -
mezzanine showing pages only when loged in
I've got some trouble with my brand new mezzanine installation. After setting up mysql with UTF8 charset, migrating the model to the database and setting up a superuser for mezzanine I created a new page with some content that I wanted to show to my students. You can visit it here: fadenstrahl.de The page "Elektromagnetismus" is missing! It shows up as long as I am logged in but it hides when i'm logged out. And the checkbox "login required" is not checked! I was trying to set up this page as / (in the meta description) and redirect the homepage to this page in the ursl.py by commenting this line: # url("^$", direct_to_template, {"template": "index.html"}, name="home"), and uncommenting this line: url("^$", mezzanine.pages.views.page, {"slug": "/"}, name="home"), I had to add this at the beginning: import mezzanine.pages.views I got the same problem. But because due to the problem, I get a 404 because there is no homepage anymore. Why do I have to be logged in to see the content. I want it to be public. Thanks for your help and best regards, Pascal -
Bootstrap form showing error messages in a different style
I have two forms in my django app, and I'm using bootstrap3 to custom them, But the error messages to the form aren't equal. For my login form I have the error messages in a container, like this But in the Sign up form... merely illustrative images My templates are using the same structure, I don't know why the difference. login.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% load bootstrap3 %} <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% block content %} <div class="row"> <div class="col-sm-4"> <form method="POST" action=""> {% csrf_token %} {% bootstrap_form form %} <input class='btn btn-primary' type="submit" value="Logar"> </form></br></br> </div> </div> {% endblock %} </body> </html> signup.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% load bootstrap3 %} <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% block content %} <div class="row"> <div class="col-sm-4"> <form method="POST" action=""> {% csrf_token %} {% bootstrap_form form %} <input class='btn btn-primary' type="submit" value="Cadastrar"> </form> </div> </div> {% endblock %} </body> </html> -
Django MySQL Manual Full Text Search Code Location
The Django docs mention that this was removed in 1.10 because it was too database specific and has been replaced with this : (https://docs.djangoproject.com/en/1.10/releases/1.10/#search-query-lookup) from django.db import models class Search(models.Lookup): lookup_name = 'search' def as_mysql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return 'MATCH (%s) AGAINST (%s IN BOOLEAN MODE)' % (lhs, rhs), params models.CharField.register_lookup(Search) models.TextField.register_lookup(Search) Does anyone know where this code belongs in the project structure so it will be executed at the right time? Thanks! -
Error 404 on get request from AJAX call on django views
I am getting a "Page Not for error" for the ajax request that is supposed to fetch data from the django views Projectboard/dashboard.html <form action="view"> <br> Select your favorite fruit: <select id="mySelect"> <option value="apple" selected >Select fruit</option> <option value="apple">Apple</option> <option value="orange">Orange</option> <option value="pineapple">Pineapple</option> <option value="banana">Banana</option> </select> </form> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#mySelect").change(function(){ selected ="apple"; $.ajax({ type: 'GET', dataType: 'json', contentType: 'application/json; charset=utf-8', url: '/projectboard/view/', data: { 'fruit': selected }, success: function(result) { document.write(result) } }); }); }); </script> projectboard/urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^disp.html$', views.index2, name='index2'), url(r'^view/(?P<id_remedio>\w+)/$', views.view, name='view'), url(r'view$', views.view, name='view') ] views.py from django.http import HttpResponse def view(request): data="bleh" if request.method == 'GET': print (request.body) data = request.body return HttpResponse(json.dumps(data)) The error i am getting is GET http://127.0.0.1:8000/projectboard/view/?fruit=apple 404 (Not Found) -
How to resolve cyclic dependency in defining generic models in django
I want to define a generic model, which can be used in any app. Following are the definitions of my generic models:- User = settings.AUTH_USER_MODEL # This mixin is used to track the user, who has created this object. class OwnedModel(models.Model): owner = ForeignKey(to=User, null=True, editable=False) class Meta: abstract = True # AreaOrVillage extending this model, will also get owner field, which # refer to User. class AreaOrVillage(OwnedModel): area_village_name = LocationIdentifierField(name="areaOrVillageName", verbose_name="Area/Village:", blank=False, null=False) area_village_code = LocationCodeField(name="areaOrVillageCode", verbose_name="Area/Village Code", null=True, blank=True) zipcode = ZipCodeField(verbose_name="ZipCode", null=False, blank=False) # It's another model, referred by this model tehsil = models.ForeignKey(to=Tehsil, related_name="areas_or_villages") class Meta: verbose_name_plural = "Areas/Villages" unique_together = ("tehsil", "areaOrVillageName") ordering = ("tehsil", "areaOrVillageName") app_label = 'location_app' def __str__(self): text = self.to_str() return "{}{}{}".format(text, ", " if text and self.tehsil else "", self.tehsil.__str__() if self.tehsil else "") def to_str(self): return "%s" %(self.areaOrVillageName or self.areaOrVillageCode) Now, In my django project, I have overridden default user model as follow(which makes use of generic models, defined above) :- class PSS_User_Type(ModelBase): def __new__(cls, name, bases, dictattrs): user_type = super(PSS_User_Type, cls).__new__(cls, name, bases, dictattrs) OVER_RIDDEN_ATTR = "is_staff" NEW_ATTR = "is_devteam_member" if hasattr(user_type, OVER_RIDDEN_ATTR): setattr(user_type, NEW_ATTR, getattr(user_type, OVER_RIDDEN_ATTR)) delattr(user_type, OVER_RIDDEN_ATTR) setattr(user_type, "__getattr__", PSS_User_Type.__getattr__) def __getattr__(self, attrname): effective_attr = NEW_ATTR β¦ -
why my save() isn't working? Django
I'm working on a web app, but my save isn't working. I want to show age and country on a table after I hit on submit button. Here's what I got: // models AGES = ( ('OLD', 'OLD'), ('YOUNG', 'YOUNG '), ) class Person(models.Model): name = models.TextField() age = models.CharField(max_length=128,choices=AGES, default=True) def __str__(self): return self.name class Questions_old(models.Model): person = models.ForeignKey(Person) country = models.TextField() hobbies = models.TextField() def __str__(self): return self.person.name class Questions_young(models.Model): person = models.ForeignKey(Person) country = models.TextField() parents = models.TextField() def __str__(self): return self.person.name // forms class personForm(forms.ModelForm): class Meta: model = Person fields = ["age","name"] class person_oldForm(forms.ModelForm): class Meta: model = Questions_old exclude = ('Person',) fields = ['country','hobbies'] class person_youngForm(forms.ModelForm): class Meta: model = Questions_young exclude = ('Person',) fields = ['country','parents'] // views def person_form(request): form1 = personForm(request.POST or None) form2 = person_oldForm(request.POST or None) form3 = person_youngForm(request.POST or None) queryset1 = Person.objects.all() queryset2 = Questions_old.objects.all() queryset3 = Questions_young.objects.all() qs = chain(queryset2,queryset3) context = { "form1": form1, "form2": form2, "form3": form3, "qs": qs, } form1_valid = form1.is_valid() form2_valid = form2.is_valid() form3_valid = form3.is_valid() if form1_valid: person = form1.save() if form2_valid: qo = form2.save(commit=False) qo.person = person qo.save() if form3_valid: qy = form3.save(commit=False) qy.person = person qy.save() return render(request, β¦ -
Facebook import and export in Django
I want to upload photos to Facebook and retrieve photos from Facebook through my Django 1.10 web application. How can i do that? Is there any reference or tutorials for it? -
Django - filtering related subset (foreign key) - Error
everybody! After inspectdb I have such a model class User(models.Model): id = models.AutoField(primary_key=True) login = models.CharField(max_length=30) ... created_on = models.DateTimeField(blank=True, null=True) updated_on = models.DateTimeField(blank=True, null=True) ... class Meta: managed = False db_table = 'users' def __str__(self) : return(self.lastname + ' ' + self.firstname) class Journal(models.Model): id = models.AutoField(primary_key=True) user_id = models.ForeignKey(User, db_column='user_id') notes = models.TextField(blank=True, null=True) created_on = models.DateTimeField() class Meta: managed = False db_table = 'journals' In this case I'm trying to get all of the journals that created by specified user and created later specified date. user = User.objects.get(id=12) myCount = user.journal_set.filter(created_on>myDay).count() And here I'm receiving next error: Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'created_on' is not defined Can anyone help here: how to count related journals created by specified user in this model? Thank you! -
Django REST framework. Get object by unique url
I making rest api of my django project for mobile client. I have this model and API structure for Categories objects: models.py class Category(models.Model): title = models.CharField(max_length=200, verbose_name="Title") url = models.CharField(max_length=200, verbose_name="Url") api/serializers.py class CategoryDetailSerializer(ModelSerializer): class Meta: model = Category fields = [ 'id', 'title', 'url' ] api/views.py class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategoryDetailSerializer and api/urls.py urlpatterns = [ url(r'^(?P<pk>\d+)/$', CategoryViewSet.as_view({'get': 'retrieve'}), name='detail'), ] To retrieve Category object I use GET request to my_server_url/api/categories/[pk]/ Question is how can get object with it's url field (which is unique). e.g. like this: my_server_url/api/categories/category_1/ Is it possible with rest-framework? Or maybe I should get map of [pk]:[url] objects first, then get pk by url from it and pass it to existing request method..? -
unable to import numpy and pandas into django
may I check why am I unable to import numpy or pandas into django? it keeps giving import numpy as np ImportError: No module named numpy The below is my code to import it. I'm importing at the views.py btw from django.shortcuts import render from django.template import loader from django.http import HttpResponse import numpy as np