Here is my model:
class Browser(models.Model):
profile_name = models.CharField(max_length=400)
browser_type = (
('fr', 'Firefox'),
('ch', 'Chrome'),
('op', 'Opera'),
('ot', 'Other'),
)
browser_name = models.CharField(choices=browser_type, max_length=2)
device_name = models.CharField(max_length=400)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Bookmark(models.Model):
browser = models.ForeignKey(Browser, on_delete=models.CASCADE, null=True, blank=True)
title = models.TextField()
url = models.TextField()
iv = models.TextField()
salt = models.TextField()
iteration = models.IntegerField(default=1500)
tags = TaggableManager()
I only want to update certain fields, so here is the modelform
class BookmarkFormEdit(ModelForm):
class Meta:
model = Browser
exclude = ('tags', 'browser_name', 'device_name', 'profile_name')
but my problem is, values are not updating as expected . Here is the view:
def bookmark_edit(request, pk=None):
if request.method == 'POST':
bookmark = Bookmark.objects.get(pk=pk)
frm = BookmarkFormEdit(request.POST, instance=bookmark)
print(request.POST.get('iteration')) // printing correct value from front-end
if frm.is_valid():
x = frm.save()
print(x.iteration) // not saving the new value !
return JsonResponse({'status': 'created'})
else:
return JsonResponse({'error': frm.errors})
return render(request, 'bookmark_edit.html', {'pk': pk})
You are incorrectly defined model in the form. You should use Bookmark model instead of Browser.
class BookmarkFormEdit(ModelForm):
class Meta:
model = Bookmark
You may need to define fields to include/exclude as you want for this model.
Related
I want to give a Admin the ability to update the image associated to a Product record. I have an edit class that allows the admin to update various elements of a record all of which are updating correctly except for the image fields. The problem is uploading image is working in Creating but not in Updating.
Model:
class Product(models.Model):
id = models.AutoField(primary_key=True, db_column='product_id')
user = models.ForeignKey(UserProfile, models.CASCADE, blank=True, null=True,db_column='user_id')
category = models.ForeignKey(Category, models.CASCADE, blank=True, null=True)
product_name = models.CharField(max_length=500, blank=True, null=True)
description = models.TextField(null=True, blank=True)
quantity = models.IntegerField(default=0, blank=True, null=True)
unit_price = models.FloatField(blank=True, null=True)
dis_price = models.FloatField(blank=True, null=True, db_column='discount_price')
available_qty = models.PositiveIntegerField(default=0,blank=True, null=True)
created_at = models.DateTimeField(default=datetime.datetime.now())
image1 = models.ImageField(db_column='product_image1', null=True, blank=True, upload_to='media/images/')
image2 = models.ImageField(db_column='product_image2', null=True, blank=True, upload_to='media/images/')
image3 = models.ImageField(db_column='product_image3', null=True, blank=True, upload_to='media/images/')
Serializer :
from .models import Product
#Products Adding Serilaizer
class ad_products(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['category','product_name','description','quantity','unit_price','dis_price','image1','image2','image3']
# Product Updating Serializer
class ad_products_update(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['category','product_name','description','unit_price','dis_price','image1','image2','image3']
Views :
POST
class Admin_products(CreateAPIView):
serializer_class = ad_products
#transaction.atomic
def post(self,request,token):
try:
token1 = KnoxAuthtoken.objects.get(token_key=token)
except:
return Response(status=status.HTTP_404_NOT_FOUND)
user = token1.user_id
usertable = UserProfile.objects.get(id=user)
userdata = usertable.id
if(UserProfile.objects.filter(id=userdata, is_active='True')):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid(raise_exception=True):
productcategory = serializer.validated_data['category']
productname = serializer.validated_data['product_name']
description = serializer.validated_data['description']
quantity = serializer.validated_data['quantity']
unitprice = serializer.validated_data['unit_price']
discountprice = serializer.validated_data['dis_price']
image1 = serializer.validated_data['image1']
image2 = serializer.validated_data['image2']
image3 = serializer.validated_data['image3']
if(Category.objects.filter(category_name__iexact=productcategory)):
tablecategory = Category.objects.get(category_name__iexact=productcategory)
table = Product.objects.create(product_name=productname,
description=description, quantity=quantity, unit_price=unitprice,
dis_price=discountprice,user=usertable, category=tablecategory.id, image1=image1, image2=image2, image3=image3)
return Response("Success", status=status.HTTP_200_OK)
else:
data = {'message': "Category Not Found"}
return Response(data, status=status.HTTP_400_BAD_REQUEST)
else:
data = {"message":'User is in In-Active, please Activate your account'}
return Response(data, status=status.HTTP_406_NOT_ACCEPTABLE)
Image is successfully uploaded to media folder and path is stored in Database.
PUT
class Admin_products_update(CreateAPIView):
serializer_class = ad_products_update
#transaction.atomic
def put(self,request,token,pid):
try:
token1 = KnoxAuthtoken.objects.get(token_key=token)
except:
return Response(status=status.HTTP_404_NOT_FOUND)
user = token1.user_id
usertable = UserProfile.objects.get(id=user)
userdata = usertable.id
if(UserProfile.objects.filter(id=userdata, is_active='True')):
if(Product.objects.filter(user=userdata, id=pid)):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid(raise_exception=True):
category = serializer.validated_data['category']
productname = serializer.validated_data['product_name']
description = serializer.validated_data['description']
unitprice = serializer.validated_data['unit_price']
discountprice = serializer.validated_data['dis_price']
image1 = serializer.validated_data['image1']
image2 = serializer.validated_data['image2']
image3 = serializer.validated_data['image3']
if(Category.objects.filter(category_name__iexact=category)):
cat = Category.objects.get(category_name__iexact=category)
Product.objects.filter(id=pid, user=userdata).update(
category = cat.id, product_name=productname, description=description,
unit_price=unitprice, dis_price=discountprice,image1=image1, image2=image2, image3=image3)
data = {"message":'Product Details Updated successfully'}
return Response(data, status=status.HTTP_200_OK)
else:
data = {'message': "Category Not Found"}
return Response(data, status=status.HTTP_400_BAD_REQUEST)
else:
data = {'message' : "Product Details Not Found"}
return Response(data, status=status.HTTP_404_NOT_FOUND)
else:
data = {"message":'Account is in In-Active, please Activate your account'}
return Response(data, status=status.HTTP_406_NOT_ACCEPTABLE)
When i use Update method image path is storing in DB, but Image is not storing in Media folder.
can anyone have an idea how to solve this issue
<queryset>.update(...) only adds kind of annotations to the queryset and affects only SQL query generation and does not call model.save method. But only model.save operates with model instances and calls field's save method which reaches file storage. A queryset (<model>.objects.filter().update()) cannot not do anything with file storages.
So instead of writing an update query you should instantiate model instance and save it. DRF documentation has examples of implementing serializers which save instances (as model instances, not direct DB update)
You use ModelSerializer which by default does call instance.save in update method implementation thus it is unclear how you got to your implementation. Just follow the docs and let model.save happen.
I want to conditionally display either frequency_input or duration_input fields based on the behavior.recording attribute of the selected behavior.
I have a Trial form that currently displays 3 fields:
behavior_name (foreign Key) dropdown
frequency_input
duration_input
Im not sure if i should the best method to solve this (Javascript or solve in the View)?
Trial Model
class Trial(models.Model):
behavior_name = models.ForeignKey(Behavior, on_delete=models.CASCADE)
client_session = models.ForeignKey(Client_Session, on_delete=models.CASCADE)
frequency_input = models.PositiveIntegerField(default=0, blank=True)
duration_input = models.DurationField(blank=True, default=timedelta(minutes=0))
class Meta:
verbose_name_plural = 'trials'
def __str__(self):
return str(self.id)
Behavior Model
RECORDING_CHOICES = (
('Rate','RATE'),
('Duration','DURATION'),
('Frequency','FREQUENCY')
)
class Behavior(models.Model):
name = models.CharField(max_length=200)
goal = models.CharField(max_length=200)
recording = models.CharField(max_length=10, choices=RECORDING_CHOICES, null=False)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='Active')
def __str__(self):
return self.name
Trial Form
class TrialForm(forms.ModelForm):
class Meta:
model = Trial
fields = ('behavior_name','frequency_input', 'duration_input')
Add Trial View
def add_trial(request, clientsession_id):
client_session = Client_Session.objects.get(id=clientsession_id)
if request.method != 'POST':
form = TrialForm()
else:
form = TrialForm(data=request.POST)
if form.is_valid():
add_trial = form.save(commit=False)
add_trial.client_session = client_session
add_trial.save()
return HttpResponse(status=204, headers={'HX-Trigger': 'trialupdated'})
context = {'client_session': client_session, 'form': form}
return render(request, 'sessions/add_trial.html', context)
I'm lost in django formsets. I tried many variations and none works as I need. Maybe it is a little bit confusing what my models are :)
What do I want to do? I need to create a view that displays all AssessParameters related to KapTSI and my problem is editing fields [assessment_requirements, value, finding]. Maximum what is was able to solve by using formset was editing those fields but how to display only the assessment_requirements those are related to edited parameter and to all parameters? And the bonus if there is a way with using CBV?
Models.py
class AssessParameter(models.Model):
application = models.ForeignKey(Application, on_delete=models.CASCADE, blank=True, null=True)
parameter = models.ForeignKey(Parameter, on_delete=models.DO_NOTHING)
requirement = models.TextField(blank=True)
assessment_requirements = models.ManyToManyField(Requirement, related_name="assessments", blank=True)
value = models.TextField(blank=True, null=True)
finding = models.ForeignKey(Finding, on_delete=models.DO_NOTHING)
note = models.TextField(blank=True)
documents = models.CharField(max_length=1, blank=True)
class KapTsi(models.Model):
title = models.CharField(max_length=150)
number = models.CharField(max_length=20)
tsi = models.ManyToManyField(Standard, related_name="tsis")
def __str__(self):
return f"{self.number} | {self.title}"
class ParameterGroup(models.Model):
title = models.CharField(max_length=150)
kap_tsi = models.ForeignKey(KapTsi, models.DO_NOTHING)
def __str__(self):
return f"{self.kap_tsi} {self.title}"
class Parameter(models.Model):
parameter_group = models.ForeignKey(ParameterGroup, on_delete=models.DO_NOTHING)
title = models.CharField(max_length=255)
standards = models.ManyToManyField(Standard, through="Specification", blank=True)
description = models.TextField(blank=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.title
foms.py
class AssessParameterForm(forms.ModelForm):
class Meta:
model = AssessParameter
exclude = ['parameter', 'requirement', 'application']
AssessmentParameterFormSet = modelformset_factory(AssessParameter, form=AssessParameterForm, extra=0)
last try: views.py
def assessment_group(request, pk, slug, group):
application = Application.objects.get(id=pk)
group = ParameterGroup.objects.get(id=group)
assessments = AssessParameter.objects.filter(application=application).filter(parameter__parameter_group=group)
parameter = Requirement.objects.filter(parameter__parameter_group=group)
formset = AssessmentParameterFormSet(instance=assessments)
# for form in formset:
# form.fields['assessment_requirements'].queryset = parameter
context = {
'application': application,
'formset': formset,
}
return render(request, 'assessment/assessment-group.html', context)
I have a Task model. I want to assign task to multiple users so i have taken ManytoMany relationship. So Django is creating a ManytoMany table but i want to track that which user has completed task and when. So I took intermediary model by using through='TaskComplete'. Now I can not see task_assign_to feild in form. And even i declare in modelForms and submit it gives below error.
Cannot set values on a `ManyToManyField` which specifies an intermediary model. Use audit.TaskComplete's Manager instead.
Now I want that admin selects the user from main form and into intermediary model.
I tried but can not find any solution for this. below is my code. Please guide me how to do it?
My Model:
class Task(models.Model):
task_audit_title = models.ForeignKey(MainAudit,on_delete= models.CASCADE, related_name='audit_title_for_task',verbose_name= ('Audit Title'))
task_subtask_name = models.ManyToManyField(SubTask, related_name='subtask_for_task',verbose_name= ('Subtask Title'))
task_subject = models.CharField(verbose_name= ('Task Subject'),max_length=100,blank=False)
task_description = models.CharField(verbose_name= ('Task Description'),max_length=1000,blank=True)
task_assign_to = models.ManyToManyField(User, related_name='task_assign_to', through='TaskComplete')
task_assign_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name='task_crt_by')
task_deadline = models.DateTimeField(null=True,blank=True)
task_perticulars = models.ManyToManyField(Perticular, related_name='task_perticular', blank=True)
task_created_time = models.DateTimeField(default=timezone.now)
task_modified_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name='task_mod_by', null=True, blank=True)
task_modified_time = models.DateTimeField(null=True,blank=True)
is_del = models.BooleanField(default=0)
class Meta:
permissions = (
("change_temp_delete_task", "Can delete temporarily"),
)
def __str__(self):
return self.task_subject
def get_absolute_url(self):
return reverse('create-task')
class TaskComplete(models.Model):
task_title = models.ForeignKey(Task,on_delete= models.CASCADE, related_name='assigned_task')
is_completed = models.BooleanField(default=0)
task_cmt_by_doer = models.CharField(verbose_name= ('Submit Comment'),max_length=100,blank=True)
completed_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name = 'task_completed_by')
completed_time = models.DateTimeField(null=True,blank=True)
My View:-
class TaskCraeteView(LoginRequiredMixin,SuccessMessageMixin,CreateView):
# permission_required = 'Company.add_company'
model=Task
success_message = " Task Craeted successfully!"
reverse_lazy('create-task')
login_url = 'login'
template_name = 'create-task'
form_class = TaskCreateForm
# fields =[]
def form_valid(self,form):
form.instance.task_assign_by = self.request.user
My traceback my traceback link
My Form
class TaskCreateForm(forms.ModelForm):
class Meta:
model = Task
fields = ['task_audit_title','task_subtask_name','task_subject','task_description',
'task_assign_to','task_deadline','task_perticulars']
I created a form view and when I want to save a form with two modules I see "IntegrityError". Please help, Thank you in advance
class Place(models.Model):
LocalName = models.CharField('Nazwa Lokalu', max_length=200)
slug = models.SlugField('Link', max_length=100, default="")
LocalImg = models.ImageField('Zdjęcie Lokalu',
upload_to='Place/static/locals/img', blank=True, max_length=20000)
LocalAdress = models.CharField('Adres', max_length=500)
LocalNumberPhone = models.CharField('Numer telefonu', max_length=9)
LocalHours = models.TextField(verbose_name='Godziny otwarcia',
max_length=20000)
def get_aboslute_url(self):
return reverse("place:place_create", kwargs={'id': self.id})
class Meta:
verbose_name = "Lokal"
verbose_name_plural = "Lokale"
def __str__(self):
return self.LocalName
class Menu(models.Model):
place = models.ForeignKey(Place, on_delete=models.CASCADE,
related_name="place", default="")
Dinner = models.CharField("Nazwa potrawy",blank=True, default="",
max_length=200)
DinnerComponents = models.CharField("Składniki",blank=True, default="",
max_length=20009)
PizzaPrice = models.CharField("Rozmiar i cena Pizzy",
help_text="np.Mała-10zł", default="", blank=True, max_length=300)
Price = models.DecimalField("Cena",default="00", max_digits=5,
decimal_places=2)
class Meta:
verbose_name = "Menu"
verbose_name_plural = "Menu"
views.py
def create_place(request):
form = PlaceForm()
sub_form = MenuForm()
if request.POST:
form = PlaceForm(request.POST)
sub_form = MenuForm(request.POST)
if form.is_valid() and sub_form.is_valid():
place = form.save(commit=False)
place.location = sub_form.save()
place.save()
context = {
'form': form,
'sub_form': sub_form
}
return render(request, 'posts/layout.html', context)
Forms.py
class PlaceForm(forms.ModelForm):
class Meta:
model = Place
fields = ('LocalName', 'LocalAdress', 'LocalNumberPhone','LocalHours',)
class MenuForm(forms.ModelForm):
class Meta:
model = Menu
fields = ('Dinner','DinnerComponents','DinerCategory', 'Price',)
After filling in the form and clicking submit, an error will appear "NOT NULL constraint failed: posts_menu.place_id"
You have to first save a Place then assign the saved place to the Menu and finally save the menu.
if form.is_valid() and sub_form.is_valid():
place = form.save()
menu = sub_form.save(commit=False)
menu.place = place
menu.save()
That's because a Menu needs a place foreign key otherwise it cannot be saved.
(Note: why do you mix snake_case and CamelCase for your field names? It's terribly difficult to know how your model's properties are called. Python's convention is snake_case for all properties/methods/variables)