Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best web framework for computer vision
I am developing a computer vision app where user can connect their IP camera and then find video analysis by yolo or other object detection algorithm. Tensorflow provides me the web version for JS/Nodejs. But which will be the best you think between python(Django)/JavaScript(MERN)? And why? If I choose python, I can find a rich python ML library. But I can't really decide. -
How to get attributes value of html inputs in django views
I have html input like this: <input type="text" name="download_number" class="corecharinputwidget form-control" size="10" maxlength="30" style="font-size: smaller;margin-top: 30px;" placeholder="Enter Document Number" id="id_download_number" pk="1"> and I want to recieve pk attribute value in django view. -
Regrading operational error in the django no such table
I am using django admin page and try to add record in the my table ,but when i am adding the record , I am getting operational error ,no such table exist,please help me regarding this,I am using sqllite database -
How to use checkbox in form, i have in my model 1 field manytomanyfield
I need to show the category field in my template as a check box field forms.py class PostUpdateForms(forms.ModelForm): class Meta: model = CreatePost fields = ['title', 'img', 'category', 'content' ] widgets = { 'title':forms.TextInput(attrs={'class':'form-control'}), } models.py class Categories(models.Model): category = models.CharField(verbose_name="Categoria", max_length=20) class Meta: verbose_name = 'Categoria' verbose_name_plural = 'Categorias' ordering = ['category'] def __str__(self): return self.category def custom_upload_to(instance, filename): #old_intance = CreatePost.objects.get(pk=instance.pk) #old_intance.img.delete() return 'post/'+filename class CreatePost(models.Model): #user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Usuario") title = models.CharField(verbose_name="Titulo", max_length=100) slug = models.CharField(max_length=200, blank=True) content = models.TextField(verbose_name="Contenido", null=True, blank=True) img = models.ImageField(upload_to=custom_upload_to, null=True, blank=False) category = models.ManyToManyField(Categories) created = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(CreatePost, self).save(*args, **kwargs) class Meta: verbose_name = 'Anime' verbose_name_plural = 'Animes' ordering = ['-created'] -
Django change the default path for login form
By default, the path for login is registration/login.html. Problem is that I want to use the login form inside the main index page not in another page. If I put the below codes in webpage/registration/login.html, the login form works. But if I put the codes in webpage/index.html the login is not successful. <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> How is it possible to change the default login path to look on webpage/index.html and not on registration/login.html? -
How to serve Django app on separate domain from the rest of the Django project
I'm using the Apache server with mod_wsgi. It is a Django project with 3 apps: app1, app2, app3 Each app is defined in the urls.py and work fine: examplesite.com/app1 examplesite.com/app2 examplesite.com/app3 My virtualhost conf is setup to accept both examplesite.com and app2examplesite.com. Now what I'm trying to do is also have just one of these apps, app2, served at the root of another domain: app2examplesite.com The end result should be that examplesite.com/app2 and app2examplesite.com are identical. And therefore app1 & app3 would be inaccessible through app2examplesite.com. What is the best-practice way to do this? I've got something working by setting my urls.py to load the same view at both: path('', MainHome.as_view(), name='home') path('app2/', MainHome.as_view(), name='app2-home') However this is not what I want, since this essentially makes both examplesite.com and app2examplesite.com identical, and all 3 apps accessible on both domains. I'm not sure if this needs to be done via Apache's confs, or through Django's urls.py or settings. TLDR; Currently, Django project works like: examplesite.com examplesite.com/app1 examplesite.com/app2 examplesite.com/app3 But I want to make app2 available at: app2examplesite.com -
Get Value of Data from Form In Ajax Django Request
I need to redirect my code to another page in Django url including primary key from my view.py after submission. I want to un-commitment these line of codes in my views.py b = Business.objects.get(pk=business.pk) about = AboutBusiness.objects.create(business=b) So I can get the value of about.id and add it to my ajax line like this, to redirect to this page; window.location.href = "/seller/addaboutbusiness/about.id"; model.py class Business(models.Model): FLIP_TYPE = ( ('1', 'Buy Out'), ('2', 'Partnership') ) TYPE = ( ('1', 'Business Name'), ('2', 'Sole Proprietorship'), ('3', 'Partnerships'), ('4', 'Limited Partnership'), ('5', 'Corporation'), ('6', 'Limited Liability Company'), ('7', 'Nonprofit Organization'), ('8', 'Cooperative') ) user = models.ForeignKey( User, related_name='business', on_delete=models.CASCADE) flip = models.CharField( "Type of Flipping", max_length=150, choices=FLIP_TYPE) name = models.CharField('Busniess Name', max_length=50) """ status = models.CharField('Registration Status', max_length=50, choices=STATUS) """ status = models.BooleanField("Regsitration Status", default=True) registration = models.CharField( 'Regsitraion Number', max_length=25, blank=True, null=True) t_business = models.CharField( "Business Type", max_length=120, choices=TYPE) approval = models.BooleanField(default=False) created_at = models.DateField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class AboutBusiness(models.Model): """Model definition for AboutBUsiness.""" business = models.ForeignKey( Business, related_name="about", on_delete=models.CASCADE) founder = models.CharField( "OwnerShip Name", help_text="Seperate the name with comma", max_length=500) found = models.IntegerField( ("When Found"), choices=YEAR_CHOICES, default=datetime.datetime.now().year) about = models.TextField("About The Business") #industry = models.CharField(max_length=150) industry = models.ManyToManyField(Industry) location = models.CharField("Business … -
Failed to start gunicorn.service: Job for gunicorn.socket failed . Ubunto 18.04
I am following this How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 18.04 guide. I have created the following file .socket sudo nano /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target I have created the following file .service. How I have formatted my own version sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=guilhermenog Group=www-data WorkingDirectory=/home/guilhermenog/projetoagenda ExecStart=/home/guilhermenog/projetoagenda/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ agenda.wsgi:application [Install] WantedBy=multi-user.target Than I have tried to execute the following code sudo systemctl start gunicorn.socket And i have recibed this message error Job for gunicorn.socket failed See "systemctl status gunicorn.socket" and "journalctl -xe" for details. After i tried the recommended code ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: inactive (dead) Listen: /run/gunicorn.sock (Stream) Apr 26 18:41:45 projetoagenda systemd[1]: gunicorn.socket: Socket service gunicorn.service not loaded, refusing. Apr 26 18:41:45 projetoagenda systemd[1]: Failed to listen on gunicorn socket. Apr 26 18:48:41 projetoagenda systemd[1]: gunicorn.socket: Socket service gunicorn.service not loaded, refusing. Apr 26 18:48:41 projetoagenda systemd[1]: Failed to listen on gunicorn socket. Apr 26 18:52:53 projetoagenda systemd[1]: gunicorn.socket: Socket service gunicorn.service not loaded, refusing. Apr 26 18:52:53 projetoagenda systemd[1]: Failed to listen on gunicorn … -
How do I get rid of djangorestframework Serializer Abstract class warning in Pycharm?
I noticed a warning in Pycharm that won't go a way in my Django project. Only think I can find is a link to it being a PyCharm bug... back in 2016 In my class: class MySerializer(serializers.Serializer): ... I get the following warning: Class MySerializer must implement all abstract methods When I do the quick fix suggested so it ends up looking like one of the following: class MySerializer(serializers.Serializer, ABC): ... # or class MySerializer(serializers.Serializer, metaclass=ABCMeta): ... # or class MySerializer(serializers.Serializer): # have update or create defined in serializer. def update(self, instance, validated_data): pass def create(self, validated_data): pass But this just breaks the project and I'm not too sure what's happening here if I'm being honest or why it wants one of the above solutions to suppress the warning. Is it really a PyCharm bug or am I doing something wrong? -
Django dynamic iframe render
I have a requirement to dynamically generate a pdf in django and print through web page Web Page should have Parameters (from django.form). After entering the parameters and upon POST/submit btn click, iframe below parameter form in html page should get refresh. -
Formsets. Initial data cannot be displayed in ModelChoiceField
In my application, the user can create and edit reports. When rendering the report edit page, the fields are filled with initial data. I ran into the following problem - one of the fields (operator) does not display the value that I pass to it in the view through the initial argument. Instead, the field either remains empty or takes on a default value, depending on the settings. All other fields are filled with initial data without errors. I'm using Formsets, the problem field is ModelChoiceField. The initial data is taken from the json array. As far as I could understand the HTML code - in the problem field "operator", in the "option" tag (it seems to be generated by the Select widget) the "selected" attribute is missing. But how to put this attribute there is not clear. Adding to the confusion is that the "eq_type" field, which is also a select field, is displayed without errors. "selected" appears next to the desired option. Maybe someone came across a similar one? Please, tell me what could be the problem. fragment of forms.py: class AMSEquipmentForm(forms.Form): EQ_TYPES = ( ('panel_antenna', 'панельная антенна'), ('RRL_antenna', 'РРЛ антенна'), ('radio_module', 'радиомодуль') ) eq_type = forms.ChoiceField(choices=EQ_TYPES, label='Тип') … -
How Can I execute search function after click on specific category name?
I have some book category names within Anchor tags on the home page. If a user clicks on a specific category, I want to show them all the books of that category. But I can't get an idea to pass the name of the category from Anchor tag through url.py to views.py and then execute the search function. home.html <ul class="book-catagory"> <li class="list-item"> <a href="{% url 'home' %}">Philosophy</a> </li> <li class="list-item"> <a href="{% url 'home' %}">Litereture</a> </li> <li class="list-item"> <a href="{% url 'home' %}">Computer Science</a> </li> <li class="list-item"> <a href="{% url 'home' %}">Electrical</a> </li> </ul> path in url.py path('',views.home, name='home') views.py def home(request): if request.method == 'POST': searchName = request.POST.get('searchBook') if not searchName : searchName = "" context={ 'data': Book.objects.filter(bookname__contains=searchName) } return render(request, 'library_site/home.html',context) else: context={ 'data': Book.objects.all() } return render(request, 'library_site/home.html',context) -
Django Models 'RelatedObjectDoesNotExist'
Previous Model: class Users(models.Model): first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=10) The code below I added after I already created an Admin Super User username: DeputyCarlos, Password: Password123 I also created a regular User to test my signup & login views username: Johnny, first_name: john, last_name: williams, email: john99@hotmail.com, password: Johnnypassword!23 I then wanted to add an email verification step to my signup view so I followed this tutorial (Sign Up With Confirmation Mail) https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html which I got to succesfully run with some minor adjustments. Current Model: class Users(models.Model): first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=10) verified = models.CharField(max_length=3) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() Using my Current Model I registered a new user with the following: username: clix, first_name: jimmy, last_name: plastic, email: jimmyplastic@gmail.com, password: Stacks8!. I verified my email by clicking on the link and got redirected to my account page. I can freely navigate between my other views but as soon as I logout. I cannot log back in again. I also cannot login using my other username (johnny). I also cannot login into my admin page using my superuser (DeputyCarlos) I get the following … -
How using data of current model into current model :)
Hiii every one. I am new to Django and start to create a basic project and now i have a problem with ImageField and Upload_To i have a model that have some field, like (car_name) and (photo) and i called that "Cars" admin can create a new car and select an image and type a name for that car then admin hit save button and now image should save somewhere I want to save that image into this path: photos/Cars/???car_name??? my question is: how get the name of car and use that name to use in ((upload_to = path))? im really sorry if i have writing issue 🙏🙏🙏 This is my code: class Cars(models.Model): car_name= models.CharField(max_length = 40) photo = models.ImageField(upload_to=f"photos/Cars/{car_name}") -
Why can't I login my user after registering it?
I'm trying to authenticate my user's login request but I keep getting "This username is not valid." even though I did register it previously. The only one that can login so far is the admin but I did not create the admin through the registration page. What's not working and how can I fix it? These are the serializers: user = get_user_model() class UserRegistrationSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all(),lookup='iexact')] ) email = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all(),lookup='iexact')] ) password = serializers.CharField( required=True, label="Password", style={'input_type': 'password'} ) password_2 = serializers.CharField( required=True, label="Confirm Password", style={'input_type': 'password'} ) class Meta: model = User fields = ['username', 'email', 'password', 'password_2',] def validate_password(self, value): if len(value) < 8: raise serializers.ValidationError( "Password should be at least 8 characters long.") return value def validate_password_2(self, value): data = self.get_initial() password = data.get('password') if password != value: raise serializers.ValidationError("Passwords don't match.") return value def validate_username(self, value): if User.objects.filter(username=value).exists(): raise serializers.ValidationError("Username already exists.") return value def create(self, validated_data): user = User.objects.create_user( username=validated_data['username'], password=validated_data['password'], email=validated_data['email'] ) return user class UserLoginSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, write_only=True, ) token = serializers.CharField( allow_blank=True, read_only=True ) password = serializers.CharField( required=True, write_only=True, style={'input_type': 'password'} ) class Meta(object): model = User fields = ['username', 'password', 'token'] def validate(self, data): … -
Django forms get request user
I am building using Django and now when someone tries to post something it makes him choose which user to make the post with. how can I make the value of author same as the request user. this is the form code. class PostForm(forms.ModelForm): class Meta: model = Post fields = ("title", "author", "body", "header_image") widgets = { "title": forms.TextInput(attrs={"class": "form-control"}), "author": forms.Select(attrs={"class": "form-control"}), "body": forms.Textarea( attrs={"class": "form-control", "rows": 4, "cols": 15} ), } and the view code class BlogCreateView(CreateView): model = Post form_class = PostForm template_name = "post_new.html" success_url = reverse_lazy("blogs:posts") -
Django Docker Cron - How can i run crons in docker?
i have a docker with django running on it. Now i want to run a script via cron. But the problem it does not work. If i run the cron manually it works but the cron just dont want to run the command. Cron service is availalbe. Pls help :D -
How to pass extra parameter to validate_foo?
I'm trying to define an empty variable named foo in my base serializer and then let my subclass decide what it should be. Something like a default string. After that I want it to use the variable when validating foo. How would I do this? class BaseSerializer(serializers.ModelSerializer): foo = serializers.Charfiled(read_only=True, help_text='foo') def validate_foo(self, data, foo): # do something with `data` and `foo` -
django docker postgres s3 lambda
AWS announced 4 months ago that "you can now package and deploy Lambda functions as container images", see here for AWS announcement and sample code. I am trying to deploy my Django app in production using this service and setup CI/CD using GitHub. I've been able to figure out the CI/CD deploying a simple Python app using Lambda (no S3 or RDS). However, I don't know how to get Django, S3, Postgres, and Lambda to work together. I am new to Docker and followed this tutorial However, the tutorial does not talk about how to serve the static files using S3 and how to get Lambda, Postgres, and S3 all in the container, persumably because this is a fairly new service. I was wondering if anyone has successfully deployed a Django app for development purposes using these services and can share how the Dockerfile, docker-compose.yml, etc. should look like -
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async
WebSocket HANDSHAKING /tunnelws/ticket/0fa9dd05-0d91-4baa-923e-05f6af6f55a0/ [127.0.0.1:56637] Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\fields\related_descriptors.py", line 173, in get rel_obj = self.field.get_cached_value(instance) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'user' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\staticfiles.py", line 44, in call return await self.application(scope, receive, send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py", line 71, in call return await application(scope, receive, send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\sessions.py", line 47, in call return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\sessions.py", line 254, in call return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\auth.py", line 181, in call return await super().call(scope, receive, send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\middleware.py", line 26, in call return await self.inner(scope, receive, send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py", line 150, in call return await application( File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\consumer.py", line 62, in call await await_many_dispatch([receive], self.dispatch) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\utils.py", line 51, in await_many_dispatch await dispatch(result) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\consumer.py", line 73, in dispatch await handler(message) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\generic\websocket.py", line 175, in websocket_connect await self.connect() File "E:\VirtualLab\VirtualLab\VirtualLab_Server\VirtualLab_Server\guacdproxy\consumer.py", line 42, in connect if ticket.user != self.scope['user']: File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\fields\related_descriptors.py", line 187, in get rel_obj = self.get_object(instance) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\fields\related_descriptors.py", … -
How to correctly serve my React production build through Django. Currently having MIME type issues with current configuration
I'm trying to deploy my react/django web-app to a linux-VM droplet. I'm not using a webpack for the JS content. Instead, I'm serving npm run build static files through a CDN sub-domain, digital ocean s3 bucket. I'm able to python manage.py collectstatic which then pushes my react production build folder to the CDN. When I visit my production website, it currently just loads up a blank page with these console errors: Refused to apply style from 'https://www.my_website_URL.com/static/css/main.ce8d6426.chunk.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Refused to execute script from 'https://www.my_website_URL.com/static/js/2.ca12ac54.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Refused to execute script from 'https://www.my_website_URL.com/static/js/main.220624ac.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. There aren't any network errors that provide any useful information for this matter. The issue has to be server side (django)... I think. Project set up: The react production build is inside my core django folder. Here is how I link my React through django: core urls.py def render_react(request): return render(request, "index.html") #index.html being created by react, not django templates urlpatterns = [ … -
Creating your own sdk for a django website
I have a website on django and I need to create a telegram bot for this site. You need to create an sdk for the site and use it when creating a telegram bot. How can this be done? -
Call a function after creating or updating django model instances
# Do something after each create()/update() or bulk_create()/bulk_update() I want to call a function each time a model instance is created/updated or bulk operation is performed. Where can I put that function so that it is called all these times? I know we can add post_save listener, but I think, it is not called for bulk operations. I am also bulk_updating this model's instances from migration RunPython, so can it trigger that function from migration as well? P.S. I'm using Django 3.1.7 with MySQL -
Django Forms from Model instances in loop
Is it possible to create forms from model instances created in Django's admin? So from a model like this. #models.py # Math, Language Arts, Physical Development etc... class Domain(models.Model): name = models.CharField(max_length=100, blank=False, null=True) display_name = models.CharField(max_length=50, blank=True, null=True) # Shapes, Gross Locomotor Movement Skills etc... class Standard(models.Model): name = models.CharField(max_length=50, blank=False, null=True) domain = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True) Create a form that loops through each Standard/Domain created in Django's admin #forms.py class DomainStandardForm(): fields = [] standards = Standard.objects.get.all() for standard in standards: #create form fields from each Standard End result of DomainStandardForm -
Django 3.2 - how can i made redirect with context?
The main page is block with random instance of model. Also there is a page with form for add new instance . After create new instance i want redirect to main page, but it must render not random instance, it must render instance, which i create. How can i make this? main page controller: def brick_page_foo(request): peekeys = [] for item in Brick.objects.filter(is_published=True): peekeys.append(item.pk) brick = Brick.objects.get(id=random.choice(peekeys)) if brick.image: image_flag = image_flag_foo(brick.image) else: image_flag = 'no_image' context = {'brick':brick, 'image_flag':image_flag,} return render(request, 'brick/bricks.html', context) add form controller: def add_brick(request): if request.method == 'POST': form = BrickAddForm(request.POST, request.FILES) if form.is_valid(): brick = form.save() print(colored(brick, 'yellow')) if brick.image: image_flag = image_flag_foo(brick.image) else: image_flag = 'no_image' context = {'brick':brick, 'image_flag':image_flag,} return render(request, 'brick/bricks.html', context) else: form = BrickAddForm() return render(request, 'brick/add_brick.html', {'form':form})