These are chat archives for django/django

3rd
Nov 2016
Miracle Ayodele
@iammiracle
Nov 03 2016 02:51
hello guys, i need help with my django form
i created a form using html
and i have been confused on how to go about it
the one i know is {{form}}
but i dont need it now

var = "<form name="form" action="" method="post" role="form">
{% csrf_token %}

              <div class="top-row">
                  <div class="field-wrap">
                      <label>
                        First Name<span class="req">*</span>
                      </label>
                      <input type="text" id="firstname" required autocomplete="off" name="firstname" />
                  </div>

                  <div class="field-wrap">
                      <label>
                        Last Name<span class="req">*</span>
                      </label>
                      <input type="text"  id="lastname" required autocomplete="off" name="lastname"/>
                    </div>
              </div>

</form>";

my model already contains the declaration

model.py

var = "class Registration(models.Model):

firstname = models.CharField(max_length=200)
lastname = models.CharField(max_length=200)";
Miracle Ayodele
@iammiracle
Nov 03 2016 03:00

form.py

var = "class RegistrationForm(forms.Form):

firstname = forms.CharField(label='First Name', max_length=200)
lastname = forms.CharField(label='Last Name', max_length=200)";
Miracle Ayodele
@iammiracle
Nov 03 2016 04:22
view.py
var = "def Registration(request):
context = {}
form = Registration(request.POST or None)
if request.POST:
    if form.is_valid():
        new_member = form.save()
context.update({'form': form})
return render(request, 'index.html', context)";
pls any help/
?
its not showing in mysql database
nd it gives no error'
Simon Frid
@fridiculous
Nov 03 2016 05:47
hey guys, when working with factories, where do you like to put your factory files? in your test folder?
Filip Figiel
@megapctr
Nov 03 2016 07:52
@fridiculous I don't need factories since I discovered model-mommy
It generates random values for required fields. Of course you can specify your own values
@koderNeptune you should pass form data via the data kwarg
Like Registration(data=request.POST)
Simon Frid
@fridiculous
Nov 03 2016 07:57
Yeah I'm using factoryboy
i tend to like it (ussually) because it lets me do custom operations
Simon Frid
@fridiculous
Nov 03 2016 08:04
how does it compare to factory_boy?
Miracle Ayodele
@iammiracle
Nov 03 2016 08:28
it's not working still @megapctr
vaibhav jain
@vaibhav-jain
Nov 03 2016 09:58
@koderNeptune Don't you think the Form Name is RegistrationForm
karry91
@karry91
Nov 03 2016 10:31
hey please help out

raceback:

File "/home/eric/first_project/projectx/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response

  1. response = self.process_exception_by_middleware(e, request)

File "/home/eric/first_project/projectx/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response

  1. response = wrapped_callback(request, callback_args, *callback_kwargs)

File "/home/eric/first_project/mysite/blog/views.py" in post_list

  1. posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')

Exception Type: NameError at /
Exception Value: global name 'Post' is not defined

Filip Figiel
@megapctr
Nov 03 2016 10:32
@karry91 seriously? it's right there: Exception Value: global name 'Post' is not defined
you need to import that thing
@fridiculous you can look at some tests in my project to see model-mommy in action: https://github.com/megapctr/Yak/blob/master/tests/projects/querysets.py
karry91
@karry91
Nov 03 2016 10:34
yea i did that but error keeps popping up :from .models import Post
Filip Figiel
@megapctr
Nov 03 2016 10:35
it should work then, or you should get an ImportError
maybe try reloading the server?
in case the autoreload failed
karry91
@karry91
Nov 03 2016 10:37
@filip let me try that out
karry91
@karry91
Nov 03 2016 10:44
still not working what could be my mistake
Filip Figiel
@megapctr
Nov 03 2016 10:44
are you sure your views have the Post?
karry91
@karry91
Nov 03 2016 10:48

from django.shortcuts import render
from django.utils import timezone
from .models import post

Create your views here.

def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts':post})

hey filip there it is .im trying to load the actual screenshot but i can see no way to load screen shots here instead i have copy pasted
Filip Figiel
@megapctr
Nov 03 2016 10:50
the names are case sensitive
post is not the same as Post
karry91
@karry91
Nov 03 2016 10:51
yap but upon changing it another error pops up
Filip Figiel
@megapctr
Nov 03 2016 10:53
sometimes a different error is progress :)
karry91
@karry91
Nov 03 2016 10:55
@filip ImportError: cannot import name Post
Jorik Kraaikamp
@JostCrow
Nov 03 2016 10:56
Can you show us more of the file?
Filip Figiel
@megapctr
Nov 03 2016 10:56
there you go, your models don't seem to have a Post
karry91
@karry91
Nov 03 2016 11:01
@filip class Post(models.Model): i have it
Filip Figiel
@megapctr
Nov 03 2016 11:02
hmm, is your models.py adjacent to that views.py file?
are they in the same directory?
karry91
@karry91
Nov 03 2016 11:03
yes
Filip Figiel
@megapctr
Nov 03 2016 11:04
this is really getting out of hand
can you show models.py?
karry91
@karry91
Nov 03 2016 11:05

from django.db import models
from django.utils import timezone

class Post(models.Model):
author = models.ForeignKey('auth.user')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)

def publish(self):
self.published_date = timezone.now()
self.save()

def __str__():
    return self.title
Filip Figiel
@megapctr
Nov 03 2016 11:06
everything looks fine here
one more thing you could try is to remove the *.pyc files and restart the server
karry91
@karry91
Nov 03 2016 11:12
sth else i hv rectified now p in Post in admn.py was lower case upon changing the import error rectified but this now

Traceback:

File "/home/eric/first_project/projectx/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response

  1. response = self.process_exception_by_middleware(e, request)

File "/home/eric/first_project/projectx/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response

  1. response = wrapped_callback(request, callback_args, *callback_kwargs)

File "/home/eric/first_project/mysite/blog/views.py" in post_list

  1. posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')

File "/home/eric/first_project/projectx/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method

  1. return getattr(self.get_queryset(), name)(args, *kwargs)

File "/home/eric/first_project/projectx/local/lib/python2.7/site-packages/django/db/models/query.py" in filter

  1. return self._filter_or_exclude(False, args, *kwargs)

File "/home/eric/first_project/projectx/local/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude

  1. clone.query.add_q(Q(args, *kwargs))

File "/home/eric/first_project/projectx/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q

  1. clause, _ = self._add_q(q_object, self.used_aliases)

File "/home/eric/first_project/projectx/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q

  1. allow_joins=allow_joins, split_subq=split_subq,

File "/home/eric/first_project/projectx/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter

  1. lookups, parts, reffed_expression = self.solve_lookup_type(arg)

File "/home/eric/first_project/projectx/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in solve_lookup_type

  1. , field, , lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())

File "/home/eric/first_project/projectx/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in names_to_path

  1. "Choices are: %s" % (name, ", ".join(available)))

Exception Type: FieldError at /
Exception Value: Cannot resolve keyword 'published_date' into field. Choices are: author, author_id, created_date, id, text, title

Filip Figiel
@megapctr
Nov 03 2016 11:14
looks like you've added a new field to the model but didn't migrate your database
there's no published_date column in your db
karry91
@karry91
Nov 03 2016 11:20
i have migrated
Filip Figiel
@megapctr
Nov 03 2016 11:21
you wouldn't be getting this error if you migrated
you have to run manage.py makemigrations and then manage.py migrate
karry91
@karry91
Nov 03 2016 11:22
yap did that for sure
Filip Figiel
@megapctr
Nov 03 2016 11:26
I can't think of anything else, perhaps some else will know what's going on
the last idea would be to remove your database and all migration files and run makemigrations and migrate again
karry91
@karry91
Nov 03 2016 11:49
how do i d it?
Miracle Ayodele
@iammiracle
Nov 03 2016 12:13
@vaibhav-jain even at that, it is still not showing my data in the database and it's not giving error
Filip Figiel
@megapctr
Nov 03 2016 12:19
@koderNeptune try adding some print statements to see what's happening in your code
Miracle Ayodele
@iammiracle
Nov 03 2016 12:26
@megapctr ok, i just added print context and nth was even printing
i guess its not seeing the value yet
do u tink it could because i did not use {{ form }} to display the form
i use html in displaying my form
Filip Figiel
@megapctr
Nov 03 2016 12:34
I think your print was at the top level in the register function
if the print is not showing up, it means your function isn't being run
check if you hooked the correct function in your urls.py
Miracle Ayodele
@iammiracle
Nov 03 2016 12:50
Yo, thanks @megapctr , i figured it out
thank u very much
Filip Figiel
@megapctr
Nov 03 2016 12:51
glad you could make it :)
karry91
@karry91
Nov 03 2016 13:00
to which do i add {{posts}}

To print a variable in Django templates, we use double curly brackets with the variable's name inside, like this:

blog/templates/blog/post_list.html
{{ posts }}
Try this in your blog/templates/blog/post_list.html template. Replace everything from the second <div> to the third </div> with {{ posts }}

Get Python
@getpy_twitter
Nov 03 2016 13:19
Django Weekly Issue 11 is out http://djangoweekly.com/newsletter/no/11/ ... Django Admin customization, Protecting Sensitive Information in Django, Handle GitHub Webhooks Using Django, Auto-Generate Swagger Docs for your Django API and more ... Have a look.
The django under the hood conference is live streaming here https://m.youtube.com/watch?v=rsEkQbMLCH4
Filip Figiel
@megapctr
Nov 03 2016 13:21
:-1:
pkariz
@pkariz
Nov 03 2016 13:35
hi if im doing django rest backend + angular 2 frontend. If i want to send PATCH request to rest api i must include x-csrftoken header (whose value i set to the value of cookie named 'csrftoken' if i understand correctly). When does django give me that cookie though?
Filip Figiel
@megapctr
Nov 03 2016 13:36
@pkariz usually, the cookie is set when you render a django template with a {% csrf_token %} templatetag
pkariz
@pkariz
Nov 03 2016 13:36
if its important im using also the CORS addition to django because backend and frontend are separated
Filip Figiel
@megapctr
Nov 03 2016 13:36
however, you can override it by using a specific decorator on your view
pkariz
@pkariz
Nov 03 2016 13:37
@megapctr yes forgot to mention, its separated, django is only used for REST API, not for displaying templates
Filip Figiel
@megapctr
Nov 03 2016 13:37
oh, in that case I think you can disable CSRF if you're using cors
pkariz
@pkariz
Nov 03 2016 13:37
why?
Filip Figiel
@megapctr
Nov 03 2016 13:37
doesn't cors ensure the requests are coming from a specific address?
(I barely know what cors is :worried: )
anyway, here's how to enforce csrftoken cookie: megapctr/Yak@9164d6f
pkariz
@pkariz
Nov 03 2016 13:38
@megapctr ty :)
btw i think youre right that i dont need csrf
Filip Figiel
@megapctr
Nov 03 2016 13:41
whew :sweat_smile:
csrf protection would effectively restrict you from using the api from a separate client
pkariz
@pkariz
Nov 03 2016 13:42
if i do $.http.get on a webpage then what is the origin?
Filip Figiel
@megapctr
Nov 03 2016 13:43
the page you sent the request from
unless you specify otherwise
pkariz
@pkariz
Nov 03 2016 13:43
but how does that protect u from csrf? u can still give a 'user' an image with an url which starts this code or not?
Filip Figiel
@megapctr
Nov 03 2016 13:45
one solution would be to host your webapp under a subdomain
like api.myapp.io
and set csrf cookie for the main domain
pkariz
@pkariz
Nov 03 2016 13:46
hm so i still need that csrf thingy
Filip Figiel
@megapctr
Nov 03 2016 13:46
in the project I linked to you earlier, i also intended to separate back and frontend, but there was too much shit to take care of in order to do so
I ended up having django render my webapp
karry91
@karry91
Nov 03 2016 16:33
FieldError at /
Cannot resolve keyword 'published_date' into field. Choices are: author, author_id, created_date, id, text, title
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.9
Exception Type: FieldError
Exception Value:
Cannot resolve keyword 'published_date' into field. Choices are: author, author_id, created_date, id, text, title
Exception Location: /home/eric/first_project/projectx/local/lib/python2.7/site-packages/django/db/models/sql/query.py in names_to_path, line 1330
Python Executable: /home/eric/first_project/projectx/bin/python
Python Version: 2.7.12
any one to help with that please
pkariz
@pkariz
Nov 03 2016 16:42
i have django rest api running on 127.0.0.1:8000 and angular app on localhost:4200. anyone knows why do my browsers ignore the cookie im given from the django rest api? heres the cookie:
Set-Cookie:csrftoken=tOCVRk1jagMmc8ON6wC02hf0HDrHLa7fT9cmZMgAc6lbcZTEcmVvcb95DClHhUVH; expires=Thu, 02-Nov-2017 16:23:30 GMT; Max-Age=31449600; Path=/
Alhadie
@muhammadalhadie_twitter
Nov 03 2016 17:32
hello, does anybody understand pipeline?
i don't know how to add my static files onto django pipeline, here is my code:
PIPELINE = {
'PIPELINE_ENABLED': True,
'CSS_COMPRESSOR': 'pipeline.compressors.yuglify.YuglifyCompressor',
'CSSMIN_BINARY': 'cssmin',
'JS_COMPRESSOR': 'pipeline.compressors.yuglify.YuglifyCompressor',
'JAVASCRIPT': {
'bootstrap': {
'source_filenames': (
'twitter_bootstrap/js/transition.js',
'twitter_bootstrap/js/modal.js',
'twitter_bootstrap/js/dropdown.js',
'twitter_bootstrap/js/scrollspy.js',
'twitter_bootstrap/js/tab.js',
'twitter_bootstrap/js/tooltip.js',
'twitter_bootstrap/js/popover.js',
'twitter_bootstrap/js/alert.js',
'twitter_bootstrap/js/button.js',
'twitter_bootstrap/js/collapse.js',
'twitter_bootstrap/js/carousel.js',
'twitter_bootstrap/js/affix.js',
),
'output_filename': 'Help_Desk/js/b.js',
},
},
'STYLESHEETS': {
'bootstrap': {
'source_filenames': (
'twitter_bootstrap/css/bootstrap.css',
),
'output_filename': 'Help_Desk/css/bootstrap.css',
'extra_context': {
'media': 'screen,projection',
},
},
'melon': {
'source_filenames': (
'assets/css/responsive.css',
),
'output_filename': 'Help_Desk/css/melon.css',
'extra_context': {
'media': 'screen,projection',
},
},
},
}
deniskrishna
@deniskrishna
Nov 03 2016 18:21
hello everyone, is there a way to implement generic many-to-many sortable relationship without going mad?
Mark Heppner
@mheppner
Nov 03 2016 18:53
@pkariz I'm pretty sure it's because your browser is treating localhost and 127.0.0.1 as different domains. try using one or the other.
@karry91 it's because your model doesn't have a published_date field. did you misspell it?
@deniskrishna what exactly is making you mad? do you have some sample models?
pkariz
@pkariz
Nov 03 2016 19:00
@mheppner i tried running angular app on 127.0.0.1:4200 also and still didnt work (it doesnt work in chrome and in ff, both ignore the cookie)
do i have to set CSRF_COOKIE_DOMAIN to something specific?
Mark Heppner
@mheppner
Nov 03 2016 19:07
@pkariz you could try explicitely setting it to localhost, and running the angular app on localhost. I’m honestly not sure though. are you sure angular is looking for the correct cookie name?
@pkariz cookies aren’t port-specific, so as long as you run both services on localhost, they should be visible
pkariz
@pkariz
Nov 03 2016 19:10
im not sure what angular actually does, im testing by checking list of cookies in the browser and by running js code to read it
Mark Heppner
@mheppner
Nov 03 2016 19:11
all you should have to do is inject $cookies then use $cookies.get(‘csrftoken’)
pkariz
@pkariz
Nov 03 2016 19:12
im using ng2
i think i might be having this kind of a problem, not sure though:
http://stackoverflow.com/questions/7346919/chrome-localhost-cookie-not-being-set
Mark Heppner
@mheppner
Nov 03 2016 19:13
you said you also had the problem in firefox though
i’d try using this for ng2
pkariz
@pkariz
Nov 03 2016 19:13
to read the cookie?
the same problem was also in other browsers, more info:
http://stackoverflow.com/questions/1134290/cookies-on-localhost-with-explicit-domain
Mark Heppner
@mheppner
Nov 03 2016 19:16
by default, the csrf cookie is set to an empty domain, you havent explicitely set it yet
how are you reading it in your js app?
pkariz
@pkariz
Nov 03 2016 19:18
im reading it from the chrome devtools with a few different getCookie implementations (also the one mentioned in django docs, https://docs.djangoproject.com/es/1.10/ref/csrf/)
Mark Heppner
@mheppner
Nov 03 2016 19:19
go over to the ‘application’ tab in the devtools and look for the cookies on the left. does it exist there?
pkariz
@pkariz
Nov 03 2016 19:20
too bad i cant check it now, dont have access to the code from home :/
Mark Heppner
@mheppner
Nov 03 2016 19:21
hm well feel free to pm once you get access again
pkariz
@pkariz
Nov 03 2016 19:21
ty :)
Ryan Moore
@xHeliotrope
Nov 03 2016 20:10
I need a select distinct query, but it needs to be case insensitive. Something like this, friends = Friend.objects.order_by('name').distinct('name') , but if I had Matt and matt, I'd only want one in my queryset. Is there a django-ey way to do this?
Jourdan Rodrigues
@jourdanrodrigues
Nov 03 2016 20:12
Friend.objects.order_by('name').distinct('name').filter(name__iexact='Matt')
Ryan Moore
@xHeliotrope
Nov 03 2016 20:14
...I mean I'd like to do that over the whole queryset. Like, if I had Matt, matt, Doug, Doug I'd want back a queryset with just Matt, Doug or matt, Doug
Ramon Moraes
@vyscond
Nov 03 2016 23:06
This message was deleted
Quick questions. The "db_constraint" option from the ForeignKey, when it's set to False automatically removes an existent constraint?
pkariz
@pkariz
Nov 03 2016 23:45
@mheppner u think csrf token is needed in my situation? CORS allows rest api calls only from angular2 page so the only thing where i see csrf helping me is if i have some url where as soon as user comes on it some POST/PUT/PATCH/DELETE xhr is called, which imo pages shouldnt be doing it anyway. Am i missing smth? (sry to bother u, just thought i might forget to ask u this tomorrow :P)