passing a parameter through CreateView to a be an initial value in a form

2020-02-19 Thread Sam Hefer
Hey Patric,

Have a look at stackoverflow.

 https://stackoverflow.com/a/60273100/7063031

I used form_valid in the createview to get the form instance field, passed the 
pk through the URL to the template, then used get_context  in the view so the 
template can get the pk from the URL. You’ll understand better when you use it 
and play around with it.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e34e9ef6-9af8-4c6f-8bbf-29f64342c880%40googlegroups.com.


Re: [ANN] copernic v0.0.0

2020-02-19 Thread Amirouche Boubekki


On Monday, February 17, 2020 at 11:13:38 PM UTC+1, Amirouche Boubekki wrote:
>
> I am very pleased to announce that I will work on porting my work on a 
> versioned database (read: scalable wikidata) to Python and Django.
>
> If you want to know more and follow the development watch this: 
> https://github.com/amirouche/copernic
>


I put together the basic building blocks: generic tuple store and the 
versioned generic tuple store. The tests pass, however the absence of 
proof, is not the proof of the absence, so there might be bugs. Anyway, I 
added two issues:

- How to convert wordnet rdf into the format that will be accepted by 
copernic: https://github.com/amirouche/copernic/issues/11

- Another one about more about how the versioned and change request happen: 
https://github.com/amirouche/copernic/issues/10

It is still no possible to add changes from the web ui, but here is some 
screenshot: https://functional.cafe/@zig/103686859595640820

This project has the power the change the "Quatery industry" also known as 
the knowledge industry.  The gist of the idea I want to demonstrate is how 
to apply the pull-request mechanic on any structured data.  That idea, is 
applied directly to the creation and maintenance of a knowledge base, but 
it could be applied on most or any B2B or B2C products.

The installation on at least on ubuntu 18.04, is straight forward, follow 
the instructions at: https://www.foundationdb.org/download/#ubuntu

Then pip install -r requirements.txt

And the rest is usual django stuff. I recommend you read nstore.py and 
vnstore.py. The UI is defined in frontend app.

Happy hacking!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9ef0df90-daf8-4107-884e-d021c7fb6777%40googlegroups.com.


passing a parameter through CreateView to a be an initial value in a form

2020-02-19 Thread Patrick Carra
Hello I am trying to pass a value from a link into CreateView and use that 
value as an inital value in a form.  I am not having much success and am 
not sure that I am doing this correctly.  Here is what I have so far:
Link:
Circuit Ref: {{ record.id1 }}

urls.py
path('addXC//', views.addXC.as_view(), name='addXC'),

views.py
class addXC(CreateView):
model = Xcinventorytable
fields = ['circuitref', 'circuitid', 'vendor', 'legacy', 'address', 
'city', 'state', 'ciopsticket', 'notes']
success_url="/thanks/xcadded/"


def get_form_kwargs(self):
kwargs=super(addXC, self).get_form_kwargs()
kwargs.update({'circuitref': circuitref})
return kwargs

forms.py
class XcinventorytableForm(ModelForm):
class Meta:
model = Xcinventorytable
widgets = {'notes': forms.TextInput(attrs={'size':200, 'rows':2})}
help_texts = {'Circuitref': ('Enter the circuitref listed at the 
top of the last screen')}
fields = '__all__'


def __init__(self, *args, **kwargs):
circuitref = kwargs.pop('circuitref')
super(XcinventoryForm, self).__init__(*args, **kwargs)
self.fields['circuitref'].initial = circuitref


Any help or suggestions are appreciated

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/fd729e92-6256-4c3a-84df-79250794d6f6%40googlegroups.com.


Re: Django queryset result and mysql query are wrong after updating from 3.0.2 to 3.0.3

2020-02-19 Thread mohamed alisaleh...@gmail.com
بتاريخ الأربعاء، 19 فبراير، 2020 10:51:53 م UTC+3، كتب Ricardo H:
> Hi Simon, 
> 
> 
> It was ok on 2.2.6, only on 3.0.3 it fails.
> 
> 
> I use BigIntegerField because I use it for some calculations after that, but 
> even if I try with DurationField it doens't assert right.
> 
> 
> Definitely must be caused by this patch, if I can't find another solution, 
> where and how should I report this ?.
> 
> 
> Thanks.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1d4386ce-fb0e-4dc5-ae42-3636d9168eed%40googlegroups.com.


Re: Django queryset result and mysql query are wrong after updating from 3.0.2 to 3.0.3

2020-02-19 Thread Simon Charette
Hello Ricardo,

I suggest you follow these docs to submit your bug report and link to this 
thread.

https://docs.djangoproject.com/en/3.0/internals/contributing/bugs-and-features/#reporting-bugs

I'd mention that the issue is also present if you use 
`output_field=DurationField` as BigIntegerField
was likely only working by change.

Cheers,
Simon


Le mercredi 19 février 2020 14:51:53 UTC-5, Ricardo H a écrit :
>
> Hi Simon, 
>
> It was ok on 2.2.6, only on 3.0.3 it fails.
>
> I use BigIntegerField because I use it for some calculations after that, 
> but even if I try with DurationField it doens't assert right.
>
> Definitely must be caused by this patch, if I can't find another solution, 
> where and how should I report this ?.
>
> Thanks.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/0ce21876-4be1-4096-8537-c9d76894dd84%40googlegroups.com.


Re: Re: Re: I am filling up the form but my filled out items are not rendering into database and also the session is not working

2020-02-19 Thread DHRUVA
How can I do ImageField and FileField in crispy forms

On Thu, 20 Feb, 2020, 12:53 AM ,  wrote:

>
>
> Yaa did that still facing issue
>
>
>
> *From: *onlinejudge95 
> *Sent: *Thursday, February 20, 2020 12:32 AM
> *To: *django-users@googlegroups.com
> *Subject: *Re: Re: I am filling up the form but my filled out items are
> not rendering into database and also the session is not working
>
>
>
> The template file
>
>
>
>
>
> <*form **method**="post" **novalidate*>
>
> No action attribute defined here. Where do you expect the data to be sent?
>
>
> {% csrf_token %}
>
>   <*div **class**="form-group col-md-4 mb-0"*>
> {{ form.name|as_crispy_field }}
>   
>   <*div **class**="form-group col-md-4 mb-0"*>
> {{ form.email|as_crispy_field }}
>   
>   <*div **class**="form-group col-md-4 mb-0"*>
> {{ form.link_sent|as_crispy_field }}
>   
> <*button **type**="submit" **class**="btn btn-primary"*>Start
>  <*button **type**="submit" **class**="btn btn-primary"*>Save
>
>   
> {% endblock %}
>
>
>
>
>
> *From: *Farai M 
> *Sent: *Wednesday, February 19, 2020 11:19 PM
> *To: *django-users@googlegroups.com
> *Subject: *Re: I am filling up the form but my filled out items are not
> rendering into database and also the session is not working
>
>
>
> The session must be activated in the settings file check that it should
> work smoothly.
>
> On the insert can u share the template file mostly .It is to do with post
> requests not reaching back end. You can try to print the post request
> before your save to model to see if all inputs are coming through.If it's
> not that try get create to see if it's an problem with duplicates.
>
>
>
>
>
>
>
>
>
>
>
>
>
> *views.py from *django.views.generic *import *FormView, TemplateView
> *from *django.shortcuts *import *render,redirect
> *from *.models *import 
> *modelstep1,modelstep2,modelstep3,modelstep4,modelstep5,modelstep6,modelstep7,modelstep8,modelstep9,modelstep10
> *from *.forms *import 
> *FormStep1,FormStep2,FormStep3,FormStep4,FormStep5,FormStep6,FormStep7,FormStep8,FormStep9,FormStep10
>
> *def *FormStep1View(request):
> forms = FormStep1()
> *return *render(request, *'form_1.html'*, context={*'form'*: forms})
>
>
> *def *addForm1(request):
> form = FormStep1(request.POST)
> *if *form.is_valid():
> u=modelstep1()
> u.name = form.cleaned_data[*'name'*]
> u.email = form.cleaned_data[*'email'*]
> u.link_sent = form.cleaned_data[*'link_sent'*]
> u.title = request.POST.get(*'name'*)
> u.content = request.POST.get(*'email'*)
> u.content = request.POST.get(*'link_sent'*)
> u.save()
> request.session[*'name'*] = u.name
> request.session[*'email'*] = u.email
> request.session[*'link_sent'*] =u.link_sent
> *return *redirect(*'/form/2/'*,context={*'form'*: form})
>
>
>
> *def *FormStep2View(request):
> forms = FormStep2()
> *return *render(request, *'form_2.html'*, context={*'form'*: forms})
> *def *addForm2(request):
> form = FormStep2(request.POST)
> *if *form.is_valid():
>   v=modelstep2()
>   v.country=form.cleaned_data[*'country'*]
>   v.city=form.cleaned_data[*'city'*]
>   v.year_of_birth=form.cleaned_data[*'year_of_birth'*]
>   v.current_grade=form.cleaned_data[*'current_grade'*]
>   v.university=form.cleaned_data[*' university'*]
>   v.school=form.cleaned_data[*'school'*]
>   v.native_language=form.cleaned_data[*'native_language'*]
>   v.phone_number = form.cleaned_data[*'phone_number'*]
>   v.email_business=form.cleaned_data[*'email_business'*]
>   v.social_media=form.cleaned_data[*'social_media'*]
>
>   request.session[*'country'*] = v.country
>   request.session[*'city'*] = v.city
>   request.session[*'year_of_birth'*] = v.year_of_birth
>   request.session[*'current_grade'*] = v.current_grade
>   request.session[*'university'*] = v.university
>   request.session[*'school'*] = v.school
>   request.session[*'native_language'*] = v.native_language
>   request.session[*'phone_number'*] = v.phone_number
>   request.session[*'email_business'*] = v.email_business
>   request.session[*'social_media'*]=  v.social_media
>   *return *redirect(request, *'/form/3/'*, 
> context={*'form'*:form})
>
>
> *def *FormStep3View(request):
> forms = FormStep3()
> *return *render(request, *'form_3.html'*, context={*'form'*: forms})
> *def *addForm3(request):
> form = FormStep3(request.POST)
> *if *form.is_valid():
>x=modelstep3()
>x.internship_idea = form.cleaned_data[*'internship_idea'*]
>x.startup_business = form.cleaned_data[*'startup_business'*]
>x.goals = 

Re: Django queryset result and mysql query are wrong after updating from 3.0.2 to 3.0.3

2020-02-19 Thread Ricardo H
Hi Simon, 

It was ok on 2.2.6, only on 3.0.3 it fails.

I use BigIntegerField because I use it for some calculations after that, 
but even if I try with DurationField it doens't assert right.

Definitely must be caused by this patch, if I can't find another solution, 
where and how should I report this ?.

Thanks.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/0c714166-b3ec-4b58-b574-0effc0fd7f37%40googlegroups.com.


Django: ManyToManyField appears as empty on my template

2020-02-19 Thread Sergio Madueño
I'm having an issue displaying a ManyToManyField in a character profile 
template using Django.

The template has to show an avatar, alongside some information about the 
character, including a list of guilds this character had joined. But, when 
I try to display that list, it appears as if it is empty. I had a look into 
my site administration page, and that information is there, so I have 
confirmation that the data can be displayed in my template. I just don't 
know how. How could I handle that?

These are my models:

""" Modelos de la aplicación de personajes """
from django.db import models


class Guild(models.Model):
""" Modelo del clan """
guild_name = models.CharField(max_length=25)
rank = models.PositiveSmallIntegerField()


def __str__(self):
return self.guild_name


class Character(models.Model):
""" Modelo del personaje """
character_name = models.CharField(max_length=25)
level = models.PositiveSmallIntegerField()
race = models.CharField(max_length=25)
gender = models.CharField(max_length=25)
job = models.CharField(max_length=25)
avatar = models.ImageField(upload_to='', blank=True)
character_guilds = models.ManyToManyField(Guild, blank=True)


def __str__(self):
return self.character_name+': '+self.race+' '+self.job+' level '+str
(self.level)+'. '

My view.py file:

def characterprofile(request, pk):
""" Método para mostrar el perfil de un personaje """
template = '../templates/character/characterProfile.html'
profile = Character.objects.get(pk=pk)
guilds = profile.character_guilds.all()
context = {
'profile': profile,
'guilds': guilds
}
return render (request, template, context)

And my template.html:

{% extends 'base.html' %}


{% block content %}

{{ profile.character_name }}'s profile


Return




{% if profile.avatar %}

{% else %}
There is no avatar to display here.
{% endif %}


Information

Name: {{ profile.character_name 
}}
Level: {{ profile.level }}
Race: {{ profile.race }}
Gender: {{ profile.gender }}
Job: {{ profile.job }}

Guilds: 
{% for g in guilds %} 
{{ g }} 
{%endfor%}






Copyright© 2020

{% endblock %}

Many thanks in advance!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e8ede78e-a01a-4bcf-8895-005af4fd8a60%40googlegroups.com.


Re: How to store a boolean expression (parse tree) in a model?

2020-02-19 Thread Simon Charette
Could you simply make the connector field nullable to express that?

Simon

Le mercredi 19 février 2020 12:15:32 UTC-5, test a écrit :
>
> thanks, do you know how i can create custom leaf nodes when using MPTT or 
> treebeard?
>
> My parent nodes should have connector types such as AND/OR but the child 
> should not
>
>
> On Tuesday, February 18, 2020 at 11:30:40 PM UTC-5, Simon Charette wrote:
>>
>> I suggest you have a look at the "Trees and Graph" section of the
>> Django Packages website[0]. I've personally used MPTT and Treebeard
>> in the past without too much trouble.
>>
>> You could also a field able to store composite data structures
>> such as JSONField or even a dedicated PostgreSQL type[1] to efficiently 
>> store
>> such data.
>>
>> Cheers,
>> Simon
>>
>> [0] https://djangopackages.org/grids/g/trees-and-graphs/
>> [1] https://www.postgresql.org/docs/current/sql-createtype.html
>>
>> Le mardi 18 février 2020 18:13:39 UTC-5, test a écrit :
>>>
>>> Let's say I have:
>>>
>>> Calculator #1:
>>> Expression: (True AND False) AND (True OR False)
>>>
>>> This expression should be a child of some calculator. 
>>>
>>> class Calculator(models.Model):
>>> name = ...
>>>
>>> class Expression(models.Model):
>>> parent = models.ForeignKey(Calculator)
>>>
>>> boolean = AND or OR
>>>
>>> sub_exp1 = models.ForeignKey(Expression)
>>> sub_exp2 = models.ForeignKey(Expression)
>>>
>>>
>>> When I query all the expressions for the Calculator #1, I should get all 
>>> the subexpressions.
>>>
>>> 1 AND 2 5
>>> 2 AND 3 4
>>> 3 leaf node of True 
>>> 4 lead node of False
>>> 5 OR 6 7
>>> 6 leaf node of True
>>> 7 leaf node of False
>>>
>>> From this, I can quickly apply my parse tree.
>>>
>>> How would I display the base case/leaf nodes in my model? Also, is there 
>>> a better way?
>>>
>>> Thanks, I would really appreciate any help
>>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1b1c4b6e-71e7-4613-854c-b96d0028f28b%40googlegroups.com.


Re: Django queryset result and mysql query are wrong after updating from 3.0.2 to 3.0.3

2020-02-19 Thread Simon Charette
Hello Ricardo,

This could be a regression caused by a patch addressing a regression in 
3.0.3[0].

Did you also notice this behaviour on Django 2.2.x or was this project 
started from Django 3.0?

>From what I can see though I find it strange that the ExpressionWrapper of 
end_total_time
have an output_field of BigIntegerField instead of DurationField. That 
could be the origin
of your issue.

Cheers,
Simon

[0] 
https://github.com/django/django/commit/02cda09b13e677db01863fa0a7112dba631b9c5c

Le mercredi 19 février 2020 13:08:57 UTC-5, Ricardo H a écrit :
>
> Hello,  after I updated django from 3.0.2 to 3.0.3 the result of the 
> following code has changed when using a MySQL database. It produces a wrong 
> sql query and also the wrong result for "*end_total_time"* attribute.
> Is this a bug ? also is there any other way to get the wright result using 
> 3.0.3 ?
>
> Thank you.
>
> *models.py*
> from datetime import datetime
> import pytz
>
>
> from django.db import models
> from django.db.models.functions import Cast
>
>
> class PhaseQueryset(models.QuerySet):
>
>
> def with_duration(self,):
> base_date = datetime(2000, 1, 3, 0, tzinfo=pytz.utc)
>
>
> # When I use base_date to do the end_total_time math in 3.0.3 
> together
> # with ended_at annotated, it creates a wrong query
> qs = self.annotate(
> ended_at=models.Case(
> models.When(
> models.Q(type='TYPEONE'),
> then=models.functions.Now()
> ),
> default=models.F('started_at'),
> output_field=models.DateTimeField(),
> ),
> base_date=models.functions.Cast(
> models.Value(base_date),
> output_field=models.DateTimeField()
> ),
> end_total_time=models.ExpressionWrapper(
> models.F('ended_at') - models.F('base_date'),
> output_field=models.fields.BigIntegerField()
> )
> )
>
>
> return qs
>
>
> # Create your models here.
> class Phase(models.Model):
> objects = PhaseQueryset().as_manager()
> started_at = models.DateTimeField()
> type = models.CharField(max_length=40)
>
>
>
> *tests.py*
> from datetime import datetime, timedelta
> import pytz
>
>
> from django.test import TestCase
> from daterror.models import Phase
> # Create your tests here.
>
>
> class TestDateProblem(TestCase):
>
>
> def setUp(self,):
> past = datetime.now(tz=pytz.UTC) - timedelta(days=30)
> Phase.objects.create(started_at=past, type='TYPEONE')
> past = datetime.now(tz=pytz.UTC) - timedelta(days=33)
> Phase.objects.create(started_at=past, type='TYPETWO')
> past = datetime.now(tz=pytz.UTC) - timedelta(days=34)
> Phase.objects.create(started_at=past, type='TYPETHREE')
>
>
>
>
> def test_timedifference_not_none(self,):
> phases = Phase.objects.all().with_duration()
> print(phases[0].end_total_time)
> print(phases[1].end_total_time)
> print(phases[2].end_total_time)
> self.assertNotEqual(None, phases[0].end_total_time)
> self.assertNotEqual(None, phases[1].end_total_time)
> self.assertNotEqual(None, phases[2].end_total_time)
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/4542b03e-797a-4e06-99c2-5ca77ccd4aec%40googlegroups.com.


RE: Re: Re: I am filling up the form but my filled out items are not rendering into database and also the session is not working

2020-02-19 Thread dhruvashah1221999
 Yaa did that still facing issue From: onlinejudge95Sent: Thursday, February 20, 2020 12:32 AMTo: django-users@googlegroups.comSubject: Re: Re: I am filling up the form but my filled out items are not rendering into database and also the session is not working The template file  
No action attribute defined here. Where do you expect the data to be sent? {% csrf_token %} 
    {{ form.name|as_crispy_field }}  div> 
    {{ form.email|as_crispy_field }}  div> 
    {{ form.link_sent|as_crispy_field }}  div>   

Re: Re: I am filling up the form but my filled out items are not rendering into database and also the session is not working

2020-02-19 Thread onlinejudge95
On Wed, Feb 19, 2020 at 11:31 PM  wrote:

> The template file
>
>
>
>
>
> <*form **method**="post" **novalidate*>
>
> No action attribute defined here. Where do you expect the data to be sent?

>
> {% csrf_token %}
>
>   <*div **class**="form-group col-md-4 mb-0"*>
> {{ form.name|as_crispy_field }}
>   
>   <*div **class**="form-group col-md-4 mb-0"*>
> {{ form.email|as_crispy_field }}
>   
>   <*div **class**="form-group col-md-4 mb-0"*>
> {{ form.link_sent|as_crispy_field }}
>   
> <*button **type**="submit" **class**="btn btn-primary"*>Start
>  <*button **type**="submit" **class**="btn btn-primary"*>Save
>
>   
> {% endblock %}
>
>
>
>
>
> *From: *Farai M 
> *Sent: *Wednesday, February 19, 2020 11:19 PM
> *To: *django-users@googlegroups.com
> *Subject: *Re: I am filling up the form but my filled out items are not
> rendering into database and also the session is not working
>
>
>
> The session must be activated in the settings file check that it should
> work smoothly.
>
> On the insert can u share the template file mostly .It is to do with post
> requests not reaching back end. You can try to print the post request
> before your save to model to see if all inputs are coming through.If it's
> not that try get create to see if it's an problem with duplicates.
>
>
>
>
>
>
>
>
>
>
>
>
>
> *views.py from *django.views.generic *import *FormView, TemplateView
> *from *django.shortcuts *import *render,redirect
> *from *.models *import 
> *modelstep1,modelstep2,modelstep3,modelstep4,modelstep5,modelstep6,modelstep7,modelstep8,modelstep9,modelstep10
> *from *.forms *import 
> *FormStep1,FormStep2,FormStep3,FormStep4,FormStep5,FormStep6,FormStep7,FormStep8,FormStep9,FormStep10
>
> *def *FormStep1View(request):
> forms = FormStep1()
> *return *render(request, *'form_1.html'*, context={*'form'*: forms})
>
>
> *def *addForm1(request):
> form = FormStep1(request.POST)
> *if *form.is_valid():
> u=modelstep1()
> u.name = form.cleaned_data[*'name'*]
> u.email = form.cleaned_data[*'email'*]
> u.link_sent = form.cleaned_data[*'link_sent'*]
> u.title = request.POST.get(*'name'*)
> u.content = request.POST.get(*'email'*)
> u.content = request.POST.get(*'link_sent'*)
> u.save()
> request.session[*'name'*] = u.name
> request.session[*'email'*] = u.email
> request.session[*'link_sent'*] =u.link_sent
> *return *redirect(*'/form/2/'*,context={*'form'*: form})
>
>
>
> *def *FormStep2View(request):
> forms = FormStep2()
> *return *render(request, *'form_2.html'*, context={*'form'*: forms})
> *def *addForm2(request):
> form = FormStep2(request.POST)
> *if *form.is_valid():
>   v=modelstep2()
>   v.country=form.cleaned_data[*'country'*]
>   v.city=form.cleaned_data[*'city'*]
>   v.year_of_birth=form.cleaned_data[*'year_of_birth'*]
>   v.current_grade=form.cleaned_data[*'current_grade'*]
>   v.university=form.cleaned_data[*' university'*]
>   v.school=form.cleaned_data[*'school'*]
>   v.native_language=form.cleaned_data[*'native_language'*]
>   v.phone_number = form.cleaned_data[*'phone_number'*]
>   v.email_business=form.cleaned_data[*'email_business'*]
>   v.social_media=form.cleaned_data[*'social_media'*]
>
>   request.session[*'country'*] = v.country
>   request.session[*'city'*] = v.city
>   request.session[*'year_of_birth'*] = v.year_of_birth
>   request.session[*'current_grade'*] = v.current_grade
>   request.session[*'university'*] = v.university
>   request.session[*'school'*] = v.school
>   request.session[*'native_language'*] = v.native_language
>   request.session[*'phone_number'*] = v.phone_number
>   request.session[*'email_business'*] = v.email_business
>   request.session[*'social_media'*]=  v.social_media
>   *return *redirect(request, *'/form/3/'*, 
> context={*'form'*:form})
>
>
> *def *FormStep3View(request):
> forms = FormStep3()
> *return *render(request, *'form_3.html'*, context={*'form'*: forms})
> *def *addForm3(request):
> form = FormStep3(request.POST)
> *if *form.is_valid():
>x=modelstep3()
>x.internship_idea = form.cleaned_data[*'internship_idea'*]
>x.startup_business = form.cleaned_data[*'startup_business'*]
>x.goals = form.cleaned_data[*'goals'*]
>x.established_year = form.cleaned_data[*'established_year'*]
>x.number_of_employees = form.cleaned_data[*'number_of_employees'*]
>x.months = form.cleaned_data[*'months'*]
>x.website = form.cleaned_data[*'website'*]
>x.cell_number_business = 
> form.cleaned_data[*'cell_number_business'*]

Django queryset result and mysql query are wrong after updating from 3.0.2 to 3.0.3

2020-02-19 Thread Ricardo H
Hello,  after I updated django from 3.0.2 to 3.0.3 the result of the 
following code has changed when using a MySQL database. It produces a wrong 
sql query and also the wrong result for "*end_total_time"* attribute.
Is this a bug ? also is there any other way to get the wright result using 
3.0.3 ?

Thank you.

*models.py*
from datetime import datetime
import pytz


from django.db import models
from django.db.models.functions import Cast


class PhaseQueryset(models.QuerySet):


def with_duration(self,):
base_date = datetime(2000, 1, 3, 0, tzinfo=pytz.utc)


# When I use base_date to do the end_total_time math in 3.0.3 
together
# with ended_at annotated, it creates a wrong query
qs = self.annotate(
ended_at=models.Case(
models.When(
models.Q(type='TYPEONE'),
then=models.functions.Now()
),
default=models.F('started_at'),
output_field=models.DateTimeField(),
),
base_date=models.functions.Cast(
models.Value(base_date),
output_field=models.DateTimeField()
),
end_total_time=models.ExpressionWrapper(
models.F('ended_at') - models.F('base_date'),
output_field=models.fields.BigIntegerField()
)
)


return qs


# Create your models here.
class Phase(models.Model):
objects = PhaseQueryset().as_manager()
started_at = models.DateTimeField()
type = models.CharField(max_length=40)



*tests.py*
from datetime import datetime, timedelta
import pytz


from django.test import TestCase
from daterror.models import Phase
# Create your tests here.


class TestDateProblem(TestCase):


def setUp(self,):
past = datetime.now(tz=pytz.UTC) - timedelta(days=30)
Phase.objects.create(started_at=past, type='TYPEONE')
past = datetime.now(tz=pytz.UTC) - timedelta(days=33)
Phase.objects.create(started_at=past, type='TYPETWO')
past = datetime.now(tz=pytz.UTC) - timedelta(days=34)
Phase.objects.create(started_at=past, type='TYPETHREE')




def test_timedifference_not_none(self,):
phases = Phase.objects.all().with_duration()
print(phases[0].end_total_time)
print(phases[1].end_total_time)
print(phases[2].end_total_time)
self.assertNotEqual(None, phases[0].end_total_time)
self.assertNotEqual(None, phases[1].end_total_time)
self.assertNotEqual(None, phases[2].end_total_time)

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/7b25cb7d-f213-486b-95b5-15d438277d01%40googlegroups.com.


RE: Re: I am filling up the form but my filled out items are not rendering into database and also the session is not working

2020-02-19 Thread dhruvashah1221999
The template file      {% csrf_token %}  
    {{ form.name|as_crispy_field }}  div> 
    {{ form.email|as_crispy_field }}  div> 
    {{ form.link_sent|as_crispy_field }}  div>   

RE: Re: I am filling up the form but my filled out items are not rendering into database and also the session is not working

2020-02-19 Thread dhruvashah1221999
 import os# Build paths inside the project like this: os.path.join(BASE_DIR, ...)BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))# Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = 'w(gn#4op(yq4-_@@z0zsw2-!c-ai4#wb48a1y^(ke)y)c1q('# SECURITY WARNING: don't run with debug turned on in production!DEBUG = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'crispy_forms',    'mysite.core',]CRISPY_TEMPLATE_PACK = 'bootstrap4'MIDDLEWARE = [    'django.middleware.security.SecurityMiddleware',    'django.contrib.sessions.middleware.SessionMiddleware',    'django.middleware.common.CommonMiddleware',    'django.middleware.csrf.CsrfViewMiddleware',    'django.contrib.auth.middleware.AuthenticationMiddleware',    'django.contrib.messages.middleware.MessageMiddleware',    'django.middleware.clickjacking.XFrameOptionsMiddleware',]ROOT_URLCONF = 'mysite.urls'TEMPLATES = [    {    'BACKEND': 'django.template.backends.django.DjangoTemplates',    'DIRS': [    os.path.join(BASE_DIR, 'mysite/templates')    ],    'APP_DIRS': True,    'OPTIONS': {    'context_processors': [    'django.template.context_processors.debug',    'django.template.context_processors.request',    'django.contrib.auth.context_processors.auth',    'django.contrib.messages.context_processors.messages',    ],    },    },]WSGI_APPLICATION = 'mysite.wsgi.application'# Database# https://docs.djangoproject.com/en/2.1/ref/settings/#databasesDATABASES = {    'default': {    'ENGINE': 'django.db.backends.sqlite3',    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),    }}# Password validation# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validatorsAUTH_PASSWORD_VALIDATORS = [    {    'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',    },    {    'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',    },    {    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',    },    {    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',    },]# Internationalization# https://docs.djangoproject.com/en/2.1/topics/i18n/LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS, _javascript_, Images)# https://docs.djangoproject.com/en/2.1/howto/static-files/STATIC_URL = '/static/' From: Farai MSent: Wednesday, February 19, 2020 11:19 PMTo: django-users@googlegroups.comSubject: Re: I am filling up the form but my filled out items are not rendering into database and also the session is not working The session must be activated in the settings file check that it should work smoothly.On the insert can u share the template file mostly .It is to do with post requests not reaching back end. You can try to print the post request  before your save to model to see if all inputs are coming through.If it's not that try get create to see if it's an problem with duplicates. On Wed, Feb 19, 2020, 7:33 PM mick  wrote:  views.py from django.views.generic import FormView, TemplateViewfrom django.shortcuts import render,redirectfrom .models import modelstep1,modelstep2,modelstep3,modelstep4,modelstep5,modelstep6,modelstep7,modelstep8,modelstep9,modelstep10from .forms import FormStep1,FormStep2,FormStep3,FormStep4,FormStep5,FormStep6,FormStep7,FormStep8,FormStep9,FormStep10def FormStep1View(request):    forms = FormStep1()    return render(request, 'form_1.html', context={'form': forms})def addForm1(request):    form = FormStep1(request.POST)    if form.is_valid():    u=modelstep1()    u.name = form.cleaned_data['name']    u.email = form.cleaned_data['email']    u.link_sent = form.cleaned_data['link_sent']    u.title = request.POST.get('name')    u.content = request.POST.get('email')    u.content = request.POST.get('link_sent')    u.save()    request.session['name'] = u.name    request.session['email'] = u.email    request.session['link_sent'] =u.link_sent    return redirect('/form/2/',context={'form': form})def FormStep2View(request):    forms = FormStep2()    return render(request, 'form_2.html', context={'form': forms})def addForm2(request):    form = FormStep2(request.POST)    if form.is_valid():  v=modelstep2()  v.country=form.cleaned_data['country']  v.city=form.cleaned_data['city']  v.year_of_birth=form.cleaned_data['year_of_birth']  v.current_grade=form.cleaned_data['current_grade']

Re: I am filling up the form but my filled out items are not rendering into database and also the session is not working

2020-02-19 Thread Farai M
The session must be activated in the settings file check that it should
work smoothly.
On the insert can u share the template file mostly .It is to do with post
requests not reaching back end. You can try to print the post request
before your save to model to see if all inputs are coming through.If it's
not that try get create to see if it's an problem with duplicates.

On Wed, Feb 19, 2020, 7:33 PM mick  wrote:

>
>
>
>
>
>
> views.py from django.views.generic import FormView, TemplateView
> from django.shortcuts import render,redirect
> from .models import 
> modelstep1,modelstep2,modelstep3,modelstep4,modelstep5,modelstep6,modelstep7,modelstep8,modelstep9,modelstep10
> from .forms import 
> FormStep1,FormStep2,FormStep3,FormStep4,FormStep5,FormStep6,FormStep7,FormStep8,FormStep9,FormStep10
>
> def FormStep1View(request):
> forms = FormStep1()
> return render(request, 'form_1.html', context={'form': forms})
>
>
> def addForm1(request):
> form = FormStep1(request.POST)
> if form.is_valid():
> u=modelstep1()
> u.name = form.cleaned_data['name']
> u.email = form.cleaned_data['email']
> u.link_sent = form.cleaned_data['link_sent']
> u.title = request.POST.get('name')
> u.content = request.POST.get('email')
> u.content = request.POST.get('link_sent')
> u.save()
> request.session['name'] = u.name
> request.session['email'] = u.email
> request.session['link_sent'] =u.link_sent
> return redirect('/form/2/',context={'form': form})
>
>
>
> def FormStep2View(request):
> forms = FormStep2()
> return render(request, 'form_2.html', context={'form': forms})
> def addForm2(request):
> form = FormStep2(request.POST)
> if form.is_valid():
>   v=modelstep2()
>   v.country=form.cleaned_data['country']
>   v.city=form.cleaned_data['city']
>   v.year_of_birth=form.cleaned_data['year_of_birth']
>   v.current_grade=form.cleaned_data['current_grade']
>   v.university=form.cleaned_data[' university']
>   v.school=form.cleaned_data['school']
>   v.native_language=form.cleaned_data['native_language']
>   v.phone_number = form.cleaned_data['phone_number']
>   v.email_business=form.cleaned_data['email_business']
>   v.social_media=form.cleaned_data['social_media']
>
>   request.session['country'] = v.country
>   request.session['city'] = v.city
>   request.session['year_of_birth'] = v.year_of_birth
>   request.session['current_grade'] = v.current_grade
>   request.session['university'] = v.university
>   request.session['school'] = v.school
>   request.session['native_language'] = v.native_language
>   request.session['phone_number'] = v.phone_number
>   request.session['email_business'] = v.email_business
>   request.session['social_media']=  v.social_media
>   return redirect(request, '/form/3/', context={'form':form})
>
>
> def FormStep3View(request):
> forms = FormStep3()
> return render(request, 'form_3.html', context={'form': forms})
> def addForm3(request):
> form = FormStep3(request.POST)
> if form.is_valid():
>x=modelstep3()
>x.internship_idea = form.cleaned_data['internship_idea']
>x.startup_business = form.cleaned_data['startup_business']
>x.goals = form.cleaned_data['goals']
>x.established_year = form.cleaned_data['established_year']
>x.number_of_employees = form.cleaned_data['number_of_employees']
>x.months = form.cleaned_data['months']
>x.website = form.cleaned_data['website']
>x.cell_number_business = form.cleaned_data['cell_number_business']
>x.co_founder_details = form.cleaned_data['co_founder_details']
>x.social_media_business = 
> form.cleaned_data['social_media_business']
>x.save()
>request.session['internship_idea'] = x.internship_idea
>request.session['startup_business'] = x.startup_business
>request.session['goals'] = x.goals
>request.session['established_year'] = x.established_year
>request.session['number_of_employees'] = x.number_of_employees
>request.session['months'] = x.months
>request.session['website'] = x.website
>request.session['cell_number_business'] = x.cell_number_business
>request.session['co_founder_details']= x.co_founder_details
>request.session['social_media_business'] = x.social_media_business
>return redirect(request,'/form/4/',context={'form':form})
>
> def FormStep4View(request):
> forms = FormStep4()
> return render(request, 'form_4.html', context={'form': forms})
> def addForm4(request):
>  form = 

I am filling up the form but my filled out items are not rendering into database and also the session is not working

2020-02-19 Thread mick








views.py from django.views.generic import FormView, TemplateView
from django.shortcuts import render,redirect
from .models import 
modelstep1,modelstep2,modelstep3,modelstep4,modelstep5,modelstep6,modelstep7,modelstep8,modelstep9,modelstep10
from .forms import 
FormStep1,FormStep2,FormStep3,FormStep4,FormStep5,FormStep6,FormStep7,FormStep8,FormStep9,FormStep10

def FormStep1View(request):
forms = FormStep1()
return render(request, 'form_1.html', context={'form': forms})


def addForm1(request):
form = FormStep1(request.POST)
if form.is_valid():
u=modelstep1()
u.name = form.cleaned_data['name']
u.email = form.cleaned_data['email']
u.link_sent = form.cleaned_data['link_sent']
u.title = request.POST.get('name')
u.content = request.POST.get('email')
u.content = request.POST.get('link_sent')
u.save()
request.session['name'] = u.name
request.session['email'] = u.email
request.session['link_sent'] =u.link_sent
return redirect('/form/2/',context={'form': form})



def FormStep2View(request):
forms = FormStep2()
return render(request, 'form_2.html', context={'form': forms})
def addForm2(request):
form = FormStep2(request.POST)
if form.is_valid():
  v=modelstep2()
  v.country=form.cleaned_data['country']
  v.city=form.cleaned_data['city']
  v.year_of_birth=form.cleaned_data['year_of_birth']
  v.current_grade=form.cleaned_data['current_grade']
  v.university=form.cleaned_data[' university']
  v.school=form.cleaned_data['school']
  v.native_language=form.cleaned_data['native_language']
  v.phone_number = form.cleaned_data['phone_number']
  v.email_business=form.cleaned_data['email_business']
  v.social_media=form.cleaned_data['social_media']

  request.session['country'] = v.country
  request.session['city'] = v.city
  request.session['year_of_birth'] = v.year_of_birth
  request.session['current_grade'] = v.current_grade
  request.session['university'] = v.university
  request.session['school'] = v.school
  request.session['native_language'] = v.native_language
  request.session['phone_number'] = v.phone_number
  request.session['email_business'] = v.email_business
  request.session['social_media']=  v.social_media
  return redirect(request, '/form/3/', context={'form':form})


def FormStep3View(request):
forms = FormStep3()
return render(request, 'form_3.html', context={'form': forms})
def addForm3(request):
form = FormStep3(request.POST)
if form.is_valid():
   x=modelstep3()
   x.internship_idea = form.cleaned_data['internship_idea']
   x.startup_business = form.cleaned_data['startup_business']
   x.goals = form.cleaned_data['goals']
   x.established_year = form.cleaned_data['established_year']
   x.number_of_employees = form.cleaned_data['number_of_employees']
   x.months = form.cleaned_data['months']
   x.website = form.cleaned_data['website']
   x.cell_number_business = form.cleaned_data['cell_number_business']
   x.co_founder_details = form.cleaned_data['co_founder_details']
   x.social_media_business = form.cleaned_data['social_media_business']
   x.save()
   request.session['internship_idea'] = x.internship_idea
   request.session['startup_business'] = x.startup_business
   request.session['goals'] = x.goals
   request.session['established_year'] = x.established_year
   request.session['number_of_employees'] = x.number_of_employees
   request.session['months'] = x.months
   request.session['website'] = x.website
   request.session['cell_number_business'] = x.cell_number_business
   request.session['co_founder_details']= x.co_founder_details
   request.session['social_media_business'] = x.social_media_business
   return redirect(request,'/form/4/',context={'form':form})

def FormStep4View(request):
forms = FormStep4()
return render(request, 'form_4.html', context={'form': forms})
def addForm4(request):
 form = FormStep4(request.POST)
 if form.is_valid():
y=modelstep4()
y.funding = form.cleaned_data['funding']
y.domain = form.cleaned_data[' domain']
y.stage_business = form.cleaned_data['stage_business']
y.initial_idea = form.cleaned_data['initial_idea']
y.business_plan = form.cleaned_data['business_plan']
y.stage_website = form.cleaned_data['stage_website']
y.presence_on_social = form.cleaned_data['presence_on_social']
y.ventured_registered = form.cleaned_data['ventured_registered']
y.vent_type = form.cleaned_data['vent_type']
y.date_register = 

Re: How to store a boolean expression (parse tree) in a model?

2020-02-19 Thread test
thanks, do you know how i can create custom leaf nodes when using MPTT or 
treebeard?

My parent nodes should have connector types such as AND/OR but the child 
should not


On Tuesday, February 18, 2020 at 11:30:40 PM UTC-5, Simon Charette wrote:
>
> I suggest you have a look at the "Trees and Graph" section of the
> Django Packages website[0]. I've personally used MPTT and Treebeard
> in the past without too much trouble.
>
> You could also a field able to store composite data structures
> such as JSONField or even a dedicated PostgreSQL type[1] to efficiently 
> store
> such data.
>
> Cheers,
> Simon
>
> [0] https://djangopackages.org/grids/g/trees-and-graphs/
> [1] https://www.postgresql.org/docs/current/sql-createtype.html
>
> Le mardi 18 février 2020 18:13:39 UTC-5, test a écrit :
>>
>> Let's say I have:
>>
>> Calculator #1:
>> Expression: (True AND False) AND (True OR False)
>>
>> This expression should be a child of some calculator. 
>>
>> class Calculator(models.Model):
>> name = ...
>>
>> class Expression(models.Model):
>> parent = models.ForeignKey(Calculator)
>>
>> boolean = AND or OR
>>
>> sub_exp1 = models.ForeignKey(Expression)
>> sub_exp2 = models.ForeignKey(Expression)
>>
>>
>> When I query all the expressions for the Calculator #1, I should get all 
>> the subexpressions.
>>
>> 1 AND 2 5
>> 2 AND 3 4
>> 3 leaf node of True 
>> 4 lead node of False
>> 5 OR 6 7
>> 6 leaf node of True
>> 7 leaf node of False
>>
>> From this, I can quickly apply my parse tree.
>>
>> How would I display the base case/leaf nodes in my model? Also, is there 
>> a better way?
>>
>> Thanks, I would really appreciate any help
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/75510047-05c3-4f66-ade8-f76c4866f249%40googlegroups.com.


Re: NoReverseMatch() error while learning Python

2020-02-19 Thread Jorge Gimeno
On Wed, Feb 19, 2020 at 4:47 AM DamnGeniuses' Squad <
andhikaravelen...@gmail.com> wrote:

> NoReverseMatch at /polls/1/
>
> Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: 
> ['polls/(?P[0-9]+)/vote/$']
>
> Request Method: GET
> Request URL: http://127.0.0.1:8000/polls/1/
> Django Version: 3.0.3
> Exception Type: NoReverseMatch
> Exception Value:
>
> Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: 
> ['polls/(?P[0-9]+)/vote/$']
>
> Exception Location: 
> C:\Users\Andhika\AppData\Local\Programs\Python\Python38\lib\site-packages\django\urls\resolvers.py
> in _reverse_with_prefix, line 677
> Python Executable:
> C:\Users\Andhika\AppData\Local\Programs\Python\Python38\python.exe
> Python Version: 3.8.1
> Python Path:
>
> ['E:\\TestingKetiga-2\\mysite',
>  
> 'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
>  'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
>  'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38\\lib',
>  'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38',
>  'C:\\Users\\Andhika\\AppData\\Roaming\\Python\\Python38\\site-packages',
>  
> 'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
>
> Server time: Wed, 19 Feb 2020 09:56:21 +
> Error during template rendering
>
> In template E:\TestingKetiga-2\mysite\polls\templates\polls\detail.html,
> error at line *5*
> Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried:
> ['polls/(?P[0-9]+)/vote/$']
> 1 {{ question.question_text }}
> 2
> 3 {% if error_message %}{{ error_message }}{%
> endif %}
> 4
> 5 
> 6 {% csrf_token %}
> 7 {% for choice in question.choice_set.all %}
> 8  value="{{ choice.id }}">
> 9 {{ choice.choice_text
> }}
> 10 {% endfor %}
> 11 
> 12 
> Please help me fix this , i want to learn more about Django , but i
> already searching for 3 hours but got no solution yet
> Thankyouu
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/b5374455-e259-4ac7-b16d-2b55c8dd6924%40googlegroups.com
> 
> .
>

Would you be able to show us your polls/urls.py and your mysite/urls.py
please?

-Jorge

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CANfN%3DK-v801hrCxQ%2B6Em_Wfu%3D5p8ZYw9xZHOoA_jN7x3Y0_WFg%40mail.gmail.com.


NoReverseMatch at /sitemap.xml

2020-02-19 Thread Yash Garg
When i'm loading sitemap.xml for my site i'm getting this error 


Reverse for 'blog-detail' with arguments '('This is my title slug', '2020', 
'2', '19')' not found. 1 pattern(s) tried: 
['blog\\/(?P[0-9]+)\\/(?P[0-9]+)\\/(?P[0-9]+)\\/(?P[-a-zA-Z0-9_]+)$']

sitemap.py 

class BlogSitemap(Sitemap):
priority = 0.5
changefreq = 'daily'

def  items(self):
return Blog.objects.filter(status=1)

def location(self, item):
return reverse('blog-detail', args = (item.slug, 
str(item.blog_published_at.year), str(item.blog_published_at.month), 
str(item.blog_published_at.day)))

Models.py
class Blog(models.Model):

STATUS = (
(0,"Draft"),
(1,"Publish")
)

blog_title = models.CharField(_("Blog Title For Slug"), 
validators=[MinLengthValidator(8)], max_length=120, blank=False,null=False)
title = models.CharField(_("Blog Title"), 
validators=[MinLengthValidator(8)], max_length=120, blank=True,null=False)
slug = models.SlugField(_("Slug"), max_length=200, unique = True, blank = 
True)
meta_tag = models.TextField(_("Blog Meta tags"), null = False, blank= True)
banner_text = models.CharField(_("Top Banner Text Overlay"), max_length = 
50, null = False)
banner_image = models.FileField(_("Banner Image"), blank=True)
blog_abstract = models.TextField(_("Blog Abstract"), max_length= 500, blank 
= False, null = False)
blog_published_at = models.DateField(_("Blog published date") , blank = 
False, default = timezone.now)
blog_image = models.FileField(_("Blog Image"), blank=True)
def __str__(self):
return self.title

class Meta:
ordering = ['-blog_published_at']
db_table = '"public_blog"'

def get_absolute_url(self):
return reverse('blog-detail', args=(self.slug, 
self.blog_published_at.year, self.blog_published_at.month, 
self.blog_published_at.day))

def save(self):
super(Blog, self).save()
self.slug = slugify(self.blog_title)
super(Blog, self).save()
urls.py 

path('sitemap.xml', sitemap, {'sitemaps':sitemaps}, name = 'sitemap'),

How can i resolve this issue?

Thank You

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c11845b6-475e-4f91-ae8a-54164af9234a%40googlegroups.com.


djoser and custom user model

2020-02-19 Thread Emmanuel klutse
Hello team,
I need help with understanding how djoser and custom user model works
better.
Problem breakdown
First, I’m trying to manage my system users. I want to implement customers,
employees, and admin as users in the system. I want to know if I should
create a separate table in my DB for employees after setting staff=true in
my custom user model.
Can you help me understand what it means and how to use staff=true to
create an employee system user?

Secondly, I want the token to be generated on creating a user but that too
is not happening.
Note: I can create a token for a user via the admin interface.
Attached are some of my project files.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAAw18mB12Wj2YCrvmJFQbPX%3DAm-g4Wh7-ngDWZehhGBDgFq%3DKw%40mail.gmail.com.
from django.contrib import admin
from .models import MyUser

# Register your models here.
admin.site.register(MyUser)
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin


# Create your models here.
class MyUserManager(BaseUserManager):
def create_user(self, email, username, password=None, is_active=True, is_admin=False, is_staff=False,
**extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError("The Email must be set")
if not username:
raise ValueError("The Username must be set")
if not password:
raise ValueError("The Password must be set'")

user_obj = self.model(email=self.normalize_email(email))

user_obj.set_password(password)
user_obj.username = username
user_obj.email = email
user_obj.active = is_active
user_obj.admin = is_admin
user_obj.staff = is_staff
user_obj.save(using=self._db)
return user_obj

def create_staff(self, email, username, password=None, **extra_fields):

myuser = self.create_user(email=email, username=username, password=password, is_staff=True)
myuser.active = True
myuser.staff = True
myuser.save(using=self._db)
return myuser

def create_superuser(self, email, password, username, **extra_fields):
myuser = self.create_user(email=email, username=username, password=password, is_staff=True, is_admin=True,
  **extra_fields)
myuser.active = True
myuser.staff = True
myuser.admin = True
myuser.save(using=self._db)
return myuser


class MyUser(AbstractBaseUser):
email = models.EmailField(max_length=60, unique=True)
username = models.CharField(max_length=60, unique=True)
phone = models.CharField(null=True, max_length=15)
first_name = models.CharField(max_length=60, null=True)
last_name = models.CharField(max_length=60, null=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'phone', 'first_name', 'last_name', 'is_admin', 'is_staff']

objects = MyUserManager()

def __str__(self):
return self.email + ',' + self.username

def has_perm(self, perm, obj=None):
return self.admin

def has_module_perms(self, app_label):
return True

@property
def is_staff(self):
return self.staff

@property
def is_admin(self):
return self.admin

@property
def is_active(self):
return self.active
from rest_framework import serializers
from djoser.serializers import UserCreateSerializer
from .models import MyUser
from rest_framework.authtoken.models import Token


class MyUserCreateSerializer(UserCreateSerializer):
class Meta(UserCreateSerializer.Meta):
model = MyUser
fields = '__all__'


# class MyUserSerializer(serializers.ModelSerializer):
# class Meta:
# model = MyUser
# fields = '__all__'
# extra_kwargs = {'password': {'write_only': True, 'required': True}}
#
# def create(self, validated_data):
# user = MyUser.objects.create_user(**validated_data)
# user.is_active = True
# Token.objects.create(user=user)
# return user
from django.urls import path
from django.conf.urls import include
from rest_framework.routers import DefaultRouter
from rest_framework import routers

# from .views import MyUserViewSet
from rest_framework.authtoken.views import obtain_auth_token

router = routers.DefaultRouter()
# router.register('myusers', MyUserViewSet)

urlpatterns = [
path('', 

Help on passing model field as function argument

2020-02-19 Thread Saswat Ray
Hi All,

*Views.py :*
class DASDataViewSet(viewsets.ModelViewSet):
queryset = DASData.objects.all()
serializer_class = DASDataSerializer

def create(self, request, *args, **kwargs):
try:
das_data = {
'patient': request.data['patient'],
'hexa_data': request.data['hexa_data'],
'device_id': request.data['device_id'],
}
serializer = DASDataSerializer(data=das_data)
if serializer.is_valid():
serializer.save()
self._numeric_conversion(serializer)
#self._start_monitoring(request.data['patient'])
return Response("Success", status=status.HTTP_201_CREATED)
except DASData.DoesNotExist:
return Response("Failed to persist device data",
status=status.HTTP_400_BAD_REQUEST)

@staticmethod
*def _start_monitoring(patient_id, presentation_mode):# should be like
this*
with open(os.path.join(constants.LOG_DIR, "%s.lck" %
str(patient_id)), 'w+'):
pass
p = Pipeline()
   # p.startmonitor(patient_id)
*p.startmonitor(patient_id, presentation_mode) # should be like
this*
*---*
*models.py:*

class Patients(models.Model):
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
age = models.IntegerField()
height = models.IntegerField()
weight = models.DecimalField(max_digits=5, decimal_places=2)
bmi = models.DecimalField(max_digits=5, decimal_places=2, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
*presentation_mode* = models.CharField(max_length=20,
default='sleeping')

*Doubt :*
In the view.py, i would like to add "presentation_mode" in
p.startmonitor(patient_id) like p.startmonitor(patient_id,
presentation_mode) but "presentation_mode" is the field of Patients model
as shown above but DASDataViewSet we are using "DASData" model.

*How can i fetch "presentation_mode" as argument
to p.startmonitor(patient_id) which is field of Patients model.?*



*Thanks*,
*Saswat*

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAEhPkLFs3imguC4SXahLHy6aM1-sGWc0wu22CTtX553skF%2Bgyg%40mail.gmail.com.


NoReverseMatch() error while learning Python

2020-02-19 Thread DamnGeniuses' Squad
NoReverseMatch at /polls/1/

Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: 
['polls/(?P[0-9]+)/vote/$']

Request Method: GET
Request URL: http://127.0.0.1:8000/polls/1/
Django Version: 3.0.3
Exception Type: NoReverseMatch
Exception Value: 

Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: 
['polls/(?P[0-9]+)/vote/$']

Exception Location: 
C:\Users\Andhika\AppData\Local\Programs\Python\Python38\lib\site-packages\django\urls\resolvers.py
 
in _reverse_with_prefix, line 677
Python Executable: 
C:\Users\Andhika\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.1
Python Path: 

['E:\\TestingKetiga-2\\mysite',
 'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
 'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
 'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38\\lib',
 'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38',
 'C:\\Users\\Andhika\\AppData\\Roaming\\Python\\Python38\\site-packages',
 
'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']

Server time: Wed, 19 Feb 2020 09:56:21 +
Error during template rendering

In template E:\TestingKetiga-2\mysite\polls\templates\polls\detail.html, 
error at line *5*
Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: 
['polls/(?P[0-9]+)/vote/$']
1 {{ question.question_text }} 
2 
3 {% if error_message %}{{ error_message }}{% endif 
%} 
4 
5  
6 {% csrf_token %} 
7 {% for choice in question.choice_set.all %} 
8  
9 {{ choice.choice_text 
}} 
10 {% endfor %} 
11  
12  
Please help me fix this , i want to learn more about Django , but i already 
searching for 3 hours but got no solution yet
Thankyouu

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/b5374455-e259-4ac7-b16d-2b55c8dd6924%40googlegroups.com.


Re: using Django to create/build enterprise e-commerce system

2020-02-19 Thread Mbu Charles
Hello, saw your reply and i was wishing to a favour, i am a young django 
programer and i need some help, working on some projects and with guide 
from people like you will be of great help, so i wantedt could mentor me 
please

On Saturday, February 1, 2020 at 6:13:29 PM UTC+1, Henry Udoye wrote:
>
> I need the following: 
>
> *ENTERPRISE E-COMMERCE APPLICATIONS COMPONENTS OUTLINED OR MENTIONED OR 
> LISTED BELOW AND THE ENTERPRISE E-COMMERCE APPLICATIONS COMPONENTS 
> INTEGRATOR(S) TO PUT OR GLUE THEM TOGETHER.*
>
> Custom web applications (including e-commerce applications or components 
> and/or software development)
>
> Search product or engine or crawler or spider or intelligent agent
>
> Connector or connectivity or connection (to the database)
>
> Database
>
> Analytics or query tool or data modeler
>
> Content creator or aggregator or composition or article or content writer 
> or chief spinner
>
> API Creator
>
> API Integrator or connector
>
> API Manager
>
> Opt-in tool
>
> Auto-responder or auto-responding/ email marketing 
>
> Record tracking tool
>
> Payment method or gateway or payment processing system
>
> Automation and/or scripting creation or generation tool
>
> Auto-posting
>
> Auto-retrieval
>
> Auto-extraction
>
> Auto-blogging and
>
> Custom API server with multiple end points and multiple clients. 
>
> Enterprise E-Commerce Applications Components System Integrator(s).
>
> 14000 to 15000 APIs Catalog or Repository
>
> NOTE: We have all or the entire E-Commerce applications components such 
> that with proper sense of flexibility, extensibility, interoperability, 
> integration and the related these components can be put together as a 
> component-based e-commerce architecture. Given that these components are 
> earmarked, mentioned, outlined and enumerated in the documents and are 
> standard IT products I expect a professional to be able to understand and 
> estimate (time and money) the project.
>
>  
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/259c6d2d-b303-41f4-a53d-f5ec835fb995%40googlegroups.com.


Error while learn by Django Tutorial Chapter 4

2020-02-19 Thread DamnGeniuses' Squad
NoReverseMatch at /polls/1/

Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: 
['polls/(?P[0-9]+)/vote/$']

Request Method: GET
Request URL: http://127.0.0.1:8000/polls/1/
Django Version: 3.0.3
Exception Type: NoReverseMatch
Exception Value: 

Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: 
['polls/(?P[0-9]+)/vote/$']

Exception Location: 
C:\Users\Andhika\AppData\Local\Programs\Python\Python38\lib\site-packages\django\urls\resolvers.py
 
in _reverse_with_prefix, line 677
Python Executable: 
C:\Users\Andhika\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.1
Python Path: 

['E:\\TestingKetiga-2\\mysite',
 'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
 'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
 'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38\\lib',
 'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38',
 'C:\\Users\\Andhika\\AppData\\Roaming\\Python\\Python38\\site-packages',
 
'C:\\Users\\Andhika\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']

Server time: Wed, 19 Feb 2020 09:56:21 +
Error during template rendering

In template E:\TestingKetiga-2\mysite\polls\templates\polls\detail.html, 
error at line *5*
Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: 
['polls/(?P[0-9]+)/vote/$']
1 {{ question.question_text }} 
2 
3 {% if error_message %}{{ error_message }}{% endif 
%} 
4 
5  
6 {% csrf_token %} 
7 {% for choice in question.choice_set.all %} 
8  
9 {{ choice.choice_text 
}} 
10 {% endfor %} 
11  
12 
Please Help me to solve this so i can continue to learn django 
Thankyouu

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/2771238b-8eb6-4ca2-9214-c4d46b630318%40googlegroups.com.