Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send Form Content to Endpoint in Different App Django
Say I have an app called App1 - inside of which there is a template that has a form with name and email. Now, say I have an app called App2 - that has an endpoint which takes in a name and email and sends an email to that email. Now, I want to combine the two, so that I can make the form contents go to the endpoint in App2 on submit, thus sending an email to the email in the form. How would I do this? Would it be better to just put them in the same app? When would someone use 2 apps over 1? Does this make sense? Thanks for your help! -
Tyring to understand WSGI interface in Django
I was recently trying to undestand the what is WSGI application: a WSGI application is just a callable object that is passed an environ - a dict that contains request data, and a start_response function that is called to start sending the response. In order to send data to the server all you have to do is to call start_response and return an iterable. So, here's a simple application: def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return ['Hello World!'] The Djangos wsgi.py is """ WSGI config for basic_django project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'basic_django.settings') application = get_wsgi_application() But when i see the wsgi.py the application = get_wsgi_application() object does not get passed with environ or start_response function So how to understand this -
Should I change password settings in Django or leave it as it is?
If I am building a website such as social media or even ones where there will be monetary transactions by users, is it a good idea to change the password settings for better security or do the default password settings incorporate better security measures in most cases? -
Django clone recursive objects
previously I have a problem when I want to clone the objects recursively. I know the simply way to clone the object is like this: obj = Foo.objects.get(pk=<some_existing_pk>) obj.pk = None obj.save() But, I want to do more depth. For example, I have a models.py class Post(TimeStampedModel): author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) title = models.CharField(_('Title'), max_length=200) content = models.TextField(_('Content')) ... class Comment(TimeStampedModel): author = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField(_('Comment')) ... class CommentAttribute(TimeStampedModel): comment = models.OneToOneField(Comment, related_name='comment_attribute', on_delete=models.CASCADE) is_bookmark = models.BooleanField(default=False) ... When I clone the parent object from Post, the child objects like Comment and CommentAttribute will also cloned by following new cloned Post objects. The child models are dynamically. So, I want to make it simple by creating the tool like object cloner. This snippet below is what I have done; from django.db.utils import IntegrityError class ObjectCloner(object): """ [1]. The simple way with global configuration: >>> cloner = ObjectCloner() >>> cloner.set_objects = [obj1, obj2] # or can be queryset >>> cloner.include_childs = True >>> cloner.max_clones = 1 >>> cloner.execute() [2]. Clone the objects with custom configuration per-each objects. >>> cloner = ObjectCloner() >>> cloner.set_objects = [ { 'object': obj1, 'include_childs': True, 'max_clones': 2 }, … -
How to filter a ForeignKey in Django Model
I'm trying to filter a field to be shown in the Django admin form: class Buy(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() image = models.FileField(upload_to='images/') date = models.DateTimeField() buy_price = models.DecimalField(max_digits=6, decimal_places=2) sell_price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return f'DM {self.id}' class Sell(models.Model): item = models.ForeignKey(Buy, on_delete=models.CASCADE) def __str__(self): return f'DM {self.id}' The issue is: the Django admin form must show only item > 0 in the Sell model. How can I do that with ForeignKey relationship in a simple way? I tried limit_to but it didn't work with greater than values. -
How can I get my css to render correctly?
So I'm a newbie and I'm having trouble getting my css to render in Django. I am attempting to create a red notification like in Facebook for my unread messages. But my css isn't rendering. What am I doing wrong here? Here's my code settings.py/Static_Dir STATIC_URL = '/static/' STATICFILES_DIRS = [ "/DatingAppCustom/dating_app/static", ] notification.css .btn { width:100px; position:relative; line-height:50px; } .notification { position:absolute; right:-7px; top:-7px; background-color:red; line-height:20px; width:20px; height:20px; border-radius:10px; } base.html/notification section <link href="{% static 'notification.css' %}"> <button class="btn">message counter <div class="notification">{% unread_messages request.user %}</div> </button> -
Cant add the last post to main body at django
I have no idea how to add my last post to the main content. With for loop it just copying the main content several times. I want to have these 3 blocks below to have a post and the last one to be on a main content (where the big picture located). here is the image Below my html code. <div class="container"> <div class="row"> <div class="col s6"> <div class="no-gutters"> <span style="color:pink; font-weight:bold; font-size:22px">NEW</span> <i class="small material-icons md-dark">favorite_border</i><span>25</span> <img src="{% static "images/comment.png" %}"><span>25</span> <i class="small material-icons md-dark">remove_red_eye</i><span>25</span> </div> <h2 class="blue-text">Some text/h2> <p>My last post</p> <a class="waves-effect waves-light btn-large"><span class="read">Read</span></a> </div> <div class="col s6"> <p> <img src="{% static "images/1Statya_3.png" %}" width="694px" height="568" /></p> </div> </div> </div> <hr> <div class="container"> <div class="row"> {% for post in posts %} <div class="col s12 m4"> <div class="card hoverable small"> <div class="class image"> <p>{{ post.date_posted }}</p> <img src="{% static 'images/1Statya_2.png' %}" class="center"> <span class="card-title">{{ post.title }}</span> </div> <div class="card-content"> <p>{{ post.content }}</p> </div> <div class="card-content"> <a href="#">Link blog</a> </div> </div> </div> {% endfor %} -
MODEL object has no attribute 'get' || django
I was trying to show the friends [model = FriendList] anyone have. so even if i used get to get the primary key....its giving an error. this is my models.py class Profile(models.Model): Gender = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ) user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) full_name = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(null=True, blank=True) birth_date = models.DateTimeField(null=True, blank=True, auto_now=True) gender = models.CharField(max_length=20, choices=Gender, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) def __str__(self): if self.full_name == None: return "Full Name is NULL" return self.full_name class FriendList(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) profile = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return str('%s -> %s' % (self.user.username, self.profile.user.username)) this is my views : def friend_list(request,pk): friends = FriendList.objects.get(id=pk) friend_list = None for i in friends: friend_list += i.user.username context={ 'friends':friend_list } return render(request, 'details/friend_list.html', context) why i'm gettig getting this error..... -
How to visupadding and margins in django templates and reducing white space between rows in bootstrap
I'm new to html and Django, and Bootstrap. I sometimes have trouble understanding the padding and margins. Is there some kind of clever way to use CSS to show the padding and margins visually. From what I can tell margins don't have a background color and are transparent. For example in the code below I would like to reduce the vertical space between the fields so the form would be more compact. If I just use HTML I don't seem to have a problem, but when I am using widget_tweaks I get additional space between the rows. {% load widget_tweaks %} {% block content%} <div class="containter p-4"> <div class="py-0 text-Left"> <div> <h2>Just a title for the page:</h2> </div> <form action="{% url 'addINNO:add_new' %}" method="POST"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form.visible_fields %} <div class="row py-0 "> <div class="form-group py-0 col-9"> <div class="form-group py-0"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% if field.id_for_label == 'id_description' %} {{ field|add_class:'form-control p-0'|attr:"rows:3"}} {% for error in field.errors %} <span class="help-block">{{ error }}</span> {% endfor %} {% elif field.id_for_label == 'id_comment' %} {{ field|add_class:'form-control p-0'|attr:"rows:2"}} {% for error in field.errors %} <span … -
Website with Django 3 and django_plotly_dash does not update website
I have a website that contains a dashboard that is based on plotly-dash. I want to change it and I can see the changes when running ./manage.py runserver, but not when serving is with nginx. I did ./manage.py collectstatic Also deleted all .pyc files and __pycache__ and restarted supervisor and nginx with : sudo supervisorctl stop all && sudo supervisorctl reread && sudo supervisorctl update && sudo supervisorctl start all && sudo service nginx restart Which runs through. What did I miss? -
how to use keras model that passed from other python file at django
First I work in django-envirment. I want to load keras model from settings.py and pass the model to function.py so that I can use the model in functions.py. but I'm getting the following error: InvalidArgumentError at /camera2/ Tensor input_1:0, specified in either feed_devices or fetch_devices was not found in the Graph Some people answer this type of error to use this code: from tensorflow import Graph, Session import tensorflow as tf import keras thread_graph = Graph() with thread_graph.as_default(): thread_session = Session() with thread_session.as_default(): model = keras.models.load_model(path_to_model) graph = tf.get_default_graph() and def _load_model_from_path(path): global gGraph global gModel gGraph = tf.get_default_graph() gModel = load_model(path) But that didn't work for me and I guess that answer works for loading model in multi threaded case. I don't know how to fix this error My code is below ################################################### # settings.py/the file where to load the models ################################################### from keras.models import load_model ... MODEL_ROOT = os.path.join(BASE_DIR, 'yeom') GMODEL = load_model(MODEL_ROOT +'/MobileNetV2(full).h5') #################################################################### # function.py/the file to which settings.py passed the keras model #################################################################### from django.conf import settings ... model = settings.GMODEL pred_y = model.predict(image_data) ... ... is omitted code section -
What is the best practice for storing glabal variables of a django App?
There are a few variables that are unique for my website. For Illustrative purposes let's assume it is a Blog, and the variables I am interested in are the total number of users, the total number of posts, the total number of comments in posts, the average length of a user session, and a few others. I can create a model with these parameters, and it will have a single row with all the values, but this might be a bit of an overkill. I was wondering if there was a better (pythonic?) way of doing this. -
Python Django multiple attributes in search
So I have this search form: [Doctor][Specialty][City] This is the form in HTML: <form data-provide="validation" data-disable="true" class="input-glass mt-7" method='POST' action='annuaire/'> {% csrf_token %} <div class="row"> <div class="col-md-4"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><i class="ti-search mt-1"></i></span> </div> <input type="text" class="form-control" placeholder="Doctor's Name" name="kw_name"> </div> </div> <div class="col-md-4"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><i class="ti-search mt-1"></i></span> </div> <select class="form-control" name="kw_specialty"> <option value="" disabled selected>Specialty</option> {% for spec in specialties %} <option>{{ spec }}</option> {% endfor %} </select> </div> </div> <div class="col-md-4"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><i class="ti-search mt-1"></i></span> </div> <select class="form-control" name="kw_city"> <option value="" disabled selected>City</option> {% for city in cities %} <option>{{ city }}</option> {% endfor %} </select> </div> </div> </div> <div class="row mt-2"> <div class="col-md-12"> <button class="btn btn-lg btn-block btn-outline-light" type="submit" name="search_btn">Search</button> </div> </div> </form> Before I talk about my view.py content, I would like to mention my problem first: The search form has many cases, and the users don't have to fill all three filters. But if they leave the text input empty, the results will be ALL. I want the search function to ignore the text field if it's empty (only consider it if it has a value in it). Also, if the 2 dropdowns are Null … -
Django checking if same object exists in database when user trie to add object:
I have an application that users can take what courses they are taking and there is a many to many relationships between users and a course. Now when a user wants to add a course I want to check if they have not added the same course with the partial same value, for example, the same course code and year. Currently, my view is: @login_required def course_add(request): if request.method == "POST": form = CourseForm(request.POST or none) if form.is_valid(): course = form.save(False) for c in request.user.courses.all(): if course.course_code == c.course_code and course.course_year == c.course_year: form = CourseForm message = "It's seems you already have added this course please try again." context = { 'form':form, 'message': message, } return render(request,'home/courses/course_add.html', context) request.user.courses.add(course) return redirect('home:courses') else: form = CourseForm context = { 'form':form } return render(request,'home/courses/course_add.html', context) in my user model I have this line: courses = models.ManyToManyField('home.Course',related_name='profiles') an my course model is: class Course(models.Model): course_code = models.CharField(max_length=20) course_name = models.CharField(max_length=100) course_year = models.IntegerField(('year'), validators=[MinValueValidator(1984), MaxValueValidator(max_value_current_year())]) def __str__(self): return self.course_code As you can see my intention is I don't want the user to be able to add a course if they're code and year exists regardless of the course name. How can I … -
Deploy Django app on Raspberry Pi with Domain Name
I am creating an application which will need to access a database. Since it is a small scale application I do not want to spend a ton on hosting and have a pi lying around. My plan was to have an SQL server and some sort of API on a pi and access it from the application (on other networks also). Is there an easy way to access a Django app via a purchased domain name on the pi and if so could someone list the basic steps. Otherwise, is it just better to spend a few dollars a month to host it on Digital Ocean or something similar? Thanks in advance. -
How to serve a Flutter web app with Django?
After building a flutter web app with flutter build web I want to serve the app using a simple Django server. How can I do that? -
Django-Filters Lookup_expr type 'AND'
Does Django-Filters have a lookup_expr equivalent to 'AND'? I am using Django filters with DRF to filter by multiple categories on the same field. Example: I have a category list field that accepts multiple categories categories = ['baking', 'cooking', 'desserts', 'etc'] Using the solution outlined by udeep below I got the filter to work rather well https://stackoverflow.com/a/57322368/13142864 The one issue I am running into is with the lookup_expr="in" This works as an 'OR' expression. So if I provide a filter query of categories=baking,cooking It will return all results that contain either 'baking' OR 'cooking' Is there a lookup_expr in django_filters that profiles an 'AND' functionality so that when I make the same query I get only results that contain both 'baking' AND 'cooking'? I have looked at all of the django filter docs https://django-filter.readthedocs.io/ And all of the django queryset filter where many of these type of filters seem to originate from https://docs.djangoproject.com/en/3.0/ref/models/querysets/ But unfortunately, I have had no luck. Any direction you can provide would be much appreciated. -
ModuleNotFoundError: No module named 'rest_framework.filtersuser'
I'm getting this weird error after adding rest_framework.filters. Things I tried:- 1) Removing then re-installing. 2) Tried using django-filters instead. I have included rest_framework.filters in installed apps in settings.py. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "E:\virtual environments\leaseit_api\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "E:\virtual environments\leaseit_api\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "E:\virtual environments\leaseit_api\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "E:\virtual environments\leaseit_api\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "E:\virtual environments\leaseit_api\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "E:\virtual environments\leaseit_api\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "E:\virtual environments\leaseit_api\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "E:\virtual environments\leaseit_api\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework.filtersuser' -
Django-rest-framework: different - django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_user.password
I am using django-rest-auth for authentication. Registration,login,logout are working properly but when I try to edit user detail through admin panel, password field is behaving like not required field neitherless it is not nullable field and therefore giving me following error. Does anything wrong in the code,Please help me out with it. models.py class CustomUserManager(BaseUserManager): def _create_user(self,username, email, password, is_staff,is_admin, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, username=username, is_staff=is_staff, is_active=True, is_admin=is_admin, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self,username, email, password=None, **extra_fields): return self._create_user( username, email, password, False, False, False, **extra_fields) def create_staff(self,username, email, password, **extra_fields): user = self._create_user( username,email, password, True, False, False, **extra_fields) user.save(using=self._db) return user def create_admin(self,username, email, password, **extra_fields): user = self._create_user( username,email, password, True, True, False, **extra_fields) user.save(using=self._db) return user def create_superuser(self,username, email, password, **extra_fields): user = self._create_user( username,email, password, True, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser): username = CharField(_('username'), max_length=100,unique=True) email = EmailField(_('email address'), unique=True) is_staff = BooleanField(default=False) is_admin = BooleanField(default=False) is_active = BooleanField(default=True) is_superuser = BooleanField(default=False) last_login = DateTimeField(auto_now=True) date_joined = DateTimeField(auto_now_add=True) full_name = … -
Django 3, non ASCII signs handling
I have a problem with special signs, for example polish signs (ą,ć,ń,ź etc). When I'm adding some model object to database using django server it malform to some completely different signs. It looks like some problem with coding signs, but database looks kind good because when I add new row directly in MySQL Workbench then signs are correct. But when I'm doing it with django and Django rest framework to be more specific, then signs are changing into something else. -
VUE CLI error: Access to XMLHttpRequest has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
Sorry if this question has been answered. I've searched over 40 answers on StackOverflow, vuejs forum, blogs, etc, but they don't work, or I don't understand them. Please point me in the right direction if necessary. I'm running two servers locally. One VueCLI 127.0.0.1:8080 and the other, my django project with django restframework 127.0.0.1:8000. I get the following error when I call the API (note that it includes the last forward slash): Access to XMLHttpRequest at 'http://127.0.0.1:8000/…/‘ from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. However, I get a 200 response on my django server (so it's hitting the server, and the server is responding): [03/May/2020 18:20:10] "GET /api/inventory/product/ HTTP/1.1" 200 7893 I've installed django-cors-header and setup settings.py accordingly: CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:8080', ] INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', .... ] This is my call from my VueCLI component: const axios = require('axios') let url = `http://127.0.0.1:8000/api/inventory/product/` axios .get(url) .then(response => { console.log(response) }) Please point out what I'm doing wrong or what I should do. -
Django can not find my template, when it is actually in the templates directory inside the app
I am working in some CRUD views using class based views from django but when i want to add a createview Django returns an error saying that the template does not exists when in fact there it is, but i cant not find any error. View class SchoolCreateView(CreateView): model = School fields = ('name','principal','location') school_form.html Template {%extends 'firstapp/base.html'%} {%block body_block%} <h1> {%if not form.instance.pk%} Create School {%else%} Update School {%endif%} <form method="POST"> {%csrf_token%} {%form.as_p%} <input type="submit" value="submit"> </form> </h1> {%endblock%} -
How Can I get the location of a user app from another user of same app
I’m trying to build a simple pick up and delivery app. I want a user to submit a pickup location and delivery location. Then as soon as the user submits I want to be able to get the locations of the riders’ apps but I don’t know how to go about it. It’s just like a normal for example uber app that searches the drivers locations and calculates the nearest one. Calculating the nearest one is not the issue as I can do that with google maps api, but how can I get the riders app location from the backend.? Thank you in advance. -
Inline Boostrap Cards using Django For Loop
I am using Bootstrap to make my website loop better, but I am having trouble organizing my cards in a horizontal line since I am using Django For loop to render information: html <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Coaches</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </head> <body> <div class="container"> {% for programas in programas_entrenamiento %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{programas.foto_programa.url}}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{programas.programas}}</h5> <p class="card-text">{{programas.descripcion|truncatechars:50}}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> {%endfor%} </div> models.py class ProgramasEntrenamiento(models.Model): programas = models.CharField( choices=EXERCISE_CHOICES, max_length=200, null=True) descripcion = models.TextField() foto_programa = models.ImageField(upload_to='pics/programas', null=True) def __str__(self): return self.programas Current output Expected output (sorry for bad editing) -
DjangoCMS carousel slider doesn't fit to fullscreen
i am working on a project in Djangocms. In frontage i want to put a background carousel. When i put the image sliders on it through edit, it doesn't fit to screen. i try use fluid container but it shows padding/space around it. Besides i tried to use style row column along with alignment through edit in toolbar, padding grows bigger. Should i have to do manual coding? is there any document on Djangocms carousel plugin? what is the way to edit the carousel design in Djangocms?