Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
random sized RelatedFactoryList in Factory Boy
I have the following factory definition class AFactory(django.DjangoModelFactory): b = factory.RelatedFactoryList(BFactory, factory_related_name='a', size=lambda: lambda: random.randint(0, 5)) always yields As with 0 Bs -
How to query Database using Cron jobs in Django [closed]
I have scheduled a script that should run every minute it is working fine when done normally example if I try to append output to a text file it works but if I try to save records its not working. Is it possible in Django/Django-rest framework to save record/query database using Cron jobs ? if yes, how it can be done ? -
Nginx Reverse Proxy is Displaying Default Page
I have been following this guide to use gunicorn and Nginx to host a Django site. All gunicorn related stuff has worked but when I set up Nginx and visit the page, it shows the default page and not my django site home page. Here is my config in sites-available that is simlinked to sites-enabled server { listen 80; server_name my_exact_ip; location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; } Here is also my nginx config. It has not been modified from default GNU nano 2.9.3 nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs … -
Back to previous page (cancel behavior)
I want to add a button in the logout page for cancel the process. Like here: <h1 class="h1">{% trans "Sign Out" %}</h1> <p class="lead">{% trans 'Are you sure you want to sign out?' %}</p> <form id="logout_form" class="logout" method="post" action="{% url 'account_logout' %}"> {% csrf_token %} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <a class="btn btn-danger btn-block" type="submit" href="#?">{% trans 'Cancel' %}</a> <button class="btn btn-danger btn-block" type="submit">{% trans 'Sign Out' %}</button> </form> I want to if user clicked Cancel they back to previous page, where they are coming from. -
How to fix the error 'NoneType' object has no attribute 'price'?
How to fix the error 'NoneType' object has no attribute 'price'? When you click buy, an error flies: 'NoneType' object has no attribute 'price' Request Method: GET Request URL: http://127.0.0.1:8000/order/basket_adding/?csrfmiddlewaretoken=0tcio5qRX3FWgsezHO2DgSdK5XAKS2SUooedqawgEiCdeuCrpVZ8ZhyVCxSv2aEY Django Version: 3.0.7 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'price' Exception Location: C:\Python\mysite\order\models.py in save, line 106 Python Executable: C:\Python38-32\python.exe Python Version: 3.8.3 Python Path: ['C:\Python\mysite', 'C:\Python38-32\python38.zip', 'C:\Python38-32\DLLs', 'C:\Python38-32\lib', 'C:\Python38-32', 'C:\Python38-32\lib\site-packages'] orders/models.py from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.forms import ModelForm from product.models import Product class Status(models.Model): name = models.CharField(max_length=24, blank=True, null=True, default=None) is_active = models.BooleanField(default=True) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "Статус %s" % self.name class Meta: verbose_name = 'Статус заказа' verbose_name_plural = 'Статузи заказа' class Order(models.Model): total_price = models.DecimalField(blank=True, max_digits=10, decimal_places=1, default=0) customer_name = models.CharField(blank=True, max_length=128) customer_email = models.EmailField(blank=True) customer_phone = models.CharField(max_length=48, blank=True, null=True) customer_address = models.CharField(max_length=128, blank=True, null=True) comments = models.TextField(blank=True, null=True, default=None) status = models.ForeignKey(Status, on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "Заказ %s %s" % (self.id, self.status.name) class Meta: verbose_name = 'Заказ' verbose_name_plural = 'Заказы' def save(self, *args, **kwargs): super(Order, self).save(*args, **kwargs) class ProductInOrder(models.Model): order = models.ForeignKey(Order, blank=True, null=True, default=None, on_delete=models.CASCADE) product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=models.CASCADE) … -
Database remember format flask python
I have simple question, in my site user fill a textarea where is max 300 chars. What I have to do that database (I using phpmyadmin,pymysql) remember format, I mean all enters etc. -
Unique ManyToManyField DRF
I do not want to be able to create multiple Chat objects with the same EXACT participants field. For example: If a chat already exists, with participants=["user1", "user2"], I do not want to be able to create a new chat objects with the same EXACT participants Looking for something like unique=True, except for manytomanyfield. Models: class Contact(models.Model): user = models.ForeignKey( User, related_name='friends', on_delete=models.CASCADE) friends = models.ManyToManyField('self', blank=True) def __str__(self): return self.user.username class Message(models.Model): contact = models.ForeignKey( Contact, related_name="messages", on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.contact.user.username class Chat(models.Model): participants = models.ManyToManyField( Contact, related_name='chats') messages = models.ManyToManyField(Message, blank=True) def __str__(self): return f"{self.pk}" Serializer: class ContactSerializer(serializers.StringRelatedField): def to_internal_value(self, value): return value class ChatSerializer(serializers.ModelSerializer): participants = ContactSerializer(many=True) class Meta: model = Chat fields = ("id", "messages", "participants") read_only = ('id') def create(self, validated_data): print(validated_data) participants = validated_data.pop('participants') for c in Chat.participant_set.all(): print(c) chat = Chat() chat.save() for username in participants: contact = get_user_contact(username) chat.participants.add(contact) chat.save() return chat -
Azure Rebuild modifies host in mongo_client.py to localhost
I have written a django application with mongodb as backend, created models and used DJONGO to setup the ORM, below is my settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'conversations', 'HOST':'mongodb+srv://userName:password@clusterx-abcde.mongodb.net/dbName?retryWrites=true&w=majority', 'USER':'userName', 'PASSWORD':'password' } } I had to end up modifying host from localhost to 'mongodb+srv://userName:password@clusterx-abcde.mongodb.net/dbName?retryWrites=true&w=majority' in mongo_clients.py(pymongo package). Django cant connect to mongoDB atlas https://github.com/nesdis/djongo/issues/132 Above are the links I referred to, to change host on mongo_clients.py This application works fine on my local machine, once I host it on azure, during the build azure is modifying the mongo_clients.py and changing the host to localhost making my application not work as expected. class MongoClient(common.BaseObject): """ A client-side representation of a MongoDB cluster. Instances can represent either a standalone MongoDB server, a replica set, or a sharded cluster. Instances of this class are responsible for maintaining up-to-date state of the cluster, and possibly cache resources related to this, including background threads for monitoring, and connection pools. """ HOST = 'mongodb+srv://userName:password@clusterx-abcde.mongodb.net/dbName?retryWrites=true&w=majority' PORT = 27017 # Define order to retrieve options from ClientOptions for __repr__. # No host/port; these are retrieved from TopologySettings. _constructor_args = ('document_class', 'tz_aware', 'connect') Is there anyway to have azure ignore these changes I made on … -
Django add foreign key fields to generic.CreateView
Thanks in advance, I'm learning django and making a poll project, what I want to achieve is make the user Create a question + add some answers choices, so I have a Question class based view and a Choice one class Question(models.Model): id = models.AutoField( primary_key=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) question_text = models.CharField("Question", max_length=200) pub_date = models.DateTimeField( "date de publication", default=timezone.now) popularity = models.IntegerField("popularité", default=0) def __str__(self): return self.question_text class Choice(models.Model): question_lie = models.ForeignKey( Question, to_field="id", null=True, blank=True, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text My CreateView : class CreatePoll(LoginRequiredMixin, generic.CreateView): model = Question fields = ["question_text"] template_name = "polls/create_poll.html" success_url = "/polls" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) actually the user can just provide a question without answers, in the admin part I manage to do it like that : class ChoiceInLine(admin.TabularInline): model = Choice extra = 1 class QuestionAdmin(admin.ModelAdmin): ... inlines = [ChoiceInLine] Is there a similar way ? Thanks for reading -
Linking Google cloud sql instance django website to google domain
I have created django website on Google cloud and its running on sql instance (https://school-website-272007.el.r.appspot.com). I already have a google domain, and i want to link this to it. I followed as below: Created a VM instance on GCP and linked the external ip to my running sql instance. Created Zone and 'A' / 'CNAME' in the Cloud DNS section. Added the new DNS settings to Google domain - DNS settings under custom. (used https://cloud.google.com/dns/docs/quickstart and other youtube links to perform) But still my google domain is not able to link to the website (https://school-website-272007.el.r.appspot.com) Can anyone help? -
How to serve Tornado behind a load balancer nginx?
I have this tornado application wrapped with django function as WSGI app (using in windows) from django.core.wsgi import get_wsgi_application from django.conf import settings from waitress import serve settings.configure() wsgi_app = tornado.wsgi.WSGIContainer(django.core.wsgi.WSGIHandler()) def tornado_app(): url = [(r"/models/(?P<id>[a-zA-Z0-9_-]+)/predict", PHandler), (r"/models/(?P<id>[a-zA-Z0-9_-]+)/explain", EHandler), ('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app))] return Application(url, db=ELASTIC_URL, debug=options.debug, autoreload=options.debug) if __name__ == "__main__": application = tornado_app() http_server = HTTPServer(application,xheaders=True) http_server.listen(LISTEN_PORT) IOLoop.current().start() To serve in Nginx, I have the config file upstream ingenginx { server 127.0.0.1:1111; server 127.0.0.1:2222; server 127.0.0.1:3333; } server { listen 80; location /models/71204e22-869c-4423-9c93-e9cb3c719160/predict { proxy_pass http://ingenginx/models/71204e22-869c-4423-9c93-e9cb3c719160/predict; } } I have included the config file in nginx.conf as include servers/*; include /nginx-1.18.0/pyconf.config; My local runs with nginx works fine in postman as follows POST http://127.0.0.1:1111/models/71204e22-869c-4423-9c93-e9cb3c719160/predict POST http://127.0.0.1:2222/models/71204e22-869c-4423-9c93-e9cb3c719160/predict POST http://127.0.0.1:3333/models/71204e22-869c-4423-9c93-e9cb3c719160/predict with nginx I get 404 error POST http://127.0.0.1/models/71204e22-869c-4423-9c93-e9cb3c719160/predict error <html> <head> <title>404 Not Found</title> </head> <body> <center> <h1>404 Not Found</h1> </center> <hr> <center>nginx/1.18.0</center> </body> </html> as per tornado docs https://www.tornadoweb.org/en/stable/guide/running.html is have included xheaders, not sure why I get 404 -
Add a custom action button to the users' list page that enables staff to set a user to active or inactive with the click of a button
am building a dashboard basically, presently am trying to add a custom button that allows the staff to set other users to active or inactive, with a click of the button. The main problem now is how to pass the current active state of the user from the html to Django when I click the "SWITCH TO ACTIVE STATE BUTTON " My views.py looks like this def home(request, username): username= User.objects.get(username = username ) if username.is_active : username.is_active = False username.save() else: username.is_active = True username.save() return HttpResponse ('its state has been changed') my dashboard.html looks like <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Dashboard</title> {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> <script src="{% static 'js/dashboard.js' %}"> </script> </head> <body> {% if user.is_authenticated %} Hi {{ user.username }} <br> <br> <a href="{% url 'logout' %}">logout</a> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">login</a> {% endif %} {% for all_users in users %} <li>{{all_users}} <form action="{% url 'savesttest:home' %}" method="post"> {% csrf_token %} <input type="hidden" value={users} > <button onclick="handleToggle()" id="switchName" type="submit"> Switch To Active State </button> </form> </li> {% endfor %} <p> this is all {{users}}</p> … -
How to store only the cloud image url in django?
I am trying to display image stored in dropbox , but also want to store the image url in db and access through it ! i upload the image url via csv file as : "https://previews.dropbox.com/p/thumb/AA0mW3mjmcesKPMUR6zpEkS-k1_IKjGGxOa5vfmBQrSsOmE7fO2QK5nqo8IYcJj4P5YpKZ74r4uM9OCGQygxLTYf7vyqAvCwbe9Y4-7EO9huCFLSfMFcnDL-QUAd48OEYDze-SOVR-aN7Npy0La63stvsfQrnTmPwjPiL4sHD9w7pbDYs4D2mWBfJUeyeX2mbq88FEEZvW0_dCk3_XU5zruoKy0wBSc8tATpywC_AoL-g-46IsZZUa_YLJteW3j6WN6ozAC30GuajDh0sPMKl60foiS8DtCPX06OH6vZzMCQ_GpbNQif9Qw9_KJvk80pmREClwK0tJwGYIVd-aLu7TWg2Di5BIR8dL1RY26y8ZjQ9g/p.jpeg?fv_content=true&size_mode=5https://www.dropbox.com/home/product_images/11?preview=iphone.jpg" but while it is saved it becomes , "https://localhost/media/https://previews.dropbox.com/p/thumb/AA0mW3mjmcesKPMUR6zpEkS-k1_IKjGGxOa5vfmBQrSsOmE7fO2QK5nqo8IYcJj4P5YpKZ74r4uM9OCGQygxLTYf7vyqAvCwbe9Y4-7EO9huCFLSfMFcnDL-QUAd48OEYDze-SOVR-aN7Npy0La63stvsfQrnTmPwjPiL4sHD9w7pbDYs4D2mWBfJUeyeX2mbq88FEEZvW0_dCk3_XU5zruoKy0wBSc8tATpywC_AoL-g-46IsZZUa_YLJteW3j6WN6ozAC30GuajDh0sPMKl60foiS8DtCPX06OH6vZzMCQ_GpbNQif9Qw9_KJvk80pmREClwK0tJwGYIVd-aLu7TWg2Di5BIR8dL1RY26y8ZjQ9g/p.jpeg?fv_content=true&size_mode=5https://www.dropbox.com/home/product_images/11?preview=iphone.jpg" it adds localhost url infront , so it is not displayed in the page , how to deal with this? -
I face a problem in queryset while pagination in dajngo
I am at the beginner level in the Django Framework. The queryset works well in my post list. But I face a problem in pagination to the second page queryset according to the tag field in my blog post list. When I go to the second page it shows the main list of the second page, not queryset page. I don't know where the problem behind the seen... models.py code class Post(models.Model): TOPICS = ( ('Programming' , 'Programming'), ('C' , 'C'), ('C++' , 'C++'), ('Java' , 'Java'), ('Python' , 'Python'), ) title = models.CharField(max_length=100, blank=False, null=False) content = models.TextField() tag = models.CharField(max_length=50, choices=TOPICS, blank=False, null=False, default='Programming') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title #redirect to post_detail when some post a blog def get_absolute_url(self): return reverse('post_detail', kwargs={'pk':self.pk}) viwes.py code from django.core.paginator import Paginator from .filters import BlogFilter def home(request): posts = Post.objects.all().order_by('-date_posted') postFilter = BlogFilter(request.GET, queryset=posts) posts = postFilter.qs paginator = Paginator(posts, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'page_obj' : page_obj, 'postFilter' : postFilter, } return render(request, 'blog/index.html', context) template code {% extends 'blog/base.html'%} {% load crispy_forms_tags %} {% load static %} {% block content %} <section id="article"> <div class="container"> <div class="row mt-4"> … -
I am not able to load some data in Django
I am trying to make an app in which I am putting lectures. My idea is that the user will click on Subject then on the chapter they want and then can click on the lecture they want to view. But I am not sure how to load this on my website. Can you suggest me any method to show this on my website. Even a non technical answer would do, I just need a small direction -
Django sending image file through ajax but request.FILES is empty
I'm trying to upload an image via a post request using AJAX to the server (localhost). The image gets saved in the media folder. If I do print(request.FILES['image'], it prints the name of the image file. But if I do print(request.FILES['image'].read() it is empty. I've looked at a similar question enter link description here and tried the approach, however, it didn't work for me. Here is my index.html: <!doctype html> <html> {% load static %} <head> <script type="text/javascript" src="{% static 'js/main.js' %}"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/webcamjs/1.0.25/webcam.js"></script> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script> <script type="text/javascript" src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script> <script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> <form id="submitimage" action="/upload/" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="file" id='image' name="image"> <input type="submit" value="Submit" id='uploadPic'/> </form> </body> <script> $('#submitimage').submit(function(){ $.ajax({ url : '/upload/', type : 'POST', dataType: 'json', data : $(this).serialize(), success : function(data) { console.log("calling ajax"); var img_data = $('#image').get(0).files[0]; var data= new FormData(this); // var img_data = $('#image').get(0).files[0]; data.append("img_data",img_data); console.log(data); // console.log(data.get("img_data")); $.ajax({ type: 'POST', url: '/upload/', headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: {csrfmiddlewaretoken: "{{ csrf_token }}", "imgfile": data }, contentType: false, processData: false, success: function (data) { console.log("Image uploaded"); }, error: function(data) { console.log("Couldn't upload the image"); } }); return false; }, error: function(data) { console.log('fail'); } … -
Check if user exists in database table
I want to write a method if to check if the user has added an object to their bookmarks however, I am struggling on how to write it so I can pass it into my template. So I have two types of models for bookmarking different objects: class BookmarkBase(models.Model): class Meta: abstract = True user = models.ForeignKey(Profile,on_delete=models.CASCADE, verbose_name="User") def __str__(self): return self.user.username class BookmarkPost(BookmarkBase): class Meta: db_table = "bookmark_post" date = models.DateTimeField(auto_now_add=True) obj = models.ForeignKey('home.Post',on_delete=models.CASCADE, verbose_name="Post") class BookmarkBlog(BookmarkBase): class Meta: db_table = "bookmark_blog" date = models.DateTimeField(auto_now_add=True) obj = models.ForeignKey('home.Blog',on_delete=models.CASCADE, verbose_name="Blog") And my view and URLs that are responsible for handling adding/removing Objects to bookmarks are: @login_required def add_bookmark(request, id, obj_type): data=dict() if request.method == 'POST': if obj_type=='post': model = BookmarkPost elif obj_type=='blog': model = BookmarkBlog elif obj_type=='buzz': model = BookmarkBuzz user = auth.get_user(request) bookmark, created = model.objects.get_or_create(user=user, obj_id=id).remove() if not created: bookmark.delete() context = {'bookmark':bookmark} data['html_form'] = render_to_string('main/bookmark/bookmark.html',context,request=request) return JsonResponse(data) And urls is: path('bookmark/<int:id>/<str:obj_type>/', views.add_bookmark,name='add-bookmark'), I am struggling on this part on how I can add this functionality so that if user has already added the bookmark it will change it icons and display the {% else %} part: <form class="add-bookmark-form" method="POST"> {% if request.user has not added object to … -
Can't add class to Django form fields
class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ('username', 'email') widgets = { 'username': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), } Using the code above, only the username has the form-control class, and the email doesn't. Why is that? I found a work around that makes the email field has form-control class, which is class RegisterForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) class Meta: model = User fields = ('username', 'email') widgets = { 'username': forms.TextInput(attrs={'class': 'form-control'}), } However, I really don't want it to look like this. Is there a way to make it work like the 1st piece of code? the template file is just simple <div class="form-group"> <form id="register" method="POST"> {% csrf_token %} {{ form.as_p }} </form> </div> -
django SMTP setup using gmal with custom `from`
I want to reproduce the following test case from backend email from Django built using Gmail servers , however I keep getting the owner email in to, and from from my feedback form . I am using the following send_email setup send_mail(subject, message, from_email, ['xxx@xxx']) desired output Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: You have a new aaaaaaa@gmail.com from support From: xxxx@gmail.com To: support@demo.io Date: Mon, 22 Jun 2020 02:59:30 -0000 Message-ID: <159279477011.24057.7925107016621366148@xxxxx> -
Run "git pull" for a Django project running on Windows Server 2016 IIS
My current set up has a Django project running on Windows 2016 IIS. The project is hosted on GitHub for collaboration and I would like to set up a GitHub webhook so whenever there's a push to master branch from any of the collaborators, the IIS Server will run a "git pull" to update the project on the server. What is normally the setup for this? What I have tried so far is to create an endpoint in the Django project, this endpoint whenever called will run Python subprocess to run "git pull" command in the project itself. However, whenever I run it, it get a 500 response from IIS. -
Reverse url not found
what is this error? AttributeError at /size/uspolo10/ 'str' object has no attribute 'get'a valid view function or pattern name. I got this error. I can't understand this situation that 'str' and 'get'. Please help me to solve this error. views.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() tag = models.CharField(max_length=10,blank=True,null=True,default='New') discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() schargeinc = models.FloatField(blank=True, null=True,default=-1) size = models.ForeignKey(Sizes_class, on_delete=models.CASCADE, null=True, default=False) selcsize = models.CharField(default=False,null=True,blank=True,max_length=25) def __str__(self): return self.title def get_add_cart_wsize_url(self): return reverse("core:size", kwargs={ 'slug': self.slug }) def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("core:remove-from-cart", kwargs={ 'slug': self.slug }) size.html <form method="POST" action="." > {% csrf_token %} <div id="exampleModalPopovers" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="exampleModalPopoversLabel"> <h5>Select a size</h5> {% for size in object.size.sizes_choice %} <div class="custom-control custom-radio"> <div class="custom-control custom-radio"> <input id="{{ forloop.counter }}" name="sizes_choice" value="{{ size }}" type="radio" class="custom-control-input" required> <label class="custom-control-label" for="{{ forloop.counter }}">{{ size }}</label> </div> </div> {% endfor %} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary btn-md my-0 p"> Set </a> </div> </div> </form> urls.py path('size/<slug>/', size, name='size'), -
371 dinh bo linh-p26-quan binh thanh-tp ho chi minh
namespace Example.Namespace1 { public partial class ImportantClass { protected partial class Nested1 { // I can finally start writing code here public int AddOffset(int offset) { // Code inside of a method } public string ID{ get; protected set; } } } } -
I am using mixins CreateView... and having issue in pre populating the slug field
I am using Django model-specific CreateView, UpdateView and DeleteView. For my CreateView i have some fields = ['subject', 'title', 'slug', 'overview'] on create.html page including slug field which should be populated automatically based on the title field as the user types in. Also i am using the same template for create and edit operation. In the Admin panel i can use prepopulated_fields = {'slug': ('title',)} to get this done and as the user types in this field generates the slug. Here is the related section from views.py class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin, PermissionRequiredMixin): model = Course fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list') class CourseCreateView(OwnerCourseEditMixin, CreateView): permission_required = 'courses.add_course' Any help would be appreciated. -
EDIT A FORM IN DIFERENTS TEMPLATE FOR EACH SITUATION DJANGO
I have a model called "" and the same its used to do a form with ModelForm. How you can see, i've done all the views to insert, edit, delete and see data in each template. But, I would like to edit this form in these way: The user will submit the form without fill a unique field After the user submit, I will have a template to show the informations and I would like to have something to approve or reject the form(I thought in a boolean field, with default=false) if I approve: I would like to display the same form with the fields that has already filled when the user submited, but with these fields just readonly and the another field that is empty I would like that the user could fill. After the user fill these field that was empty, he would save the forms and would be dislplayed in another template where I can accepet the answer and "close" the the cicle of the form. There is a way to do this with python/django? maybe just doing a new view. my models: class RegistroFalha(models.Model): nome = models.CharField(max_length=255) tag = models.TextField() status = models.CharField( max_length=50, default='Aberto', choices=( … -
How can i connect webcam stream from javascript to django backend?
I created a djagno website which use OpenCV to connect with webcam and stream it in browser locally and it worked. But when I uploaded the website on Heroku server, it stopped working. So I used javascript to connect the webcam. But the stream I got from javascript did not seems to be connected with my backend. So how can I connect webcam accessed using javascript and send the stream to Django backend and after processing display it back on frontend? Javascript code var video = document.querySelector("#videoElement"); if (navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }) .then(function (stream) { video.srcObject = stream; }) .catch(function (err0r) { console.log("Something went wrong!"); }); OpenCv code class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): success, image = self.video.read() ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() I know these are a lot of question, so I am expecting a pathway and keywords from where I can learn these concepts. At least give me some direction so I can learn and accomplish this.