I'm trying to code the page so that every user has its userpage where they can add their own info ( in this case YCD data). Now I'm trying to code the add button, with which user will be able to add a note to its personal page.
def add_YCD(request):
current_user = request.user
current_profile = Profile.objects.get(user_id = current_user.id)
if request.method == "POST":
if current_user.is_authenticated:
YCD_form = YCDForm(request.POST, instance = current_profile)
if YCD_form.is_valid():
YCD_form.save()
messages.success(request,('Your profile was successfully updated!'))
else:
messages.error(request,('Unable to complete request'))
return redirect("main:homepage")
YCD_form = YCDForm(instance = current_profile)
return render(request = request,
template_name = "main/add_YCD.html",
context = {"YCD_form": YCD_form,
"user": request.user,})
The code works without instance = current_profile, it just saves the note to database but doesn't display it on the userpage. I've also tried using instance = request.user.profile.
But it doesn't work at all.
Here are the Models themselves:
class Yield_Curve_Data(models.Model):
b1 = models.BigIntegerField()
b2 = models.BigIntegerField()
b3 = models.BigIntegerField()
tau = models.BigIntegerField()
Date = models.DateTimeField('date published', default = datetime.now)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
yield_curve_data = models.ManyToManyField(Yield_Curve_Data, null = True)
#receiver(post_save, sender = User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender = User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
And here's the code for forms:
class YCDForm(forms.ModelForm):
class Meta:
model = Yield_Curve_Data
fields =('b1', 'b2', 'b3', 'tau',)
Is there another way to specify the user itself or o I need to change the code completely?
Thanks
Related
I am trying to display the state values for each country name in Django app. To save the user response, I am using Django generic CreateView. My models look something like this:
class Question(model.Models):
ques_id = models.AutoField(primary_key=True)
country = models.ForeignKey(Country)
state = models.CharField(max_length=...)
class Test(model.Models):
test = models.AutoField(primary_key=True, )
test_num = models.CharField(max_length=6, )
class Response(model.Models):
response = models.AutoField(primary_key=True)
test_id = models.ForeignKey(Test, related_name='test', )
ques_offered = models.ForeignKey(Question, related_name='choice',
ans_submitted = models.CharField(max_length=240,
To display the available choices for field state for each country value (in the db), I am looping through Django management form for the formset in my template. However, I am unable to get to the values of field state instead I am getting the country values.
Additional info:
The views that I am using to achieve this:
class ResponseCreateView(CreateView):
template_name = ...
model = Test
form_class = # Form_name
def get_context_data(self, **kwargs):
data = super(ResponseCreateView, self).get_context_data(**kwargs)
if self.request.POST:
data['get_response'] = responseFormset(self.request.POST, self.request.FILES)
else:
data['get_response'] = responseFormset()
def form_valid(self, form):
context = self.get_context_data()
get_response = context['get_response']
with transaction.atomic():
if get_response.is_valid():
self.object = form.save()
get_response.instance = self.object
get_response.save()
return redirect('...')
else:
context.update({'get_response': get_response,
})
return self.render_to_response(context)
return super(ResponseCreateView, self).form_valid(form)
I keep getting this very same type error even though I am using set. Can someone maybe point out what I'm doing wrong in my api endpoint?
views.py
#require_http_methods(["GET", "POST"])
def api_requerimientos(request):
if request.method == "GET":
requerimientos = FormularioCliente.objects.all()
return JsonResponse(
{"requerimientos": requerimientos},
encoder=FormularioClienteEncoder,
)
elif request.method == "POST":
print("POST REQUEST HIT")
try:
content = json.loads(request.body)
except json.JSONDecodeError:
return HttpResponseBadRequest("Invalid JSON in request body")
requerimiento = FormularioCliente(**content) # Create a new FormularioCliente object
if "technicians" in content and isinstance(content["technicians"], list):
try:
technicians_id_list = content["technicians"]
technicians = Technician.objects.filter(employee_number__in=technicians_id_list)
requerimiento.technicians.set(technicians)
requerimiento.save()
print('requerimiento:', requerimiento)
except Technician.DoesNotExist:
pass
requerimiento.save() # Save the object to the database
models.py
class FormularioCliente(models.Model):
empresa = models.CharField(max_length=21, null=True, unique=True)
titulo = models.CharField(max_length=66)
descripcion = models.CharField(max_length=66)
enlace = models.URLField(null=True)
tipo = models.CharField(max_length=17, choices=TIPO_REQUIRIMIENTO, default="tecnologia")
date = models.DateField(null=True, auto_now_add=True)
time = models.TimeField(null=True, auto_now_add=True)
entrega = models.DateField(null=True)
finished = models.CharField(max_length=19, choices=TIPO_FINALIZACION, default="Abierto")
technicians = models.ManyToManyField(Technician, blank=True)
special_hours = models.SmallIntegerField(default=0)
regular_hours = models.PositiveSmallIntegerField(default=1)
total_hours = models.SmallIntegerField(default=1)
importancia = models.PositiveSmallIntegerField(default=1)
file = models.FileField(upload_to='files', blank=True)
updated = models.DateField(auto_now=True)
def __str__(self):
return f'{self.titulo}: {self.descripcion} # {self.date}'
def technicians_as_json(self):
return list(self.technicians.all().values())
class Technician(models.Model):
name = models.TextField()
employee_number = models.SmallIntegerField(unique=True, primary_key=True)
def __str__(self):
return self.name + " - " + str(self.employee_number)
encoders.py
class TechnicianEncoder(ModelEncoder):
model = Technician
properties = ["name", "employee_number"]
class FormularioClienteEncoder(ModelEncoder):
model = FormularioCliente
properties = [
"id",
"empresa",
"titulo",
"descripcion",
# "user",
"enlace",
# "tipo",
# "File",
"tipo",
"date",
"time",
"entrega",
"finished",
"technicians", # <-- Add this
"special_hours",
"regular_hours",
"total_hours",
"importancia",
"updated",
]
encoders = {"technicians": TechnicianEncoder()}
I also tried to loop through technicians queryset and add it to the instance one by one as well via the add() method but that also didn't work.
I even tried this:
techs = list(requerimiento.technicians.filter(employee_number__in=technicians_id_list).all())
requerimiento.technicians.set(techs)
None of it worked
I have an application that has a dropdown menu among other things.
The menu is created based on the requirements. I wrote a query that checks the statuses and calculates how many requirements are in a given status. Then he builds a menu out of it. However, I have a problem because sometimes a requisition has been created but no items have been added to it. In that case, my menu shows this as one of the items. This is not what he expects. I would like the query to return and count only those requirements in a given status that have children.
Below I paste the model code and inquiries.
class D_DemandStatus(ModelBaseClass):
status = models.CharField(max_length=20, unique=True)
name = models.CharField(max_length=50)
created_user = models.ForeignKey(User, on_delete=models.PROTECT)
def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.pk:
user = None
if not self.pk:
self.created_user = user
self.modified_by = user
super(D_DemandStatus, self).save(*args, **kwargs)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Demand status'
verbose_name_plural = 'Demands status'
class Demand(models.Model):
name = models.CharField(max_length=500)
status = models.ForeignKey(D_DemandStatus, default=3, on_delete=models.PROTECT, )
insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False)
insert_date = models.DateTimeField(default=datetime.datetime.now, editable=False)
def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.pk:
user = None
if not self.pk:
self.insert_user = user
self.status = D_DemandStatus.objects.get(status='PREPARED')
self.modified_by = user
super(Demand, self).save(*args, **kwargs)
def __str__(self):
return self.name
def submitt(self, *args, **kwargs):
if self.pk :
dict_status = D_DemandStatus.objects.get(status='WAITING')
print(dict_status)
self.demanddetails_set.filter(demand_id = self.pk).update(status=dict_status)
self.status = dict_status
self.save()
def status_actualize(self, *args, **kwargs):
if self.pk :
dict_status = D_DemandStatus.objects.get(status='ORDERED')
items_status = DemandDetails.objects.filter(demand=self.pk).values('status').distinct()
if len(items_status) == 1 and items_status[0]['status'] == dict_status.id :
self.status = D_DemandStatus.objects.get(status='ORDERED')
#elif len(items_status) > 1 :
# self.status = D_DemandStatus.objects.get(status='INPROGRESS')
self.save()
class Meta:
verbose_name = 'Demand'
verbose_name_plural = 'Demands'
class DemandDetails(models.Model):
demand = models.ForeignKey(Demand, on_delete=models.CASCADE, related_name='items')
component = models.ForeignKey(Component, on_delete=models.CASCADE)
order_item = models.ForeignKey(OrderItem, null=True, on_delete=models.PROTECT, editable=False, related_name='demand_details_item')
quantity = models.IntegerField(default=1)
comment = models.CharField(max_length=150, blank=True)
status = models.ForeignKey(D_DemandStatus, default=3, on_delete=models.PROTECT, )
insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False)
insert_date = models.DateTimeField(auto_now_add=True)
def quantityUpdate(self, val):
if self.pk :
self.quantity = val
self.save()
def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.pk:
user = None
if not self.pk:
self.insert_user = user
self.status = D_DemandStatus.objects.get(status='PREPARED')
if not self.pk:
try:
super(DemandDetails, self).save(*args, **kwargs)
except IntegrityError as e:
obj = DemandDetails.objects.get(demand_id=self.demand_id, component_id=self.component_id)
obj.quantity = obj.quantity + 1
obj.save()
else:
super(DemandDetails, self).save(*args, **kwargs)
def __str__(self):
return self.demand.name
class Meta:
verbose_name = 'Demand detail'
verbose_name_plural = 'Demand details'
constraints = [
models.UniqueConstraint(fields=['demand_id', 'component_id'], name='epm - DemandDetail (demand, component)' )
]
The query that works now looks like this:
demand_list = Demand.objects.values('status__name', 'status__id', 'status__status').annotate(count=Count('status__name')).filter(Q(status__status='WAITING') | Q(status__status='PREPARED')).order_by('-status__name')
In this case, however, even if the demand is empty (no items added), it is counted as 1
So I have changed the code a little, but it doesn't work as I would like, because it also counts the individual elements of the demand - which is obvious, because the query returns the subsequent rows that are counted.
demand_list = Demand.objects.values('status__name', 'status__id', 'status__status').annotate(count=Count('status__name'), piece=Count('demanddetails')).filter(Q(piece__gte=1)).filter(Q(status__status='WAITING') | Q(status__status='PREPARED')).order_by('-status__name')
I need to write the query in such a way that I get a list of statuses with numbers of demands only which have derived elements in DemandDetails. If a Demand exists but has no derived elements then it is not taken into account - rather it is counted as 0. This is important because in the extreme case there may be only one Demand which is empty and then I want to have information about it in the menu but with the number 0.
I hope I have managed to write clearly what I chaie.
Please help me to create a suitable query.
Regards
I have a Wagtail site where every group can work on a different page tree, with different images and documents permissions.
That is a multisite setup where I am trying to keep sites really separate.
Is that possible to limit the snippets permissions on a per-group basis?
I would like my groups to see just a subset of the snippets.
I was facing something similar when I wanted to use Site settings.
The only solution I found was to create a custom model and using ModelAdmin.
Some ‘snippets’ to get you on the run:
class SiteSettings(models.Model):
base_form_class = SiteSettingsForm
COMPANY_FORM_CHOICES = (
('BED', 'Bedrijf'),
('ORG', 'Organisatie'),
('STI', 'Stichting'),
('VER', 'Vereniging'),
)
site = models.OneToOneField(
Site,
unique = True,
db_index = True,
on_delete = models.CASCADE,
verbose_name = _('site'),
related_name = 'site_settings',
help_text = _('The sites these setting belong to.')
)
company_name = models.CharField(
_('company name'),
blank = True,
max_length = 50,
help_text = _('De naam van het bedrijf of de organisatie.')
)
company_form = models.CharField(
_('company form'),
max_length = 3,
blank = True,
default = 'COM',
choices = COMPANY_FORM_CHOICES
)
...
class MyPermissionHelper(PermissionHelper):
def user_can_edit_obj(self, user, obj):
result = super().user_can_edit_obj(user, obj)
if not user.is_superuser:
user_site = get_user_site(user)
result = user_site and user_site == obj.site
return result
class SiteSettingsAdmin(ThumbnailMixin, ModelAdmin):
model = SiteSettings
menu_label = _('Site settings')
menu_icon = 'folder-open-inverse'
add_to_settings_menu = True
list_display = ['admin_thumb', 'company_name', 'get_categories']
list_select_related = True
list_display_add_buttons = 'site'
thumb_image_field_name = 'logo'
thumb_col_header_text = _('logo')
permission_helper_class = MyPermissionHelper
create_view_class = CreateSiteSettingsView
...
class CreateSiteSettingsView(SiteSettingsViewMixin, CreateView):
#cached_property
def sites_without_settings(self):
sites = get_sites_without_settings()
if not sites:
messages.info(
self.request,
_('No sites without settings found.')
)
return sites
def dispatch(self, request, *args, **kwargs):
if request.user.is_superuser and not self.sites_without_settings:
return redirect(self.url_helper.get_action_url('index'))
return super().dispatch(request, *args, **kwargs)
def get_initial(self):
initial = super().get_initial().copy()
current_site = self.request.site
initial.update({
'company_name': current_site.site_name}
)
if self.request.user.is_superuser:
initial.update({
'site': current_site}
)
return initial
def get_form(self):
form = super().get_form()
flds = form.fields
if self.request.user.is_superuser:
fld = form.fields['site']
fld.queryset = self.sites_without_settings.order_by(
Lower('site_name')
)
return form
def form_valid(self, form):
instance = form.save(commit=False)
if not self.request.user.is_superuser:
instance.site = self.request.site
instance.save()
messages.success(
self.request, self.get_success_message(instance),
buttons=self.get_success_message_buttons(instance)
)
return redirect(self.get_success_url())
This is a continuation of this question
What follows is an abbreviated version of the original code. I tried to include the most relevant parts and left out the part of the script used by a cron job which updates the Datastore with values.
Then, in the sendFollowUp() handler, a second cron job queries the Datastore for these values, then uses a push task queue to send these values as parameters which are ultimately used in a REST API call to another service that sends people(entities) in the Datastore an email.
What I can't figure out is how to follow-up a get request with a post request in the same handler without submitting a post request through a form. This needs to happen within the sendFollowUp handler. Most of the examples I have found include submitting a form. However, I don't want to do that. I just want it to work automatically with the cron job and task queue.
import webapp2
import datetime
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import taskqueue
import jinja2
import os
jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
class emailJobs(db.Model):
""" Models an a list of email jobs for each user """
triggerid = db.StringProperty() #Trig id
recipientid_po = db.StringProperty() # id
recipientlang = db.StringProperty() #Language
fu_email_sent = db.DateTimeProperty()
fuperiod = db.IntegerProperty() # (0 - 13)
fu1 = db.DateTimeProperty()
fu2 = db.DateTimeProperty()
#classmethod
def update_fusent(cls, key_name, senddate):
""" Class method that updates fu messages sent in the GAE Datastore """
emailsjobs = cls.get_by_key_name(key_name)
if emailsjobs is None:
emailsjobs = cls(key_name=key_name)
emailsjobs.fu_email_sent = senddate
emailsjobs.put()
def timeStampFM(now):
d = now.date()
year = d.year
month = d.month
day = d.day
t = now.time()
hour = t.hour
minute = t.minute + 5
second = t.second
today_datetime = datetime.datetime(year, month, day, hour, minute, second)
return today_datetime
class MainPage(webapp2.RequestHandler):
""" Main admin login page """
def get(self):
if users.get_current_user():
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
urla = '/'
url_admin = ""
if users.is_current_user_admin():
url = users.create_logout_url(self.request.uri)
urla = "_ah/admin/"
url_admin = 'Go to admin pages'
url_linktext = 'Logout'
else:
url = users.create_login_url(self.request.uri)
url_linktext = 'Login'
template_values = {
'url': url,
'url_linktext': url_linktext,
'url_admin': url_admin,
'urla': urla,
}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
class sendFollowUp(webapp2.RequestHandler):
""" Queries Datastore for fu dates that match today's date, then adds them to a task queue """
def get(self):
now = datetime.datetime.now()
now_dt = now.date() #today's date to compare with fu dates
q = emailJobs.all()
q.filter('fuperiod >', 0)
q.filter('fuperiod <', 99)
for part in q:
guid = str(part.recipientid_po)
lang = str(part.recipientlang)
trigid = str(part.triggerid)
if part.fuperiod == 1:
fu1rawdt = part.fu1
fu1dt = fu1rawdt.date()
if fu1dt == now_dt:
follow_up = '1'
if part.fuperiod == 2: # the values go up to 12 in the original code
fu2rawdt = part.fu2
fu2dt = fu2rawdt.date()
if fu2dt == now_dt:
follow_up = '2'
if follow_up != None:
taskqueue.add(queue_name='emailworker', url='/emailworker', params={'guid': guid,
'fu': follow_up,
'lang': lang,
'trigid': trigid,
})
self.redirect('/emailworker')
class pushQueue(webapp2.RequestHandler):
""" Sends fu emails, updates the Datastore with datetime sent """
def store_emails(self, trigid, senddate):
db.run_in_transaction(emailJobs.update_fusent, trigid, senddate)
def get(self):
fu_messages = {'1': 'MS_x01',
'2': 'MS_x02',
# the values go up to 12 in the original code
}
langs = {'EN': 'English subject',
'ES': 'Spanish subject',
}
fu = str(self.request.get('fu'))
messageid = fu_messages[fu]
lang = str(self.request.get('lang'))
subject = langs[lang]
now = datetime.datetime.now()
senddate = timeStampFM(now)
guid = str(self.request.get('guid'))
trigid = str(self.request.get('trigid'))
data = {}
data['Subject'] = subject
data['MessageID'] = messageid
data['SendDate'] = senddate
data['RecipientID'] = guid
# Here I do something with data = {}
self.store_emails(trigid, senddate)
app = webapp2.WSGIApplication([('/', MainPage),
('/cron/sendfu', sendFollowUp),
('/emailworker', pushQueue)],
debug=True)
I'm not sure I really understand your question, but can't you just create a POST request with the requests module?
Post Requests
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
Also for easy task use have you seen the deferred library?
The deferred library lets you bypass all the work of setting up dedicated task handlers and serializing and deserializing your parameters by exposing a simple function, deferred.defer(). To call a function later, simply pass the function and its arguments to deferred.defer
Link