Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Group Concat in Django
I am having a model class Project(models.Model): project = models.CharField(max_length=255, blank=True, null= True) user = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() start_date = models.DateField() THis is my query for fetching the data qs = Project.objects.values('project').annotate( total_hours=Sum((F('end_time') - F('start_time'))), start_date =F('start_date'), ).distinct() for i in qs: print(i) Now what I am getting is {'project': '1', 'total_hours': Decimal('2.0000'), 'start_date': datetime.date(2020, 8, 1)} {'project': '3', 'total_hours': Decimal('1.0000'), 'start_date': datetime.date(2020, 8, 1)} {'project': '1', 'total_hours': Decimal('1.0000'), 'start_date': datetime.date(2020, 8, 2)} Here if project 1 coming twise in to diffrent dates.... How to elimintate second one add as a single object So I am trying to use GROUP_CONCAT https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat THis is the code class GROUP_CONCAT(Func): function = 'GROUP_CONCAT' template = '%(function)s(%(expressions)s)' output_field = DateField() But I am not sure How can I use it with Django ORM Query -
Django Aggregation: Summation of Multiplication of two fields with ForienKey
I have two model as below class Product(models.Model): title = models.CharField(max_length=128) slug = models.SlugField() price = models.DecimalField(default=0.0,decimal_places=2,max_digits=15,validators=[MinValueValidator(Decimal('0.00'))]) def __str__(self): return str(self.title) class OrderItem(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.product.title}" def subtotal(self): return self.quantity * self.product.price I want the total of all subtotal using aggregate but total1 = OrderItem.objects.all().aggregate(total=Sum(F('product.price') * F('quantity')))['total'] returns Cannot resolve keyword 'product.price' into field. Choices are: id, order, product, product_id, quantity and total2 = OrderItem.objects.all().aggregate(total=Sum(F('subtotal') * F('quantity')))['total'] returns Cannot resolve keyword 'subtotal' into field. Choices are: id, order, product, product_id, quantity, user_session error -
Browser error during django + SSL connection with local server
I have a problem during adding facebook login button to my website at localhost. I've already add mysite.com to hosts file and installed django-extensions, werkzeug, pyOpenSSL. By running command python manage.py runserver_plus --cert-file cert.crt my own-made sertificate was created. I imported this certificate to Trusted Chrome sertificates but safe connection doesn't establish. When i pass https://example.com:8000/account/login/ I hit an error NET::ERR_CERT_COMMON_NAME_INVALID, Failed to confirm that this is the server example.com. Its safety certificate refers to *. The server may be configured incorrectly or someone is trying to intercept your data. Please help me to solve this. -
Media File folder issue on python any where Server
I'm facing a weird issue, my media folder get created outside of the project directory on pythonanywhere, there is no issue on a local server, I uploaded many sites on pythonanywhere but this issue I faced the first time. If you help me to resolve this I shall be thankful to you. Note: My static files are run fine only issues with the media root folder python anywhere folder. Setting file -
For blog post i used tags by many_to_many filed. Now i try to use Django_Taggit for tag field, but i face some error while makemigration
Old MODELS.py when use tags by many_to_many fields class Tag(models.Model): tag_name = models.CharField(max_length=64, unique=True) tag_slug = models.SlugField(max_length=64, unique=True) created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) def __str__(self): return self.tag_name def get_absolute_url(self): return reverse("news:tag-detail", kwargs={"slug": str(self.tag_slug)}) class News(models.Model): title = models.CharField(max_length=192, unique=True) slug = models.SlugField(max_length=192, unique=True) cover_photo = models.ImageField(upload_to='news', blank=True, null=True) summary = models.CharField(max_length=280) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=1) # tags = models.ManyToManyField(Tag, blank=True, related_name='post_tag') class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse("news:post", kwargs={"slug": str(self.slug)}) current models.py After install Django_Taggit i remove tags model and rewrite tags line class News(models.Model): title = models.CharField(max_length=192, unique=True) slug = models.SlugField(max_length=192, unique=True) cover_photo = models.ImageField(upload_to='news', blank=True, null=True) summary = models.CharField(max_length=280) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=1) tags = TaggableManager() class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse("news:post", kwargs={"slug": str(self.slug)}) Also i remove tags from view.py and urls path and update html but when i try to makemigrate i face this error python manage.py makemigrations news SystemCheckError: System check identified some issues: ERRORS: news.News.tags: (fields.E300) Field defines a relation with … -
How do I set value for foreign key field?
I want to set the value for this CustomerReg in picture above to request.user.username I am able to manually select it, what I want is after login it gets directly assigned to person who has logged in to submit this form. views.py(multi_form view and register view) I cannot automatically assign CustomerReg field in Customer model. def registerPage(request): if request.user.is_authenticated: return redirect('form') else: form=CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if(form.is_valid()): form.save() user=form.cleaned_data['username'] messages.success(request, 'Account created for '+ user) return redirect('login') def multi_form(request): form=RegForm() if request.method=='POST': form=RegForm(request.POST, request.FILES) if form.is_valid(): form.save() print(request.user.id) messages.success(request, "Your Response has been recorded") context={'form':form} return render(request, 'customer/index.html', context) models.py(Customer and CustomerReg model) Customer model has customerReg field as foreign key. class CustomerReg(models.Model): user=models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name=models.CharField(max_length=200, null=True) email=models.EmailField(max_length=254) def create_profile(sender, **kwargs): if kwargs['created']: user_profile=CustomerReg.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) class Customer(models.Model): id=models.AutoField(primary_key=True, default=None) customerReg=models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) first_name=models.CharField(max_length=200, blank=False, default=None) last_name=models.CharField(max_length=200, blank=False, default=None) -
Use Email instead of Username to authenticate user
I know this answer have a lot of answers and many different ways to do that , But As of today in Django 3 I want to know which one is best and reliable way to use only email for authentication . -
python-socketio websocket emit to particular client in Socket.IO an ionic application
In my project I am using a Django application that acts as a SocketIO server to the Ionic mobile application which uses Socket.io to connect to the server as a client. My django application has another socket connection and it acts as a client to another micro service in python which uses python-socketio to create a websocket server. When I send a request from the Ionic application, it reaches the Django server which sends the request to the client via Django signals and then the request is sent to the micro services and the response from them are to be sent to the same Ionic application via Django. I was able to do it successfully when the Ionic application is only one. When there are multiple Ionic clients and when the data is different for them both, this does not make an effect. Both the clients receive the same data. My requirement forces me to have the communication through the Django server. Can anyone help me with this? Microservice (python-socketio) <--> Django (python-socketio) <--> Ionic application (socket.io) The communication is by websockets by eventlet. -
Django ORM in one query get two result
I have a query and i am trying to count total open Quote and total bids of open quote. thse are my models class Quote(models.Model): STATUS= ( ('OPEN', "Open"), ('CLOSED', "Closed"), ) status= models.CharField(max_length=14, choices = STATUS, default='OPEN') class Bid(models.Model): text = models.TextField(max_length=1000) quote = models.ForeignKey(Quote, on_delete = models.DO_NOTHING, related_name='bids') and thise is my query in django rest frameowrk for a json response def get(self, request): quote = Quote.objects.filter(status='OPEN').count() bids = Bid.objects.filter( quote__status='OPEN' ).count() return Response({ 'quotes_count': quote, 'bids_count': bids, }) Everything is working great ! but i don't like that this, coz, I think the two queries is completely worst practice, coz, i think it's possible to get same result in a single query. Can anyone please help me to optimize this query? I mean, i want to query in one veriable to get two dffierent result (Total Open Quote and Total bids of actual open quote) -
Lookups that span relationship -
I am a Django newbie so I think this is too basic to google! Thanks so much for your help! I want to do a lookup that spans three classes. In this case, I want to find all the PartListing that match the specific_part in the ListItem. I have these models: class SpecificPart(BaseModel): class PartListing(BaseModel): specific_part = models.ForeignKey( SpecificPart, on_delete=models.CASCADE, blank=True, null=True, related_name="part_listing") class ListItem(BaseModel): specific_part = models.ForeignKey(SpecificPart, on_delete=models.CASCADE, related_name="listitem") I'm trying to put the lookup under the ListItem class like this: def item_match(self): part = self.specific_part return PartListings.filter(specific_part__specific_part=part) I am getting an error that PartListing is not defined but I also suspect that I'm referencing the foreign keys incorrectly. -
Django Admin Related Problems
I want to customize the Django Admin Panel means creating my own admin Panel from scratch. Creating groups permission from scratch. Also, modify Django username Field to Email Field. Is there anyone who can do all stuff in his/her project. Please send me the project document for educational purposes. In my college, I want to show projects on these related topics. -
Confusion in form.save() in two different models
I am having problems in displaying the page due to models. I honestly don't know what the problem is and every solution I see here is beyond me, since I am only beginning to learn Django. Here's the summary: I have created two forms from two models(which are interrelated) and rendering the data from those forms in a single page. The data displays fine on the dashboard panel and the submission does save it to the database. However, whenever I try and load the pages containing same data (display pages like home for customers)I am hit with: get() returned more than one Order -- it returned 2! The code in forms.py: from django.forms import ModelForm from shop.models import * class OrderForm(ModelForm): class Meta: model = Order fields = ('customer',) class OrderItemForm(ModelForm): class Meta: model = OrderItem fields = ('item', 'status',) views.py def createOrder(request): form_order = OrderForm() form_orderitem = OrderItemForm() if request.method == 'POST': # print('Printing POST', request.POST) form_order = OrderForm(request.POST) form_orderitem = OrderItemForm(request.POST) if form_order.is_valid() and form_orderitem.is_valid(): form_order.save() form_orderitem.save() return redirect('/dashboard') context = {'form_order': form_order, 'form_orderitem': form_orderitem} return render(request, 'dashboard/order_form.html', context) -
Generic UpdateView isn't working with slug
I'm pretty new to django.I am trying to update a post with generic UpdateView. But the post isn't updating after filling up the form.Im accessing the update view through slug url. My model: class Post(models.Model): title = models.CharField(max_length=60) post_body = models.TextField() time_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE) slug = models.SlugField(null=False,unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('postdetail', kwargs={'slug': self.slug}) def save(self,*args,**kwargs): if not self.slug: author_id = str(self.author.id) self.slug = slugify(self.title +'-'+author_id) return super().save(*args, **kwargs) My view: class postupdate(LoginRequiredMixin,UserPassesTestMixin,UpdateView): model = Post fields = ['title','post_body'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True else: return False My url: path('post/<slug:slug>/updatepost/', postupdate.as_view(),name = 'updatepost'), -
Django: Ordering Objects Manually w/ A Field
I have a django model with an index IntegerField. I want to allow users to manually order these objects via a drag and drop interface. The idea is to update the ordering by updating this index field when one of the objects is dragged to a new position. So, for example if a user drags the 4th item to the top, that object will then be index 0, former index 0 will be index 1, former index 1 will be shifted to index 2 and so on. Is there a good way to do this in a single Django ORM call, without needing to iterate through the entire list of objects and increment the index? Say I want to insert an object that was at Index 4 at Index 2– is there a way to shift all indexes >= 2 by +1? -
Django admin add context to index.html
I'm trying to override Django admin index.html to show table contain latest 5 records from a model I managed to override the template with the following in my app: from django.contrib import admin admin.site.index_template = 'admin/dashboard.html' admin.autodiscover() But i have no idea how to add the latest records from model as a context to the index.html Hope someone can help me -
Django AllAuth - Link UserProfile stored in session to User created from Google Signup
I want to allow users to sample my Django website before prompting them to sign up with Google (which I implement using the django-allauth package). I want them to be able to create a UserProfile with their name, age, preferences, etc. and allow them access to the site. class UserProfile(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=25, null=True, blank=True) age = models.IntegerField(null=True, blank=True) I do this by creating a UserProfile with no associated User, and storing their UserProfile pk in the session as follows: userprofile = UserProfile(name='Harry', age=28) userprofile.save() request.session['userprofile_pk'] = userprofile.pk Then when the user eventually decides to sign up via Google, I'd like to link their UserProfile to the User model like so: userprofile_pk = request.session.get('userprofile_pk') userprofile = UserProfile.objects.filter(pk=userprofile_pk).first() userprofile.user = request.user # User that has just been created using the django-allauth Google package userprofile.save() The problem I'm facing is that the django-allauth package creates the User, logs them in, and redirects to the url specified in my LOGIN_REDIRECT_URL, which clears the session and all access to the userprofile_pk. Is there a way I can link the UserProfile stored in the session to the newly created User? -
Is there anyway to run a game irrespective of reloding page in django
I need a way to run this number game irrespective of request. It should accept the forms submitted from this same page. I found that js clock and backend clock are not synchronized so I have started reloading this game tab for each second. So that time modules are creating newly after every refresh. And another problem is when a new user visits this page it will create time modules newly which ruin this game. So please suggest me a better way to do this. views.py class NumberSection(ListView): template_name = "gamepage.html" def get(self, *args, **kwargs): context = {} silver_created=False if not silver_created: silver_end,silver_gold_buffer,silver_gold_new,silver_gold_correct,silver_gold_start = create_time_modules() self.silver = True silver_game = NumbersGame.objects.create(mode='silver') self.silver_game_id = silver_game.id context['silver_status'] = 'accepted' silver_created =True if silver_created: if silver_end<=datetime.now(): self.silver = False context['silver_status'] = 'blocked' if silver_gold_buffer<=datetime.now(): pass if silver_gold_new<=datetime.now(): silver_created = False while True: silver_x = silver_gold_correct - silver_gold_start context["silver_minutes"]=(silver_x.seconds//60)%60 context["silver_seconds"]=silver_x.seconds%60 return render(self.request,self.template_name,context=context) def post(self, *Args, **kwargs): name = self.request.POST.get("choosen") amt = self.request.POST.get("total") if name == 'silver' and self.silver: hist = History.objects.create(user=self.request.self.user.userprofile,investment=amt,color_num_selected=name) hist.id_made = self.silver_game_id hist.save() return redirect('core:next') -
Understanding Django Rest Framework's ModelViewSet Router
I have my Comment model: class Comment(models.Model): """A comment is a content shared by a user in some post.""" user = models.ForeignKey('users.User', on_delete=models.CASCADE, null=False) post = models.ForeignKey('posts.Post', on_delete=models.CASCADE, null=False) content = models.TextField(max_length=1000, null=False, blank=False) def __str__(self): """Return the comment str.""" return "'{}'".format(self.content) Its serializer: class CommentSerializer(serializers.ModelSerializer): """Comment model serializer.""" user = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Comment fields = '__all__' def create(self, validated_data): """Create a new comment in some post, by request.user.""" validated_data['user'] = self.context['request'].user return super().create(validated_data) def list(self, request): """List all the comments from some post.""" if 'post' not in request.query_params: raise ValidationError('Post id must be provided.') q = self.queryset.filter(post=request.query_params['post']) serializer = CommentSerializer(q, many=True) return Response(serializer.data) The viewset: class CommentViewSet(viewsets.ModelViewSet): serializer_class = CommentSerializer queryset = Comment.objects.all() def get_permissions(self): permissions = [] if self.action == 'create' or self.action == 'destroy': permissions.append(IsAuthenticated) return [p() for p in permissions] def get_object(self): """Return comment by primary key.""" return get_object_or_404(Comment, id=self.kwargs['pk']) # this is the drf's get_object_or_404 function def destroy(self, request, *args, **kwargs): """Delete a comment created by request.user from a post.""" pdb.set_trace() instance = self.get_object() if instance.user != request.user: raise ValidationError('Comment does not belong to the authenticated user.') self.perform_destroy(instance) def retrieve(self, request, pk=None): pass def update(self, request, pk=None): pass def partial_update(self, request, pk=None): … -
'WSGIRequest' object has no attribute 'type' error in Django API integration
I'm trying to integrate easyship API with my system. I'm able to create a shipment order using the Easyship API, but at first when the make shipment event is triggered, I receive this error 'WSGIRequest' object has no attribute 'type' and later when I refresh my page the shipment log is created and the error is gone. def update_order(request, pk): order = Order.objects.filter(id=pk).first() form = OrderForm(request.POST or None, user=request.user,instance=order) if request.method == 'POST': if form.is_valid(): if order.status=='Prepare to Ship' and order.shipment_status=='Not Created': values = { "platform_name": "Amazon", "platform_order_number": "#1234", "selected_courier_id": "null", "destination_country_alpha2": "US", "destination_city": "null", "destination_postal_code": "10022", "destination_state": "New York", "destination_name": order.name, "destination_company_name": "My Company", "destination_address_line_1": order.address, "destination_address_line_2": 'null', "destination_phone_number": order.phone, "destination_email_address": "order.email", "items": [ { "description": "Silk dress", "sku": "test", "actual_weight": 0.5, "height": 10, "width": 15, "length": 20, "category": "fashion", "declared_currency": "SGD", "declared_customs_value": 100 } ] } headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer xxxxxxAPI KEYxxxxxxxxx' } r = requests.post("https://api.easyship.com/shipment/v1/shipments", data=json.dumps(values), headers=headers) print(r.json()) order.shipment_id = r.json()['shipment']['easyship_shipment_id'] order.shipment_status = 'Created' order.save() print(r.text) response_body = urlopen(request).read() print(response_body) return redirect('/orderlist/') context = {'form':form} t_form = render_to_string('update_form.html', context, request=request, ) return JsonResponse({'t_form': t_form}) -
Why I can't display data of a user in Django?
I want to display or list all current user's leaveforms (consider it as posts). For some reasons those data are not showing up. Can you spot me the mistakes? models.py class StudentLeave(models.Model): student = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) date_created = models.DateTimeField(auto_now_add=True) leave_from_date = models.CharField(max_length=200) leave_till_date = models.CharField(max_length=200) student_name = models.CharField(max_length=200) leave_reason = models.TextField() def __str__(self): return self.student_name views.py @login_required def home(request): current_student = request.user all_student_leaveforms = StudentLeave.objects.filter(student=current_student) # student_leaveform_model = StudentLeave.objects.all().order_by("-date_created") return render(request, 'attendance/content/home.html', { 'all_student_leaveforms': all_student_leaveforms }) how I render in template {% for leaveform in all_student_leaveforms %} <div class="row"> <div class="ml-3"> <a href="#"> <h3>{{ leaveform.leave_from_date }} - {{ leaveform.leave_till_date }}</h3> </a> <p>Submit at {{ leaveform.date_created }}</p> </div> <a href="{% url 'leaveform_detail' leaveform.id %}" class="btn btn-info mt-3 ml-auto mr-3" > View </a> </div> <hr /> {% endfor %} -
Return a template after fetch
I made a fetch POST with data I want to handle on my server. I want to get that Json values sent by the fetch and use them to return a template, so i'm doing: def prepricing(request): if request.method == "POST": content = json.loads(request.body) return render(request, "letter/pricing.html", { "mail":content['mail'], "name":content['name'], "content2":content['content'] }) The post method is triggered. But here the problem is that, it doesnt' return anything. If i do instead return JsonResponse(content) it returns the value back to the js, but i need to render the template, not other thing. Any ideas? -
Django 'tuple' object has no attribute 'save'
I have this model CustomerPurchaseOrderDetail, Product, Customer, I just want that if the same productID and same CustomerID exists in the CustomerPurchaseOrderDetail model, the quantity will add 1 if the same productID and same CustomerID exists in the CustomerPurchaseOrderDetail. userID = request.POST.get("userID") client = Customer(id=userID) vegetables_id = request.POST.get("id") quantity = request.POST.get("quantity") v = Product(id=vegetables_id) price = request.POST.get("price") discount = request.POST.get("discount_price") insert = CustomerPurchaseOrderDetail.objects.get_or_create( profile=client, product = v, quantity=quantity, unitprice=price, discounted_amount = discount, discounted_unitprice = discount, ) insert.save() this is my models class CustomerPurchaseOrderDetail(models.Model): profile = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Product") quantity = models.FloatField(max_length=500, null=True, blank=True, default=1) class Product(models.Model): product = models.CharField(max_length=500) class Customer(models.Model): user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) firstname = models.CharField(max_length=500, blank=True) lastname = models.CharField(max_length=500, blank=True) contactNumber = models.CharField(max_length=500, blank=True) email = models.CharField(max_length=500, blank=True) this is my error this is my full traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/batchaddtocart/ Django Version: 2.2.4 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'customAdmin', 'sweetify'] Installed 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'] Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, … -
Django: child drop down value is not returning, from dependent drop down set
I have a dependent drop down set for Makes and Models. Javascript is used to detect the change on the Make and then to filter/populate the Model dropdown from a Model. This appears to work well. I need the child drop down value to then perform a search of inventory on another html page, which I'm creating through a view. I instead of passing the child value, the parent value is always returned. This means I can generate a search/filter using the make but not the model as is required. I have tried many combinations of requests and changing the drop downs as well as an attempt at hidden variables to obtain the java script variable in place of pulling back the dropdown option via the name attribute ..... so far no success. Really need some guidance here. Index - drop down values are rendered {% extends "app/layout.html" %} {% block content %} <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" /> <script> $(document).ready(function() { var $makevar = $("#makeddl"); $modelvar = $("#modelddl"); $options = $modelvar.find('option'); $makevar.on('change',function() { $modelvar.html($options.filter('[value="' + this.value + '"]')); }).trigger('change'); }); </script> <script type="text/javascript"> function getOption() { selectElement = document.querySelector('#modelddl'); var $modelval = selectElement.value; }; </script> </head> … -
How to get inline style values and send to Django
I created Django application using draggable images with jQuery, it's working well, however I need to save, the new top and left positions in Django Model. I was trying a way to send inline style informations for some input type="hidden" value = "??? style" Look, after user move picture Jquery Draggable send this : <div id="draggable-1" class="ui-draggable ui-draggable-handle" style="position: relative; left: 3px; top: 1453px; "> <img src="static/img/image.png" width="80" height="200"> </div> Javascript to this resource in only: <script> $( "#draggable-{{forloop.counter}}" ).draggable(); </script> I need these numbers from left and top informations to send to a Django view and save database model. any suggestion, thank you! -
How to use task decorator in django celery
I have this task in this setup that needs to be run periodically: app.tasks.sum import sys from celery.decorators import periodic_task class Sum: @periodic_task def __call__(self, a, b): return a + b sys.modules[__name__] = Sum() project.settings.py: CELERY_BROKER_URL = 'redis://user:password@redis:6379/' CELERY_RESULT_BACKEND = 'redis://user:password@redis:6379/' CELERY_BEAT_SCHEDULE = { "sum": { "task": "app.tasks.sum", "schedule": crontab(minute="*"), }, } I'm getting this error Scheduler: Sending due task sum(app.tasks.sum) The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: b'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b) Traceback (most recent call last): File "/opt/bitnami/python/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 562, in on_task_received strategy = strategies[type_] KeyError: 'app.tasks.sum' I'm not sure if i put the decorator in the correct place