Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i add order detail to paypal smart button checkout
Hi i am building an ecommerce website with django and i was looking for a way to pass order details to the merchant account. I have tried this createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '30.11', }, description: 'this is a description', }] }); }, this method worked but i can only pass strings. I have tried to pass lists but it didn't work createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '30.11', }, description: [{ order: "dress5", price: "30" }] }] }); }, any recommendations on what i should do? -
Python, Django: Alternative to a raw-sql-query
Good evening, I would like to ask, if there's a different method to a raw sql query to update items by a certain condition inside my views.py? For example, I know I could do an insert query like this: models.py class Person(models.Model): name = models.CharField() age = models.IntegerField() value = models.IntegerField() views.py def something(request): ... qs = Person(name="John Doe", age=34, value=10) qs.save() ... Is there a similiar method for updating all "Persons" if they fit a certain condition? ... qs = Person("UPDATE Person SET value=5 WHERE age < 30") # or something like this qs.save() ... Thanks for all your help and advice and a great weekend to all of you! -
Custom threaded django comments - django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I am using django 3.1x and I'm following the example here to create a threaded comment app for my project. The article instructs to add the following lines to the __init__.py file so that django can use these hooks to lookup the altered models and forms and to overrides the default set. Here is the content of __init__.py: from models import MPTTComment from forms import MPTTCommentForm def get_model(): return MPTTComment def get_form(): return MPTTCommentForm The error message makes sense, because we appear to be importing objects that have not yet been created ... However, the author of the article states that it works - and none of the comments (granted, they are a year old) seem to be complaining of this issue. Am I missing something, or has the internals (loading sequence of django) changed? How do I fix this? -
Reverse for 'operation_info' with keyword arguments '{'id_operation': ''}' not found
I had this problem while trying to pass arguments through the template this is my urls.py path('Operation/Info/<id_operation>',views.operation_info,name='operation_info'), and this is my template {% for o in operation_list %} <tr><td scope="row">{{ o.nom_operation }}</td><td>{{ o.date_prevu }}</td><td><a href="{% url 'operation_info' id_operation=c.id %}"><i class="fa fa-info" style="color:green;font-size:33px;"></i></a></td></tr> {% endfor %} this is my view : def caravane_info(request,id_caravane): connected = request.user.is_authenticated if connected: U_ID = request.user.id F = Membre.objects.get(userr_id=U_ID) bureau_level = F.Grade_bureau caravane = Caravane.objects.get(id=id_caravane) return render(request,'Bureau/operation_info.html',locals()) -
django html template not loading from generic view from model
Introduction I am currently working on a small piece of the project to understand more about the Django ORM and to display individual objects. Using Generic views to keep the code clean. (I am somewhat new to Django Framework) Goal The goal of this piece is to show how many users have written an article. For example, I have total of 4 articles. I need to show how many articles written by each user. My console output: User Article Count testuser 2 testuser1 2 testuser2 0 my output on the HTML template: User Article Count testuser 0 testuser1 0 testuser2 0 Problem I am not understanding why my console output is correct, but my HTML template isn't showing the results. Please HELP me understand why it is doing this!!!!! If there is a similar post let me know! I have been looking everywhere for the answer, but I couldn't find it on the internet. Code views.py from django.views.generic import ListView from .models import Article from django.contrib.auth import get_user_model class ArticleListView(ListView): model = Article template_name = 'article_list.html' context_object_name='article_list' queryset=Article.objects.order_by('-date') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) users = get_user_model().objects.all() context["users"] = users articles = Article.objects.all() for user in users: article_count = articles.filter(author__exact=user).values('author').count() … -
Dajngo Model embed multiple Abstract Models
Suppose I have an Order model for storing customers' orders on my site. There will be two address fields: shipping_address and billing_address. I could write it something like this: class Order(models.Model): order_number = models.CharField() time_created = models.DateTimeField() ... shipping_name = models.CharField() shipping_city = models.CharField() shipping_street = models.CharField() shipping_building = models.CharField() billing_name = models.CharField() billing_city = models.CharField() billing_street = models.CharField() billing_building = models.CharField() ... Then access fields by order.shipping_name and order.billing_name, but that is getting really cumbersome when every address needs to contain 15-20 fields. I tried One-to-One relationships, but code in other places of the application becomes very complicated. If there would be only one address field I could use an Abstract Model to make it a bit cleaner: class Address(models.Model): class Meta: abstract = True name = models.CharField() city = models.CharField() street = models.CharField() building = models.CharField() ... class Order(Address, models.Model): order_number = models.CharField() time_created = models.DateTimeField() But this way I can only have one set of address data and field names from the Address class would clash with fields from Order. Is there a way to inject or embed fields with given prefix in DB to given Model? I am looking for something similar to @Embedded decorator used … -
Django rest framework charfilter json
I have a filter in django rest charfilterinfilter(field_name= 'genres__name', lookup_expr= 'in').I have in the database is which two categories to approach I through Many To Many did ,But I have when filtrating two categories of this product there are two elements I need only one element views class CharFilterInFilter(filters.BaseInFilter, filters.CharFilter): pass class ShoppFilter(filters.FilterSet): price = filters.RangeFilter() genres = CharFilterInFilter(field_name='genres__name') title = SearchFilter() class Meta: model = smartphone fields = ['price','genres','title'] class MDShopListView(generics.ListAPIView): queryset = smartphone.objects.all() filter_backends = (DjangoFilterBackend,SearchFilter) search_fields = ['title'] filterset_class = ShoppFilter def get(self, request): queryset = self.filter_queryset(self.get_queryset()) serializer=MDShopListSerializer(queryset,many=True) return Response(serializer.data) models genres = models.ManyToManyField(Genre, verbose_name="жанры") class Genre(models.Model): [enter image description here][1] name = models.CharField("Имя", max_length=100) img json 1: https://i.stack.imgur.com/4WR6L.png -
How do I add 3 different licenses with 3 different prices in django Models
I have a product and I wanted to add three purchase options that depend on the license you buy. For example: class Product(models.Model): productname = models.CharField(max_length=200) license = models.???? There should be a multiselector here in order to select all three licenses when applicable. But how? discription = models.TextField() image = models.CharField(max_length=5000, null=True, blank=True) class License(models.Model): Here should be some kind of choice field that connects the price to the choice.... but how??? Help please. -
How to use Django channels to push newly created data to client side without reloading and not completely changing the existing normal view code
Hey guys I am quite new to django and django channels. I have a small doubt related to channels. For example, if I have a post model and I created a post, for the user to view the post, they need to either reload the page or we need to redirect them to the list page to view all the posts. What if I want to push the newly created post to the front end or to the client side without having them to reload the page? Can we use channels for that? And if we use channels for that purpose, do we need to rewrite all the codes we wrote in normal views or adding a snippet code like sending a signal when created and running an async function will do the trick? Is it difficult to implement? Thanks -
How add a custom SLA in Defect Dojo
I know that there are a option to define the default SLA days in Defect Dojo... But I have a especial finding that the SLA is diferent that my default SLA, is there option to custom de SLA to only one finding? For exemple: My SLA to High is 30 days, in default SLA in System Settings, but this Especial Finding is high with 60 days of SLA, can I change the SLA only this finding? Thanksss!!! -
Django Admin doesn't load the static files - Deployed on cPanel
I just tried to deploy a test app on my Shared Hosting and while my homepage seems to show static files perfectly, my Django Admin doesn't seem to load any static files whatsoever: My STATIC settings look like this: STATIC_ROOT = '/home/user/django/static' STATIC = '/static/' I have already executed the collectstatic command which copied all the required files to my STATIC ROOT directory Can someone help me resolve this? -
how to automatically set a superuser on creation a user type
I am using making use of some user_types in my application which are is_admin and is_landlord. I want it that whenever a user is created using the python manage.py createsuperuser. he is automatically assigned is_admin. models.py class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = datetime.datetime.now(pytz.utc) email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, 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, email=None, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user = self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) # CUSTOM USER FIELDS name = models.CharField(max_length=30, blank=True, null=True) telephone = models.IntegerField(blank=True, null=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) def get_email(self): return self.email class user_type(models.Model): is_admin = models.BooleanField(default=False) is_landlord = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): if self.is_landlord == True: return User.get_email(self.user) + " - is_landlord" else: return User.get_email(self.user) + " - is_admin" Note: I want a superuser created to automatically have … -
Connect Django to Sql server 2019
I create a new project in django and i was trying to connect to sql server 2019. So i install sql-server-2019 and after install , i check if ODBC DRIvers was ok, and as you can see , all ok so far. The next thing i do , was pip install django-pyodbc-azure I have more packages instaled because i was testing with everyhing i find , and so far i allways have the same error. it means conn = Database.connect(connstr, django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name was not found and no predefined driver (0) (SQLDriverConnect) was specified) and here is my settings.py from django: I'm stuck here, I don't even know what I can to go on -
Django Login/Authenticate user by clicking email link?
Hey Everyone I am working on creating a custom EmployeeForm in which the form is for Business Administrators, to add employees. This creates a new user Account in the database. In order to give this employee access to the platform, a temporary unique password is also set for them. On creation, an email is sent to the new employees account email providing them with their email, and randomly generated password. I would like to also include a link to send them straight to the Change password view. With the click of this link, I want it to login the user, so that they don't have to go to the login page themselves, so that they are already authenticated/logged in, and all they have to do is type in their new password. I'm wondering if it is possible to log this user in automatically with the click of the "change password" link? I am also wondering if there is even a possible way to not even set a random password, and allow the user to just click the email link, and they are free to set their initial password themselves. (Note: password is not a required field, so the employee account … -
Is there a standard/commonly-used decision table library for python?
So here's the problem I'm having, and I'm sure it's a common one. I have a pre_save trigger set up for a model such that before a model instance is saved to the database, a series of checks and modifications are made to it depending on the characteristics of some of its fields, some aggregate values calculated with respect to other instances of the model and other models, and some threshold constants for the model. What I have right now works, but it is an ungodly mess of if-else statements that is completely unmaintainable. Obviously a decision table is required, but I can't seem to find anything besides the odd github project with only a few stars. Because of this I've made my own decision table class that seems to work on its own (yet to integrate into my project), but I'd much rather use something that has been widely tried and tested if it exists. Maybe there is something specific to django, that I've overlooked? Any suggestions would be greatly appreciated! -
Using DRF and React for Contact form
I haven't seen anybody accept the form like this using DRF. I'm practically listing all of the fields for the POST method. Is it safe to do so? class ContactForm(generics.ListCreateAPIView): queryset = Contact.objects.all() serializer_class = ContactSerializer @action(methods=['GET'], detail=True) def testing_env(self): return Response({'Works': 'ayyy'}) @action(methods=['POST'], detail=True) def create_contact(self, request): data = request.data print(data) contact = Contact.objects.create(name=data['name'], email=data['email'], subject=data['subject'], message=data['message']) contact.save() return Response({'Success': 'it went good'}) And here's the React Form: handleSubmit(event){ event.preventDefault(); let data = this.state axios({ method: 'post', url: FormURL(), data:{ name: this.state.name, email: this.state.email, subject: this.state.subject, message: this.state.message, } }) } -
Django Project DEPLOYMENT - SECRET KEY
I'm deploying a Django Project on pythonanywhere. This is my first time doing anything of this kind, and I forgot to delete the secret key of my project before pushing it to GitHub (my GitHub account is private), so now the secret key is available in the code in GitHub. Is that a big problem ('cause I still didn't understand what is the key used for)? Is there a way to fix this? I read some articles online and they suggest to keep the key in envoirment variable or stored in a file but I don't have any idea of how to do that or how to change the fact that now the key is available on my GitHub account and on python anywhere since I did git clone. Can someone help me please? -
how to customize a modelform for multiple question
Right now I am able to store an object for the current question which is defined in views.py. A student comes and selects a specific Teacher and answers the question from multi-choice. But this is for one question that is assigned this way. I want my codes to work like: One selection field for Teacher for the entire form. One rating choice for each question. What is the best way to implement an evaluation system form? models.py RATING_CHOICES = ((1, "Weak"), (2, "Average"), (3, "Good"), (4, "Excellent")) class Question(models.Model): question = models.CharField(max_length=200) def __str__(self): return self.question class Teacher(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Student_Answer(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) forms.py class AnswerForm(ModelForm): class Meta: model = Student_Answer exclude = ['question'] widgets = { 'answer': RadioSelect(choices=RATING_CHOICES)} views.py def index(request): form = AnswerForm() question = Question.objects.get(id=1) if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.question = question form.save() return HttpResponseRedirect('/redirected/') else: form = AnswerForm() context = { 'question': question, 'form': form } return render(request, 'index.html', context) index.html <form action="{% url 'index'%}" method="POST"> {% csrf_token %} {{ form.teacher }} <br> {{ question }} <br> {{ form.answer }} <input type="submit" … -
django html video tag
I'm trying to do a project in django. I created the HTML-CSS page. I'm playing a video in the background of my HTML page. When I run this on local, I can see the video playing in the background. But when I add my HTML page's codes to django it doesn't show up. My video tag in html code(source part) like this; src="homevideo.mp4" type="video/mp4" IN DJANGO; project name : lubdub appname : accounts views.py def home(request): return render(request,'accounts/home.html') setting.py STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), ) templates videos homevideo.mp4 Would anyone help me plase? I'm so confused.Thx -
How to deploy Django app with PostgreSQL on GCP at minimum cost for minimal server load?
I need to deploy a Django app using PostgreSQL as the database on Google Cloud Platform. Since the app is only for my personal use, it has a minimal server load. I tried a solution by deploying my app on an F1 App Engine standard environment(us-central1 region) and ran a PostgreSQL instance on an f1-small compute engine(us-central1 region). Both these are provided in GCP free tier in the us-central1 region. But it seems a VPC serverless connector is needed for app engine standard to access Postgres on compute engine on internal IP address.(which is billed as 2 e-2 micro instances). Is there a better way of deploying it on GCP or connecting App engine standard with compute engine private IP, which incurs lesser cost? -
Django not logging anything levels less than WARNING
I am not sure why django is not logging anything less than "WARNING" level. I have this code in the view: logger = logging.getLogger(__name__) def profile_data(request): logging.info("INFO PROFILE DATA!!") logging.debug("DEBUG PROFILE DATA!!") logging.warning("WARNING PROFILE DATA!!") logging.error("ERROR PROFILE DATA!!") and this in my settings.py: # Logging LOGGING = { 'version': 1, # Version of logging 'disable_existing_loggers': False, 'filters': { # information regarding filters }, 'formatters': { '<simple_format>': { 'format': '{levelname} {message}', 'style': '{', } }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/logs/log_file1.log', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler' }, }, 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, 'root': { 'handlers': ['file', 'console'], 'level': 'DEBUG', } } } As you can see, I try to set everything to the DEBUG level, it doesn't work, I only see this is the warning and error level in the terminal: WARNING:root:WARNING PROFILE DATA!! ERROR:root:ERROR PROFILE DATA!! -
how to use if and else in my django forloop
I am trying to use an if else statement in my django template so that if the bars exist it displays them but if not then it lets me know that there are no bars available. template.html <div class="row"> {% for bar in bars %} <div class="col-md-4 col-lg-4 col-sm-12 col-xs-12" style="margin-bottom: 25px!important;"> <div class="single-promotions text-center"> <div class="promotions-img"> <img src="{{bar.image.url}}" class="img-fluid" style="height: 350px; width: 100%;" alt=""> </div> <div class="promotions-details"> <h4>{{bar.name}}</h4> <h5><span>{{bar.opening_time}} -</span><span> {{bar.closing_time}}</span></h5> <h5>{{bar.address}}</h5> <a href="{% url 'reserve' bar.pk %}" class="read-more">Book a Table</a> </div> </div> </div> {% endfor %} </div> I have tried some methods but it didn't display any thing whether the bars existed or not -
unable to upload image to s3 from django app
When a user creates a new account on my website, an image is created(generated) and is supposed to be uploaded to s3. The image is successfully created(verified by running the ls command on the server in the media directory) but it's not getting uploaded to s3. However, when I try uploading an image for a user account from the admin panel, changes are correctly reflected in s3 (i.e newly uploaded image from admin panel is shown in s3 bucket's directory). I aim to auto-upload the generated image to the s3 bucket when a new account is created. views.py def signup(request): if request.method == "POST": base_form = UserForm(data=request.POST) addnl_form = AddnlForm(data=request.POST) if base_form.is_valid() and addnl_form.is_valid(): usrnm = base_form.cleaned_data['username'] if UserModel.objects.filter(user__username=usrnm).count()==0: user = base_form.save() user.set_password(user.password) user.save() #print(img) addnl = addnl_form.save(commit=False ) addnl.user = user img = qr.make_image() #create a qr code image, full code not included. img.save('media/qrcodes/%s.png'%usrnm) addnl.qr_gen = 'qrcodes/%s.png'%usrnm addnl.save() else: messages.error(request,base_form.errors,addnl_form.errors) else: base_form = UserForm() addnl_form = AddnlForm() return render(request,'app/signup.html',{'base_form':base_form,'addnl_form':addnl_form} ) models.py class UserModel(models.Model): . . . qr_gen = models.ImageField(upload_to='qrcodes',default=None,null=True,blank=True) settings.py DEFAULT_FILE_STORAGE = 'project.storage_backend.MediaStorage' storage_backend.py from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' default_acl = 'public-read' file_overwrite = False Please help me fix the issue. Thanks. -
uWSGI can't find python3 plugin - open("./python3_plugin.so"): No such file or directory
I have tried all solutions in the stackoverflow but still I could not find a solution for me. as you can see in the pluginsdir python3 plugin is available but uwsgi say its not. [uwsgi] ini file [uwsgi] vhost = true plugins-dir = /usr/lib/uwsgi/plugins plugins = python3 socket = /var/run/domain.org.sock master = true enable-threads = true processes = 2 wsgi-file = /var/www/domain.org/config/wsgi.py virtualenv = /var/www/domain.org/env chdir = /var/www/domain.org ls -la /usr/lib/uwsgi/plugins drwxr-xr-x 2 root root 4096 Dec 18 21:44 . drwxr-xr-x 3 root root 4096 Dec 18 21:44 .. ... -rw-r--r-- 1 root root 199896 Apr 11 2020 python38_plugin.so lrwxrwxrwx 1 root root 38 Dec 18 21:44 python3_plugin.so -> /etc/alternatives/uwsgi-plugin-python3 uwsgi --ini /etc/uwsgi/apps-available/domain.org.ini [uWSGI] getting INI configuration from /etc/uwsgi/apps-available/domain.org.ini open("./python3_plugin.so"): No such file or directory [core/utils.c line 3732] !!! UNABLE to load uWSGI plugin: ./python3_plugin.so: cannot open shared object file: No such file or directory !!! *** Starting uWSGI 2.0.19.1 (64bit) on [Fri Dec 18 21:52:29 2020] *** compiled with version: 9.3.0 on 18 December 2020 13:15:35 -
How to add unix timestamp in milliseconds in django model?
Suppose I want add creation time and update time in django model. How to add this in model and get this through in rest api in django?