I did create (like and dislike) in my project and I need it when someone clicks on the button. the color will change to blue
I saw something like that where I could create a variable called something like: is_liked = False, and I can place that in HTML by context to trigger it in (if condition) but it's not working with me so, How can I run the color on the like button?
views.py
# Detail question and Create comment
class QuestionDetail(DetailView, SingleObjectMixin):
template_name = 'community/question_view.html'
slug_field = 'ask_slug'
slug_url_kwarg = 'user_slug'
model = UserAsking
queryset = UserAsking.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['my_question'] = UserAsking.objects.get(title=self.object)
self_post = UserAsking.objects.get(title=self.object)
post_slug = UserAsking.objects.get(ask_slug=self_post.ask_slug)
context['summation'] = post_slug.likes.count() - post_slug.dislikes.count()
context['comment_form'] = CommentForm
comments_count = Comment.objects.filter(userasking=UserAsking.objects.get(title=self.object))
context['comments_count'] = comments_count.count()
# liked_post = User.objects.get(username=self.request.user.username).likes.exists()
# context['liked_post'] = liked_post
# disliked_post = User.objects.get(username=self.request.user.username).dislikes.exists()
# context['disliked_post'] = disliked_post
return context
def post(self, request, user_slug, *args, **kwargs):
my_question = UserAsking.objects.get(ask_slug=user_slug)
userprof = UserProfile.objects.get(userasking__ask_slug=user_slug)
comment_form = CommentForm(request.POST, instance=request.user)
name = "%s %s" % (self.request.user.first_name, self.request.user.last_name)
username = self.request.user.username
logo = self.request.user.userprofile.logo.url
c = CommentForm(self.request.POST).add_error('comment', 'error')
if comment_form.is_valid():
comment_form = Comment.objects.create(comment=self.request.POST.get('comment', None),
userasking_id=my_question.id,
userprofile_id=userprof.id,
name=name,
username=username,
logo=logo,
comment_slug=my_question.ask_slug
)
comment_form.save()
return redirect('community:question_view', comment_form.userasking.ask_slug)
return render(request, 'community/question_view.html', {'comment_form': comment_form,
'c': c})
# Like post function
class LikePost(View, SingleObjectMixin):
template_name = 'community/question_view.html'
def post(self, request, *args, **kwargs):
post = get_object_or_404(UserAsking, ask_slug=request.POST.get('post_slug'))
if post.dislikes.filter(username=request.user).exists():
post.dislikes.remove(request.user)
post.likes.add(request.user)
models.py
class UserAsking(models.Model):
userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person')
question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question')
field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to describe what your question is about')
date = models.DateTimeField(auto_now_add=True)
ask_slug = models.SlugField(max_length=100)
likes = models.ManyToManyField(User, related_name='likes', blank=True)
dislikes = models.ManyToManyField(User, related_name='dislikes', blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('community:question_view', kwargs={'user_slug': self.ask_slug})
def save(self, *args, **kwargs):
self.ask_slug = slugify(self.title)
super().save(*args, **kwargs)
elif post.likes.filter(username=request.user).exists():
post.likes.remove(request.user)
else:
post.likes.add(request.user)
return redirect(post.get_absolute_url())
# Dislike post function
class DisLikePost(View, SingleObjectMixin):
def post(self, request, *args, **kwargs):
post = get_object_or_404(UserAsking, ask_slug=request.POST.get('post_dislike_slug'))
if post.likes.filter(username=request.user).exists():
post.likes.remove(request.user)
post.dislikes.add(request.user)
elif post.dislikes.filter(username=request.user).exists():
post.dislikes.remove(request.user)
else:
post.dislikes.add(request.user)
return redirect(post.get_absolute_url())
how can I put the condition in the HTML page to check if is_liked is True or False?
In Django Html use template like this
{% if query_set.is_like %}
...do something
change back color like <h1 style:background:''blue></h1>
{% else %}
No change... <h1></h1>
{% endif%}
I had to add a condition to get_context where that way did work with me. this way I didn't see before but it works perfectly:
views.py
class QuestionDetail(DetailView, SingleObjectMixin):
template_name = 'community/question_view.html'
slug_field = 'ask_slug'
slug_url_kwarg = 'user_slug'
model = UserAsking
queryset = UserAsking.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['my_question'] = UserAsking.objects.get(title=self.object)
self_post = UserAsking.objects.get(title=self.object)
post_slug = UserAsking.objects.get(ask_slug=self_post.ask_slug)
context['summation'] = post_slug.likes.count() - post_slug.dislikes.count()
context['comment_form'] = CommentForm
comments_count = Comment.objects.filter(userasking=UserAsking.objects.get(title=self.object))
context['comments_count'] = comments_count.count()
context['is_liked'] = False
context['is_dislike'] = False
# context to like the post
if LikePost.as_view():
if post_slug.dislikes.filter(username=self.request.user).exists():
context['is_liked'] = False
elif post_slug.likes.filter(username=self.request.user).exists():
context['is_liked'] = True
else:
context['is_liked'] = False
# context to dis-like the post
if DisLikePost.as_view():
if post_slug.likes.filter(username=self.request.user).exists():
context['is_dislike'] = False
elif post_slug.dislikes.filter(username=self.request.user).exists():
context['is_dislike'] = True
else:
context['is_dislike'] = False
return context
def post(self, request, user_slug, *args, **kwargs):
my_question = UserAsking.objects.get(ask_slug=user_slug)
userprof = UserProfile.objects.get(userasking__ask_slug=user_slug)
comment_form = CommentForm(request.POST, instance=request.user)
name = "%s %s" % (self.request.user.first_name, self.request.user.last_name)
username = self.request.user.username
logo = self.request.user.userprofile.logo.url
c = CommentForm(self.request.POST).add_error('comment', 'error')
if comment_form.is_valid():
comment_form = Comment.objects.create(comment=self.request.POST.get('comment', None),
userasking_id=my_question.id,
userprofile_id=userprof.id,
name=name,
username=username,
logo=logo,
comment_slug=my_question.ask_slug
)
comment_form.save()
return redirect('community:question_view', comment_form.userasking.ask_slug)
return render(request, 'community/question_view.html', {'comment_form': comment_form,
'c': c})
# Like post function
class LikePost(View, SingleObjectMixin):
template_name = 'community/question_view.html'
def post(self, request, *args, **kwargs):
post = get_object_or_404(UserAsking, ask_slug=request.POST.get('post_slug'))
if post.dislikes.filter(username=request.user).exists():
post.dislikes.remove(request.user)
post.likes.add(request.user)
elif post.likes.filter(username=request.user).exists():
post.likes.remove(request.user)
else:
post.likes.add(request.user)
return redirect(post.get_absolute_url())
# Dislike post function
class DisLikePost(View, SingleObjectMixin):
def post(self, request, *args, **kwargs):
post = get_object_or_404(UserAsking, ask_slug=request.POST.get('post_dislike_slug'))
if post.likes.filter(username=request.user).exists():
post.likes.remove(request.user)
post.dislikes.add(request.user)
elif post.dislikes.filter(username=request.user).exists():
post.dislikes.remove(request.user)
else:
post.dislikes.add(request.user)
return redirect(post.get_absolute_url())
at this moment, I add a condition on the view I already handle as you see above in the QuestionDetail model.
I want to add description text from users profile page to description column in my database, but when I submit form nothing happens and this column still empty.
I can get id and email on profile page after login, but can not get description form to my profile method
This is my database structure
login method:
#app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM users.data WHERE email = %s AND password = %s',
(email, password))
account = cur.fetchone()
if account:
session['loggedin'] = True
session['id'] = account[0]
session['email'] = account[3]
return redirect(url_for('profile'))
else:
return render_template('error.html')
return render_template('login.html')
profile method:
#app.route('/profile', methods=['GET','POST'])
def profile():
if 'loggedin' in session:
return render_template('profile.html', id=session['id'], email=session['email'])
if request.method == 'POST':
description = request.form['text']
cur = mysql.connection.cursor()
cur.execute('UPDATE users.data SET description = %s WHERE id = ?', (description, session['id']))
mysql.connection.commit()
cur.close()
return render_template('profile.html', id=session['id'], email=session['email'], description=description)
else:
return 'NO'
return redirect(url_for('login'))
profile.html:
your session id is: {{ id }}
your session email is: {{ email }}
your session symptom is: {{ description }}
<form action="" method="post">
<input type="text" name="text" class="form-control" placeholder="description">
<button class="btn btn-primary">Add</button>
</form>
Please assist.
I found an answer:
#app.route('/profile', methods=['GET','POST'])
def profile():
if request.method == 'GET':
if 'loggedin' in session:
return render_template('profile.html', id=session['id'], email=session['email'])
elif request.method == 'POST':
description = request.form['description']
print(description)
cur = mysql.connection.cursor()
# cur.execute('INSERT INTO users.data(description) VALUES (%s)', (description))
cur.execute('UPDATE users.data SET description = %s WHERE id = %s', (description, session['id']))
mysql.connection.commit()
cur.close()
print(description)
return render_template('profile.html', description=description)
else:
return 'NO'
return redirect(url_for('login'))
I am using repl.it, and also the webbrowser module to open a link using webbrowser.open(<link to open>)
But, my link doesn't work. Can you help me with this?
Here is my code:
import webbrowser
webbrowser.open("https://www.daffodilday.com.au/get-involved/register-your-school/", 2)
And a not-so-quick overview of the webbrowser module:
import os, sys, shlex, stat, subprocess, time
__all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"]
class Error(Exception):
pass
_browsers = {}
_tryorder = []
def register(name, klass, instance=None, update_tryorder=1):
_browsers[name.lower()] = [klass, instance]
if update_tryorder > 0:
_tryorder.append(name)
elif update_tryorder < 0:
_tryorder.insert(0, name)
def get(using=None):
if using is not None:
alternatives = [using]
else:
alternatives = _tryorder
for browser in alternatives:
if '%s' in browser:
browser = shlex.split(browser)
if browser[-1] == '&':
return BackgroundBrowser(browser[:-1])
else:
return GenericBrowser(browser)
else:
try:
command = _browsers[browser.lower()]
except KeyError:
command = _synthesize(browser)
if command[1] is not None:
return command[1]
elif command[0] is not None:
return command[0]()
raise Error("could not locate runnable browser")
def open(url, new=0, autoraise=True):
for name in _tryorder:
browser = get(name)
if browser.open(url, new, autoraise):
return True
return False
def open_new(url):
return open(url, 1)
def open_new_tab(url):
return open(url, 2)
def _synthesize(browser, update_tryorder=1):
cmd = browser.split()[0]
if not _iscommand(cmd):
return [None, None]
name = os.path.basename(cmd)
try:
command = _browsers[name.lower()]
except KeyError:
return [None, None]
# now attempt to clone to fit the new name:
controller = command[1]
if controller and name.lower() == controller.basename:
import copy
controller = copy.copy(controller)
controller.name = browser
controller.basename = os.path.basename(browser)
register(browser, None, controller, update_tryorder)
return [None, controller]
return [None, None]
if sys.platform[:3] == "win":
def _isexecutable(cmd):
cmd = cmd.lower()
if os.path.isfile(cmd) and cmd.endswith((".exe", ".bat")):
return True
for ext in ".exe", ".bat":
if os.path.isfile(cmd + ext):
return True
return False
else:
def _isexecutable(cmd):
if os.path.isfile(cmd):
mode = os.stat(cmd)[stat.ST_MODE]
if mode & stat.S_IXUSR or mode & stat.S_IXGRP or mode & stat.S_IXOTH:
return True
return False
def _iscommand(cmd):
if _isexecutable(cmd):
return True
path = os.environ.get("PATH")
if not path:
return False
for d in path.split(os.pathsep):
exe = os.path.join(d, cmd)
if _isexecutable(exe):
return True
return False
class BaseBrowser(object):
"""Parent class for all browsers. Do not use directly."""
args = ['%s']
def __init__(self, name=""):
self.name = name
self.basename = name
def open(self, url, new=0, autoraise=True):
raise NotImplementedError
def open_new(self, url):
return self.open(url, 1)
def open_new_tab(self, url):
return self.open(url, 2)
class GenericBrowser(BaseBrowser):
def __init__(self, name):
if isinstance(name, basestring):
self.name = name
self.args = ["%s"]
else:
self.name = name[0]
self.args = name[1:]
self.basename = os.path.basename(self.name)
def open(self, url, new=0, autoraise=True):
cmdline = [self.name] + [arg.replace("%s", url)
for arg in self.args]
try:
if sys.platform[:3] == 'win':
p = subprocess.Popen(cmdline)
else:
p = subprocess.Popen(cmdline, close_fds=True)
return not p.wait()
except OSError:
return False
class BackgroundBrowser(GenericBrowser):
def open(self, url, new=0, autoraise=True):
cmdline = [self.name] + [arg.replace("%s", url)
for arg in self.args]
try:
if sys.platform[:3] == 'win':
p = subprocess.Popen(cmdline)
else:
setsid = getattr(os, 'setsid', None)
if not setsid:
setsid = getattr(os, 'setpgrp', None)
p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid)
return (p.poll() is None)
except OSError:
return False
class UnixBrowser(BaseBrowser):
raise_opts = None
remote_args = ['%action', '%s']
remote_action = None
remote_action_newwin = None
remote_action_newtab = None
background = False
redirect_stdout = True
def _invoke(self, args, remote, autoraise):
raise_opt = []
if remote and self.raise_opts:
# use autoraise argument only for remote invocation
autoraise = int(autoraise)
opt = self.raise_opts[autoraise]
if opt: raise_opt = [opt]
cmdline = [self.name] + raise_opt + args
if remote or self.background:
inout = file(os.devnull, "r+")
else:
inout = None
setsid = getattr(os, 'setsid', None)
if not setsid:
setsid = getattr(os, 'setpgrp', None)
p = subprocess.Popen(cmdline, close_fds=True, stdin=inout,
stdout=(self.redirect_stdout and inout or None),
stderr=inout, preexec_fn=setsid)
if remote:
time.sleep(1)
rc = p.poll()
if rc is None:
time.sleep(4)
rc = p.poll()
if rc is None:
return True
return not rc
elif self.background:
if p.poll() is None:
return True
else:
return False
else:
return not p.wait()
def open(self, url, new=0, autoraise=True):
if new == 0:
action = self.remote_action
elif new == 1:
action = self.remote_action_newwin
elif new == 2:
if self.remote_action_newtab is None:
action = self.remote_action_newwin
else:
action = self.remote_action_newtab
else:
raise Error("Bad 'new' parameter to open(); " +
"expected 0, 1, or 2, got %s" % new)
args = [arg.replace("%s", url).replace("%action", action)
for arg in self.remote_args]
success = self._invoke(args, True, autoraise)
if not success:
args = [arg.replace("%s", url) for arg in self.args]
return self._invoke(args, False, False)
else:
return True
class Mozilla(UnixBrowser):
raise_opts = ["-noraise", "-raise"]
remote_args = ['-remote', 'openURL(%s%action)']
remote_action = ""
remote_action_newwin = ",new-window"
remote_action_newtab = ",new-tab"
background = True
Netscape = Mozilla
class Galeon(UnixBrowser):
raise_opts = ["-noraise", ""]
remote_args = ['%action', '%s']
remote_action = "-n"
remote_action_newwin = "-w"
background = True
class Chrome(UnixBrowser):
remote_args = ['%action', '%s']
remote_action = ""
remote_action_newwin = "--new-window"
remote_action_newtab = ""
background = True
Chromium = Chrome
class Opera(UnixBrowser):
raise_opts = ["-noraise", ""]
remote_args = ['-remote', 'openURL(%s%action)']
remote_action = ""
remote_action_newwin = ",new-window"
remote_action_newtab = ",new-page"
background = True
class Elinks(UnixBrowser):
remote_args = ['-remote', 'openURL(%s%action)']
remote_action = ""
remote_action_newwin = ",new-window"
remote_action_newtab = ",new-tab"
background = False
redirect_stdout = False
class Konqueror(BaseBrowser):
def open(self, url, new=0, autoraise=True):
if new == 2:
action = "newTab"
else:
action = "openURL"
devnull = file(os.devnull, "r+")
setsid = getattr(os, 'setsid', None)
if not setsid:
setsid = getattr(os, 'setpgrp', None)
try:
p = subprocess.Popen(["kfmclient", action, url],
close_fds=True, stdin=devnull,
stdout=devnull, stderr=devnull)
except OSError:
pass
else:
p.wait()
return True
try:
p = subprocess.Popen(["konqueror", "--silent", url],
close_fds=True, stdin=devnull,
stdout=devnull, stderr=devnull,
preexec_fn=setsid)
except OSError:
pass
else:
if p.poll() is None:
return True
try:
p = subprocess.Popen(["kfm", "-d", url],
close_fds=True, stdin=devnull,
stdout=devnull, stderr=devnull,
preexec_fn=setsid)
except OSError:
return False
else:
return (p.poll() is None)
class Grail(BaseBrowser):
def _find_grail_rc(self):
import glob
import pwd
import socket
import tempfile
tempdir = os.path.join(tempfile.gettempdir(),
".grail-unix")
user = pwd.getpwuid(os.getuid())[0]
filename = os.path.join(tempdir, user + "-*")
maybes = glob.glob(filename)
if not maybes:
return None
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
for fn in maybes:
# need to PING each one until we find one that's live
try:
s.connect(fn)
except socket.error:
# no good; attempt to clean it out, but don't fail:
try:
os.unlink(fn)
except IOError:
pass
else:
return s
def _remote(self, action):
s = self._find_grail_rc()
if not s:
return 0
s.send(action)
s.close()
return 1
def open(self, url, new=0, autoraise=True):
if new:
ok = self._remote("LOADNEW " + url)
else:
ok = self._remote("LOAD " + url)
return ok
def register_X_browsers():
if _iscommand("xdg-open"):
register("xdg-open", None, BackgroundBrowser("xdg-open"))
if "GNOME_DESKTOP_SESSION_ID" in os.environ and _iscommand("gvfs-open"):
register("gvfs-open", None, BackgroundBrowser("gvfs-open"))
if "GNOME_DESKTOP_SESSION_ID" in os.environ and _iscommand("gnome-open"):
register("gnome-open", None, BackgroundBrowser("gnome-open"))
if "KDE_FULL_SESSION" in os.environ and _iscommand("kfmclient"):
register("kfmclient", Konqueror, Konqueror("kfmclient"))
if _iscommand("x-www-browser"):
register("x-www-browser", None, BackgroundBrowser("x-www-browser"))
for browser in ("mozilla-firefox", "firefox",
"mozilla-firebird", "firebird",
"iceweasel", "iceape",
"seamonkey", "mozilla", "netscape"):
if _iscommand(browser):
register(browser, None, Mozilla(browser))
if _iscommand("kfm"):
register("kfm", Konqueror, Konqueror("kfm"))
elif _iscommand("konqueror"):
register("konqueror", Konqueror, Konqueror("konqueror"))
for browser in ("galeon", "epiphany"):
if _iscommand(browser):
register(browser, None, Galeon(browser))
if _iscommand("skipstone"):
register("skipstone", None, BackgroundBrowser("skipstone"))
for browser in ("google-chrome", "chrome", "chromium", "chromium-browser"):
if _iscommand(browser):
register(browser, None, Chrome(browser))
if _iscommand("opera"):
register("opera", None, Opera("opera")).
if _iscommand("mosaic"):
register("mosaic", None, BackgroundBrowser("mosaic")
if _iscommand("grail"):
register("grail", Grail, None)
if os.environ.get("DISPLAY"):
register_X_browsers()
if os.environ.get("TERM"):
if _iscommand("www-browser"):
register("www-browser", None, GenericBrowser("www-browser"))
if _iscommand("links"):
register("links", None, GenericBrowser("links"))
if _iscommand("elinks"):
register("elinks", None, Elinks("elinks"))
if _iscommand("lynx"):
register("lynx", None, GenericBrowser("lynx"))
if _iscommand("w3m"):
register("w3m", None, GenericBrowser("w3m"))
if sys.platform[:3] == "win":
class WindowsDefault(BaseBrowser):
def open(self, url, new=0, autoraise=True):
try:
os.startfile(url)
except WindowsError:
return False
else:
return True
_tryorder = []
_browsers = {}
register("windows-default", WindowsDefault)
iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
"Internet Explorer\\IEXPLORE.EXE")
for browser in ("firefox", "firebird", "seamonkey", "mozilla",
"netscape", "opera", iexplore):
if _iscommand(browser):
register(browser, None, BackgroundBrowser(browser))
if sys.platform == 'darwin':
class MacOSX(BaseBrowser):
def __init__(self, name):
self.name = name
def open(self, url, new=0, autoraise=True):
assert "'" not in url
if not ':' in url:
url = 'file:'+url
new = int(bool(new))
if self.name == "default":
script = 'open location "%s"' % url.replace('"', '%22')
else:
if self.name == "OmniWeb":
toWindow = ""
else:
toWindow = "toWindow %d" % (new - 1)
cmd = 'OpenURL "%s"' % url.replace('"', '%22')
script = '''tell application "%s"
activate
%s %s
end tell''' % (self.name, cmd, toWindow)
osapipe = os.popen("osascript", "w")
if osapipe is None:
return False
osapipe.write(script)
rc = osapipe.close()
return not rc
class MacOSXOSAScript(BaseBrowser):
def __init__(self, name):
self._name = name
def open(self, url, new=0, autoraise=True):
if self._name == 'default':
script = 'open location "%s"' % url.replace('"', '%22')
script = '''
tell application "%s"
activate
open location "%s"
end
'''%(self._name, url.replace('"', '%22'))
osapipe = os.popen("osascript", "w")
if osapipe is None:
return False
osapipe.write(script)
rc = osapipe.close()
return not rc
register("safari", None, MacOSXOSAScript('safari'), -1)
register("firefox", None, MacOSXOSAScript('firefox'), -1)
register("MacOSX", None, MacOSXOSAScript('default'), -1)
if sys.platform[:3] == "os2" and _iscommand("netscape"):
_tryorder = []
_browsers = {}
register("os2netscape", None,
GenericBrowser(["start", "netscape", "%s"]), -1)
if "BROWSER" in os.environ:
_userchoices = os.environ["BROWSER"].split(os.pathsep)
_userchoices.reverse()
for cmdline in _userchoices:
if cmdline != '':
cmd = _synthesize(cmdline, -1)
if cmd[1] is None:
register(cmdline, None, GenericBrowser(cmdline), -1)
cmdline = None
del cmdline
del _userchoices
def main():
import getopt
usage = """Usage: %s [-n | -t] url
-n: open new window
-t: open new tab""" % sys.argv[0]
try:
opts, args = getopt.getopt(sys.argv[1:], 'ntd')
except getopt.error, msg:
print >>sys.stderr, msg
print >>sys.stderr, usage
sys.exit(1)
new_win = 0
for o, a in opts:
if o == '-n': new_win = 1
elif o == '-t': new_win = 2
if len(args) != 1:
print >>sys.stderr, usage
sys.exit(1)
url = args[0]
open(url, new_win)
print "\a"
if __name__ == "__main__":
main()
Can you help me? I mostly know about everything in Python, but still sometimes need quite quaintly a lot of effort.
You can simplify the answer like this:
import webbrowser
webbrowser.open(*website*)
Of course, replace * website * with the site and no need to write the 2.
Then tell me if it works.
And by the way, some online python processor like pythonanywhere do not allow opening all websites.
Instead, they only allow some specific websites.
This is my models.py
class Cfituser(models.Model):
user = models.OneToOneField(User)
socialid = models.IntegerField(null=True)
accesstoken = models.CharField(max_length=255L, null = True)
class Meta:
db_table = 'CfitUser'
def __str__(self):
return "%s's profile" % self.user
#receiver(post_save, sender=User)
def create_cfituser(sender, instance, created, **kwargs):
if created:
Cfituser.objects.get_or_create(user=instance)
This is my views.py
#api_view(['GET', 'POST'])
def users_create(request, format = None):
"""
List all users, or create a new user.
"""
if request.method == 'GET':
cfituser = Cfituser.objects.all()
serializer = CfituserSerializer(cfituser, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = CfituserSerializer(data=request.DATA)
if serializer.is_valid():
print serializer.data
user = User.objects.create_user(username = serializer.data['socialid'])
cfituser = Cfituser.objects.get(user = user)
cfituser.accesstoken = serializer.data['accesstoken']
cfituser.socialid = serializer.data['socialid']
cfituser.save()
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Whenever there is a HTTP Post request, my database tables are filled in as expected but this error keeps popping up. I've tried almost every solution available on SO but I'm stuck with this.
I have tried user = models.OneToOneField(User, null = True) but this leads to two entries in my database table, one with user_id = NULL and one with user_id = actualvalue.
Any suggestions on how to fix this?
Saving by default commits the entry to the database, to prevent that, pass commit=False to save(), and then do your customizations.
serializer = serializer.save(commit=False)
user, created = User.objects.get_or_create(username = serializer.socialid)
cfituser, created = Cfituser.objects.get_or_create(user = user)
# cfituser.user = user This line is unnecessary
cfituser.accesstoken = serializer.accesstoken
cfituser.socialid = serializer.socialid
cfituser.save()
serializer.save()
You are also duplicating your efforts because your signal will also attempt to create a user. If you are on django 1.5, use customized user model; and for social registration/oauth, use django-social-auth.
OneToOneField means, in Cfituser.user the reverse side of the relation will directly return a single object(user.cfituser gives Cfituser). SO Cfituser.user must be unique through out the table(one and only one).
class Cfituser(models.Model):
user = models.OneToOneField(User)
socialid = models.IntegerField(null=True)
accesstoken = models.CharField(max_length=255L, null = True)
def __unicode__(self):
return "%s's profile" % self.user.username
def users_create(request, format = None):
"""
List all users, or create a new user.
"""
if request.method == 'GET':
cfituser = Cfituser.objects.all()
serializer = CfituserSerializer(cfituser, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = CfituserSerializer(data=request.DATA)
if serializer.is_valid():
print serializer.data
user = User.objects.create_user(username = serializer.data['socialid'])
Cfituser(user = user,accesstoken = serializer.data['accesstoken'],socialid = serializer.data['socialid']).save()
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)