Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djnago Razorpay integration
I want to integrate my website with razorpay, but I am lacking with the correct resource or tutorial for that. Actually I want a wallet in my website in which a user add money in his/her wallet by simply entering the amount in form and submitting the form. But I don't known how to link all files like models.py views.py urls.py and as well as the templates file. The attempt is given below please help! class PaymentDtails(models.Model): paymentby=models.OneToOneField(User,on_delete='CASCADE',null=True) razorpay_id = models.CharField(max_length=255) payment = JSONField(null=True, blank=True) amount=models.IntegerField(default=0) forms.py class AddMoneyForm(forms.ModelForm): class Meta: model= PaymentDetails fields=('amount',) please help me to integrate all that -
Chat application between user and customers
want to create a simple chat application between users and customers with the help of Django Channels.. this is my model. class ExternalMessageModel(models.Model): """ This class represents a chat message. It has a owner (user), timestamp and the message body. """ customers = models.ForeignKey('customers.Contact', on_delete=models.CASCADE, verbose_name='customer', related_name='from_customer', db_index=True) users = models.ForeignKey('users.UserProfile', on_delete=models.CASCADE, verbose_name='users', related_name='to_user', db_index=True) timestamp = models.DateTimeField('timestamp', auto_now_add=True, editable=False, db_index=True) body = models.TextField('body') I know how to create a chat application between users and users. but here my requirement is a bit different I have two tables one or user and another for customer.so my requirements are reals time communication between users and customers -
Django: the post isn't selected automatically of particular user
hi am working on a project where am using multiple user data a user did a post onto the site and when driver see that post he adds their offer to that post but when driver submit the post ...at the admin level the particular is selected automatically but the post is not selected on which he adds price this is my post model.py class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) this is my second model of adding price to a particular post class price(models.Model): my_post = models.ManyToManyField(Loader_post, related_name='prices') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') driver_price = models.CharField(max_length=150, null=True) driver_name = models.CharField(max_length=150, null=True) approved_price = models.BooleanField(default=False) status = models.BooleanField(default=False) this is my adding price to the post views.py @login_required def add_price_to_post(request, pk): post = get_object_or_404(Loader_post, pk=pk) user = request.user if request.method == "POST": form = price_form(request.POST) if form.is_valid(): ps = form.save(commit=False) ps.user = request.user ps.status = True ps.post = post ps.save() return redirect('Driver:Driverview') else: form = price_form() return render(request, 'price_form.html', {'form': form}) this is my html add post button {% for loader in Loader %} this is loop and this is button <a … -
Linking Foreign key between tables in django models
I am just starting out with Django and so please help me out with my doubt. Currently, I have three tables Topic, Webpage, and AccessRecord. In the third table AccessRecord, I have used a ForeignKey with the second table Webpage. But Webpage table has three attributes topic, name, and URL ..so my doubt is which attribute of these three will be treated as a Foreign key to AccessRecord table. Any help will be greatly appreciated. class Topic(models.Model): top_name = models.CharField(max_length=264,unique = True) def __str__(self): return(self.top_name) class Webpage(models.Model): topic = models.ForeignKey(Topic,on_delete=models.CASCADE) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage,on_delete=models.CASCADE) date = models.DateField() def __str__(self): return str(self.date) -
Sentry cloud database migration: Cannot see the migrated data in the new Sentry install
Here is the issue I am seeking to resolve: I am in the process of migrating a production Sentry instance (hosted on Nomad) onto a new new install (hosted on AWS ECS), both currently on version 9.0.0. Both the current and the new Postgres databases are hosted in AWS RDS. Same for Redis, they are both managed by AWS (i.e. ElasticCache). I have used two methods to migrate the database: (1) AWS RDS snapshot/restore, and (2) pg_dump, and pg_restore methods; and both worked successfully from the database perspective. The new database seems fine to me, with all tables exactly the same as the original database. However, when loading and hitting the new hosted Sentry instance, I can only see one empty Sentry organization, no teams, no project. Empty. I haven’t migrated the Redis database, but I can’t see why this would be the cause of it, given it’s a cache mechanism only. The source Sentry install instance also uses SAML2 for SSO. I cannot see any of that configuration, and any of that original data in the new install. What am I missing? Thank you. -
conect django to datastax casandra
I am try to conect django to datastax casandra but i cant do this. my database conection is here : DATABASES = { from cassandra.auth import PlainTextAuthProvider from cassandra.cluster import Cluster 'default': { cloud_config= { ` 'secure_connect_bundle': 'secure-connect-okul.zip'` } auth_provider = PlainTextAuthProvider('mahmut215', 'm11223344m') cluster = Cluster(cloud=cloud_config, auth_provider=auth_provider) session = cluster.connect() } } ` Help me please . -
How can I solve "cannot import name 'main' from 'virtualenv'"?
When I try running virtualenv I get the following error: [jelly@laptop Getskilled]$ virtualenv venv Traceback (most recent call last): File "/usr/bin/virtualenv", line 6, in <module> from virtualenv import main ImportError: cannot import name 'main' from 'virtualenv' (/home/jelly/.local/lib/python3.8/site-packages/virtualenv/__init__.py) Virtualenv was working when I last used it for a project so I am guessing that an update cause it to break. I have tried reinstalling virtualenv and pip. The closest post I could find was this one: virtualenv: cannot import name 'main' I tried following this post so I ran the following in the python interpreter: import virtualenv virtualenv.__file__ Which returned: '/home/jelly/.local/lib/python3.8/site-packages/virtualenv/init.py' However, there was no file /usr/local/bin/virtualenv.py and there is no virtualenv.py in the .local directory so that solution in that post won't work for me. What can I try next? -
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'