Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I cannot go to the page I want
Hello I have a post blog where I have a homepage with posts and if you click on it you are redirected to the post_detail page. Now I want the users to allow to delete their comments which I achieved but I want them to stay on the same post_detail page. I could not come over it and hope that someone can help me. Thanks in advance. post_detail.html <div class="container"> <br> <h1 style="text-align:center;">{{post.post}} </h1> <p style="font-size:small;text-align:center;">{{post.created_on}}</p> <button type="button" class="btn btn-secondary float-right" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Yorum At</button> <br> <br> <br> {% for i in commentmodel_list%} <h4 >{{i.comment}}</h4> {% if i.author_security == user%} <a style="float:right;color:red;"href="{% url 'forum:delete' slug=post.slug comment_id=i.id %}"><i class="fas fa-minus-circle"></i></a> {% endif %} {% if i.author is none %} <p style="font-size:small;">Anonim | {{i.created_on}}</p> {% else%} <p style="font-size:small;"><a style="text-decoration:none;" href="#">@{{i.author}}</a> | {{i.created_on}}</p> {% endif %} <hr> <br> {% endfor %} </div> urls.py app_name='forum' urlpatterns=[ path('', views.PostList.as_view(), name='post'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('delete/<slug:slug>/<comment_id>/',views.delete_post,name='delete') ] views.py def delete_post(request,slug=None,comment_id=None): comment_delete=Comment.objects.get(id=comment_id) comment_delete.delete() post = Post.objects.get(slug=slug) return redirect('forum:post_detail', slug= post) -
render author name from text model as foreignkey in django
I want to render the author of each post to the template in my models.py file class User(AbstractBaseUser): email = models.EmailField(verbose_name="Email", max_length=250, unique=True) date_joined = models.DateTimeField(verbose_name='Date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='Last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) full_name = models.CharField(verbose_name="Full name" ,max_length=150, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] objects = MyAccountManager() def __str__(self): return self.full_name # For checking permissions. def has_perm(self, perm, obj=None): return self.is_admin # For which users are able to view the app (everyone is) def has_module_perms(self, app_label): return True class Text(models.Model): title = models.CharField(max_length=200, null=True) document = models.TextField(max_length=None, null=True) requirements = models.TextField(max_length=200, null=True) date_created = models.DateField(auto_now_add=True ,null=True) deadline = models.DateField(null=True) author = models.ForeignKey(User ,on_delete=models.CASCADE,null=True) def __str__(self): return self.title NB: i want to render it in the home page so here is my home view def home(request): user = request.user form = TextForm() if request.method == "POST": form = TextForm(request.POST) if form.is_valid(): obj = form.save(commit=False) author = User.objects.filter(email=user.email).first() obj.author = author form.save() form = TextForm() texts = Text.objects.all().order_by('-id') context = {'form':form,'texts':texts} return render(request,'main/home.html' ,context) i want to do something like author_name = Text.author.full_name and then render author_name to the template i'm not sure if this is how to do … -
Deleting a value from a field of model in django
I am working on basic ecommerce website in django.I am having the following view that checks for a successful order. def handlerequest(request, id): order=Order.objects.get(id=id) items=order.orderitem_set.all() verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': order.save() print('order successful') else: order.dstatus="Cancelled" order.save() return render(request, 'handlerequest.html', {'response': response_dict,'order':order}) The items here refer to the products that a user has chosen to buy.My product models is as below with size model.(I have removed some fields) class Siz(models.Model): size=models.CharField(max_length=3,null=True,blank=True) class Product(models.Model): name=models.CharField(max_length=10) size=models.ManyToManyField(Siz) What I have done is that in my siz model I have added several sizes(eg. S,L,M) and for product I have selected the sizes which are available for each product. Now my concern is that whenever someone orders something then after checking in the view that the order is successful , I want to remove the size of the item ordered from the product.(For Example if someone orders a product AB of size L then from available size of that product I want to remove L) The following is my orderitem and order model for reference. class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True) complete=models.BooleanField(default=False,null=True,blank=False) class OrderItem(models.Model): product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True) order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True,) size=models.ForeignKey(Siz,on_delete=models.SET_NULL,null=True) I also want to keep in mind that if there are multiple items that a … -
Django: Create a form for another other user existing in DB. ('Users' object has no attribute 'get')
I'm creating a cloud panel for our cloud Database, and I'm having some issues by creating a form for other users and rendering it. This is my forms.py from django.forms import ModelForm from main.models import Users class UsersForm(ModelForm): class Meta: model = Users fields = '__all__' exclude = ['last_login'] And then inside the views.py, I'm trying to create a form for other user with: form = UsersForm(model) return render(request, 'service_desk/ticket_list_edit.html', {'form': form}) I'm trying to pass in the user model to the form, but as you can see I'm getting an error -
Ajax success function not working: Django JSONResponse not sending
In the code below, I am using onclick (I know it may not be the best practice but for my particular situation I think it works best) to activate an ajax call to dynamically update the content on my Django template. As of now, the data is going to the back-end, and the Comment object is being created. However, when returning a JSONResponse, the template is not using the data from this JSONResponse to update the page in any way. I have tried testing with alerts but to no avail. I am new to JS so I would love a little help! Thank you very much. Django View: def sochome(request, oid): society = Society.objects.filter(id=oid).first() membership = SocietyMembership.objects.get(member=request.user, society=society) response_data = {} if request.method == 'POST': postID = request.POST.get('post_id') comment_content = request.POST.get('comment') response_data['post_id'] = postID response_data['comment'] = comment_content post = SocPost.objects.filter(id=postID).first() SocComment.objects.create(post=post, author=request.user, content=comment_content) # print(response_data, file=sys.stderr) # print("SUCCESS JSON RESPONSE TO CLIENT SIDE", file=sys.stderr) return JsonResponse(response_data) context = { 'membership': membership, 'posts': society.posts.all().order_by('-date_posted') } return render(request, 'blog/sochome.html', context) HTML: < script type = "text/javascript" > function update_comment(post_id) { $.ajax({ type: 'POST', url: "{% url 'blog-sochome' oid=membership.society.id%}", data: { 'post_id': post_id, 'comment': document.getElementById(post_id.toString()).value }, dataType: 'text', success: function(data) { alert("ajax completed … -
Reverse for 'update_profile' not found. 'update_profile' is not a valid view function or pattern name
I hope you're well. Just one question that's been bothering me a lot lately... I got the issue only when I update my form. The update works after refreshing the page. views.py in user folder #update detail @method_decorator(login_required(login_url='/earlycooker/login/'),name="dispatch") class UserProfileUpdateView(UpdateView): model = UserProfile template_name = 'profile-update.html' form_class = UserProfileForm success_message = "Profile updated" def form_valid(self, form): form.instance.user = self.request.user form.save() return super(UserProfileUpdateView, self).form_valid(form) def get_success_url(self): return reverse('update_profile',kwargs={'slug':self.object.slug}) def get(self,request,*args,**kwargs): self.object = self.get_object() if self.object.user != request.user: return HttpResponseRedirect('/') return super(UserProfileUpdateView, self).get(request,*args,**kwargs) urls.py in user folder path('details/<slug:slug>/', UserProfileUpdateView.as_view(), name="update_profile"), profile-update.html in user folder {% url 'user:update_profile' slug=user.userprofile.slug %} -
Django Monolithic vs Microservices
I always had this doubt and want to clear it up. Django architecture is somewhat similar to microservices architecture in the sense all the apps in a Django project are isolated which is the same case in Microservices architecture. If one app fails, it doesnt affect other apps. So is it fair considering a Monolithic Django App to be a Microservices architecture? -
Custom Registration form in django shows "This field is required" even when it's filled
I have created a multiform Registration form but even when I type in all the details it says "This field is required". I have not used {{ form }}. Instead I have used fields for the input. register.html: {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <small>{{ error }}</small> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <small>{{ error }}</small> </div> {% endfor %} {% endif %} <div class="center"> <div class="form_outer"> <form method="POST"> {% csrf_token %} <div class="page slidePage"> <div class="field"> <div class="label">Username*</div> <input type="text" name="username" id="username" class="form-control"> </div> <div class="field"> <div class="label">Firstname*</div> <input type="text" name="username" id="first_name" class="form-control"></div> </div> <div class="field"> <div class="label">Lastname*</div> <input type="text" name="username" id="last_name" class="form-control"></div> </div> <div class="field"> <button type="button" class="nxt nextBtn-1">NEXT</button> </div> </div> <div class="page"> <div class="field"> <div class="label">Email</div> <input type="text" name="email" id="email" class="form-control"> </div> <div class="field"> <div class="label">Password</div> <input type="password" name="password1" id="password1" class="form-control"></div> </div> <div class="field"> <div class="label">Password Confirmation</div> <input type="password" name="password2" id="password2" class="form-control"></div> </div> <div class="field buttons"> <button type="button" class="prev-1 prev">BACK</button> <button type="submit" class="submit">SUBMIT</button> </div> </div> </form> </div> </div> forms.py: class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') class Meta: … -
Pre_Save reciever not updating item's stock
I have a cart item model and I want it to decrease the stock when the ordered field is set to true but I don't think I'm doing it right. CartItem model: class CartItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) size = models.ForeignKey(Size, on_delete=models.CASCADE, null=True) quantity = models.IntegerField(default=1) My Pre_save receiver: @receiver(pre_save, sender=CartItem) def decrease_stock_receiver(sender, instance, *args, **kwargs): if instance.ordered is True: print("check stock: " + str(instance.size.stock)) instance.size.stock -= instance.quantity print("decrease stock: " + str(instance.size.stock)) -
Connect call failed ('127.0.0.1', 6379)
I am creating simple chat server by following this tutorial here https://channels.readthedocs.io/en/latest/tutorial/part_2.html ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 6379) can any helpmeout for this I saw one of the solutions "Try changing 127.0.0.1:6379 to redis:6379" in Docker [Errno 111] Connect call failed ('127.0.0.1', 6379) but did not understand how to do that Thank you in advance -
How to avoid 2 equal loopings | Django
I got this code: i = 1 for item in cart: data_ps[f"itemId{i}"] = item data_ps[f"itemDescription{i}"] = item.category.name data_ps[f"itemAmount{i}"] = item.sell_price data_ps[f"itemQuantity{i}"] = '1' i += 1 total_value = format(((shipping_price + cart_price) / installment), '.2f') data_ps['installmentValue'] = total_value response = requests.post('https://ws.sandbox.pagseguro.uol.com.br/v2/transactions', headers=headers, params=params, data=data_ps) if response.status_code == 200: for item in cart: Sell.objects.create(item=item, date=timezone.now(), discount=Decimal(0.00), total_paid=cart.get_total_price(), buyer=request.user, ) As you can see, there are 2 for item in cart loop. After the first one, I need to get a request.post and then check if the status_code is equal 200. If so, the code gerenates another for item in cart loop. I was wondering if there is a way to avoid the second looping adding all this information inside the first one, because it just update a record in my database ('Sell.objects.create'). Any idea? Thank you -
How to load spesific data with ajax in django?
I was want to learn "how ajax working on django ?" so I found this project from web and started the working on this https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html I got something from that project but reverse engineering is did not work :/ When I run the project of this link and create a person was everything ok, like if I do not write the firstname as required input ajax gives me an eror. My button is too should working like this. But later when I wrote my own code block and pressed the (mydata) button I did not get an eror or something so I think ajax did not work and I do not know why Script.js This script is in the document.ready function $('#mydata').on('click', function(){ $firstname = $('#firstname').val(); if($firstname == ""){ alert("Please complete the required field"); }else{ $.ajax({ url: 'mydata', type: 'POST', data: { firstname: $firstname, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function(response){ console.log('working!') $('#result').html(response); } }); } }); Views.py def mydata(request): firstname = request.GET.get('firstname') members = Member.objects.filter(firstname=firstname) context = {'member': members} return render(request, 'crud/index.html', context) index.html <form class="form-inline"> {% csrf_token %} <div class="form-group"> <label>Firstname</label> <input type="text" id="firstname" class="form-control" style="width:30%;" required="required"/> <label>Lastname</label> <input type="text" id="lastname" class="form-control" style="width:30%;" required="required"/> <button type="button" id="create" class="btn btn-sm btn-primary">Create</button> … -
Record user IP address in Django During Development, not 127.0.0.1
Using Django 3.0.8, I am trying to record a user's IP address during development to ensure my database isn't spammed by multiple submissions from the same IP Address. I am currently using Django's in-built request.META.get("REMOTE_ADDR") as per the Django docs, but this only returns the 127.0.0.1 when I print out to the terminal. Is there a more robust way to obtain the IPv4/IPv6 address during development? -
Django model class relationships
I'm trying to map out the relationship between my models and before I spend to much time creating the form to create the objects on the client side I want to check it's the most efficient way of doing so. I am creating form that allows me to create a Workout. Each Workout consists of multiple exercises. However, I want the ability to be able to group exercises into Sets (Supersets). So you can either perform one exercise on its own OR 2 or 3 exercises back to the group. e.g. Workout Exercise: 1 Sets 4 Reps 12 Exercise: 2 Sets 3 Reps 10 Superset: 3 Exercise a Exercise b Sets 4 Reps 3 Exercise: 4 Sets 4 Reps 3 I current Have a Workout class with a ManyToMany to my Set class, which then has a ManyToMany to the Exercise Class. Each exercise needs to have sets and reps etc. However, something doesn't feel right about creating a 'Set' object, then assigning exercises to it. Especially when creating a single exercise object. My models currently look like the following: class Workout(models.Model): title = models.CharField(max_length=50) account = models.ForeignKey("customer.Account", on_delete=models.PROTECT) date_created = models.DateField(_('Creation date'), auto_now_add=True) set_of_exercises = models.ManyToManyField("gym.Set", blank=True) def __str__(self): … -
Is there a way in django to automatically create model objects
Hello, recently I have been using django-allauth for external auth ... But I have a question is there a way were like if there is a new user registered using django-allauth It will create the User object Is there like now a way that if there's a new user added to the Users object in the django models, it will make another model object in the example model called Profile, with all the information gather there ... Like the Profile model is watching for changes in the User object and when there is one it will make the appropriate object ... I know it is a bit confusing but please I would like to know ... -
Django: is there a simple way to store choices on the database
Seems basic as a need but I cannot find a way to store Django choices (the actual list of tuples) in database. My use case it that I have a Django app with multiple models and fields with choices. At the app level, I can always get the mapping from field value using get_foo_display or accessing the tuple, but it seems that it’s not actually stored on the DB. Considering that I connect to the DB directly for some stats and BI, I’m missing the mapping for my analysis and reports. Unless there’s some technique to do so, I guess I’ll create a « supporting » model to store the mappings. I would really appreciate your inputs/thoughts. Thank you. -
django_rest_framework: how to write an update_partial() method in a nested serializer to add or remove an object
I've been reading all over the internet and cannot find the answer to this question. below I have two datasets, dataset A and dataset B. I need to write a partial_update() serializer method which merges the two of them, drops duplicates based on the datasets timestamp key and results in the final dataset at the bottom of the question. I currently have the code below in the serializers.py section which results in a response 500 error. serializers.py def partial_update(self, instance, validated_data): instance_is = instance["income_statements"] instance_timestamps = [x["timestamp"] for x in instance_is] if "income_statements" in validated_data: is_data = validated_data.pop("income_statements") is_data_timestamps = [x["timestamp"] for x in is_data] is_time_stamp_diff = [ x for x in is_data_timestamps if x not in instance_timestamps ] is_income_statements = [ x for x in is_data if x["timestamp"] in is_time_stamp_diff ] instance_is_final = instance_is.extend(is_income_statements) instance.income_statements = instance_is_final instance.save() return instance dataset A ( stored in db ) 'income_statements': [ { 'net_income_continuous_operations': '45687000000.0', 'tax_effect_of_unusual_items': '0.0', 'net_income_from_continuing_operation_net_minority_interest': '45687000000.0', 'total_operating_income_as_reported': '60024000000.0', 'basic_average_shares': '5470820000.0', 'reconciled_depreciation': '10505000000.0', ... , ... , ... , 'timestamp': '1475193600.0' }, { 'net_income_continuous_operations': '45687000000.0', 'tax_effect_of_unusual_items': '0.0', 'net_income_from_continuing_operation_net_minority_interest': '45687000000.0', 'total_operating_income_as_reported': '60024000000.0', 'basic_average_shares': '5470820000.0', 'reconciled_depreciation': '10505000000.0', ... , ... , ... , 'timestamp': '1506729600.0' } dataset B ( sent in requests.patch … -
Run startup code when wsgi worker thread restarts
I have a django project running a wsgi application using gunicorn. Ahhh too much for the python newbie like me. I have a below gunicorn command which runs at the application startup. exec ./env/bin/gunicorn $wsgi:application \ --config djanqloud/gunicorn-prometheus-config.py \ --name "djanqloud" \ --workers 3 \ --timeout 60 \ --user=defaultuser --group=nogroup \ --log-level=debug \ --bind=0.0.0.0:8002 Below is my wsgi.py file: import os from django.core.wsgi import get_wsgi_application os.environ['DJANGO_SETTINGS_MODULE'] = 'djanqloud.settings' application = get_wsgi_application() gunicorn command shown from "ps- -eaf" command in a docker container: /opt/gq-console/env/bin/python2 /opt/gq-console/env/bin/gunicorn wsgi:application --config /opt/gq-console//gunicorn-prometheus-config.py --name djanqloud --workers 3 --timeout 60 --user=gq-console --group=nogroup --log-level=debug --bind=0.0.0.0:8002 Their is one simple thread which I create inside django project which are killed when above worker threads are killed. My question is: Is there anyway where I can create my threads AGAIN when the above worker threads are auto restarted ? I have tried to override the get_wsgi_application() function in wsgi.py file but got below error while worker threads are booted: AppImportError: Failed to find application object: 'application'. I am new to python django and wsgi applications so please try to elaborate your answers. Basically I am looking for a location where I can keep my startup code which runs when the … -
using get_absolute_url and showing an error of Reverse for 'article-detail' not found. 'article-detail' is not a valid view function or pattern name
I am using class based views to create a post. I have used get_absolute_url to go to the post page after clicking on post but it is giving an error of no reverse match. this is my modelspy from django.db import models from django.conf import settings from django.urls import reverse # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length = 50 , null=False,blank=False) body = models.TextField(max_length = 5000 , null=False,blank=False) date_published = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('article-detail', args=(str(self.id))) this is my urls.py: urlpatterns = [ path('',views.home,name="home"), path('home2/',HomeView.as_view(),name = "home2"), path('article/<int:pk>',ArticleDetailView.as_view(),name = "article-detail"), path('add_post/',AddPostView.as_view(),name="add_post"), ] this is home2.html: <ul> {%for post in object_list %} <li><a href="{%url 'post:article-detail' post.pk %}">{{post.title}}</a>-{{post.author}}<br/> {{post.body}}</li> {%endfor%} </ul> -
Can't preview the clicked button value
I am trying to preview the values of a bunch of buttons whenever they clicked. I already asked a question here and solved a part of my problem. however there is a small bug which stopped me for long time. This is the mytemplate.html(which almost does what I expect): <div id="preview-items"> </div> <script> $("#id_country").change(function () { var countryId = $(this).val(); // get the selected country ID from the HTML input success: function (data) { $('#preview-items').html(''); for (var i in data.tags) { $('#preview-items').append(` <label class="btn btn-primary mr-1"> <input type="checkbox" id="checklist" value="` + data.tags[i][0] + `"> <span> ` + data.tags[i][1] + ` </span> </label><br />` ); } } }); </script> And this is the script to preview the value of clicked buttons <script> $(function() { $(":checkbox").change(function() { var arr = $(":checkbox:checked").map(function() { return $(this).next().html(); }).get(); $("#preview-items").html(arr.join(', ')); }); }); </script> When I replace the first script with a simple button like below, it works perfectly: <div> <label class="btn btn-primary mr-1"> <input type="checkbox" id="Checklist" value="{{ item.0 }}"> <span> ITEM </span> </label> </div> Please help, I am spending too much to find just a tiny bug. -
Are there alternate methods for Django User authentication?
Can I authenticate users using a 'secret' and a registered IP? For each user I want to have a provide a 'secret' (a simpler password) and registered IPs (their home and work IPs). Then I want to allow access to certain pages only when Logged in using this method? Is this feasible? Any suggestion on how to achieve this is welcome. Bit of background: the Django website allows users to connect to a CRM service that uses OAuth. Users manage multiple CRMs (belonging to multiple clients). They separate clients by creating a separate chrome profile to each client. Right now they have to login to the Django website in each profile to connect to the CRM OAuth. If I can identify users using an IP and secret, they don't need to login in each of their client chrome profiles, so makes the process easier and convenient. Besides they do not need access to the whole site while logged in using the secret, on the page that kicks off the OAuth process and the redirect page. -
How do I change this function which works in normal django to make it work with serializer?
Hey guys I have this feedback create function which I use with my django..but Iam trying to implement the rest api and I am not sure about how to continue and change this function. I am able to list all the feedbacks without any problem but don't know how to implement the create function. Help would be much appreciated. This is my model. class Action(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='actions', db_index=True, on_delete=models.CASCADE) verb = models.CharField(max_length=255) target_ct = models.ForeignKey(ContentType, blank=True, null=True, related_name='target_obj', on_delete=models.CASCADE) target_id = models.PositiveIntegerField(null=True, blank=True, db_index=True) target = GenericForeignKey('target_ct', 'target_id') created = models.DateTimeField(auto_now_add=True, db_index=True) to create the feedback def create_action(user, verb, target=None): now = timezone.now() last_minute = now - datetime.timedelta(seconds=30) similar_actions = Action.objects.filter(user_id=user.id, verb= verb, created__gte=last_minute) if target: target_ct = ContentType.objects.get_for_model(target) similar_actions = similar_actions.filter(target_ct=target_ct, target_id=target.id) if not similar_actions: action = Action(user=user, verb=verb, target=target) action.save() return True return False serializer class GenericActionRelatedField(serializers.RelatedField): def to_representation(self, value): if isinstance(value, Post): serializer = PostListSerializer(value) return serializer.data if isinstance(value, Comment): serializer = CommentSerializer(value) return serializer.data class ActionFeedSerializer(serializers.Serializer): #TODO user = UserSerializer(read_only=True) verb = serializers.CharField() target = GenericActionRelatedField(read_only=True) created = serializers.DateTimeField() class Meta: model = Action fields = ['user', 'verb', 'target_ct', 'target_id', 'target', 'created'] Thanks a lot guys! -
Problems posting images from react to Django Rest API using redux
I'm trying to post an image in my Django API from a react form with no luck. I'm also using the image uploader from AntDesign library and redux. Here's the code I've tried so far: -Form Code: class ArticleForm extends React.Component { this.props.onSendNewArticle( fieldsValue.upload.fileList[0]); render() { <Form.Item name="upload" label="Image" onPreview={this.handlePreview}> <Upload accept=".jpeg, .png" beforeUpload={() => false}> <Button> <UploadOutlined /> Choisir une image </Button> </Upload> </Form.Item> } const mapStateToProps = (state) => { return { loading_add_article: state.add_article.loading_add_article, error_add_article: state.add_article.error_add_article, }; }; const mapDispatchToProps = (dispatch) => { return { onSendNewArticle: (image) => dispatch(actions.articleAdded(image)), }; }; export default connect(mapStateToProps, mapDispatchToProps)(CourseForm); -Here's my view.py class ArticleCreateView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): article_serializer = ArticleSerializer(data=request.data) if article_serializer.is_valid(): article_serializer.save() return Response(article_serializer.data, status=status.HTTP_201_CREATED) else: print('error', article_serializer.errors) return Response(article_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -Here's my store/actions/addArticle.js: export const articleAdded = ( image) => { return (dispatch) => { dispatch(articleDispached); axios .post("http://localhost:8000/api/create/", { img: image }) .then((res) => { const course = res.data; dispatch(articleAddSucess(course)); }) .catch((err) => { dispatch(articleAddFailed(err)); }); }; }; Here's the error that I get: POST http://localhost:8000/api/create/ 415 (Unsupported Media Type) -
APScheduler for creating and loading model
I have a recommendation system project made on python/django. Now I have one Main_Trainer file that trains a recommendation model and I have one Main_Recommender file that gives a recommendation. In my apps.py, I am checking whether the recommendation model is present as a pickle file or not. If present, I am loading the pickle file in a variable there so that it can be used by Main_Recommender file for giving recommendations and I don't have to load model again and again and hence performance is enhanced. If recommendation model is not present, before initializing variable I'm calling the main_trainer function in Main_Trainer file and then loading the pickle file in a variable. Now I want to place a scheduler here such that my trainer runs everyday at 11pm so that my model pickle file is replaced and then load the model pickle file again in the variable. By the time model trainer is running at 11pm, I want my project to use existing file for the recommendation and after the model is created, suppose at 11.30pm, I want my model variable to get refreshed. How can we achieve this scenario? -
Validation not ocurring for custom field type in Django
I'm attempting to make a custom type in Django: from django.db.models import DecimalField from django.core import validators from django.utils.functional import cached_property class MinOneHundredDecimalField(DecimalField): @cached_property def validators(self): return super().validators + [ validators.MinValueValidator(100, "Minimum value is 100"), ] And I use this in my model: class MyModel(BaseModel): amount = MinOneHundredDecimalField( decimal_places=2, max_digits=6, ) However when testing, I'm able to set amount to a value less than 100: def test_min_val(self): my_model = MyModel(amount=50) my_model.save() self.assertNotEqual(my_model.amount, 50, "Message here") I also tried adding the validator directly in the model, but I get the same result: amount = MinOneHundredDecimalField( decimal_places=2, max_digits=6, validators=[MinValueValidator(100.0, "Minimum value is 0")] ) Any ideas why this validator isn't working? Ty!