Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How build AJAX in follow user functionality
I have big challange with AJAX. I made 'Follow User' functionality and don't know how implement AJAX for this... This is my code: In models.py i have: class UserFollowing(models.Model): following_from = models.ForeignKey("Profile", related_name="following_from", on_delete=models.CASCADE) follow_to = models.ForeignKey("Profile", related_name="follow_to", on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: db_table = 'users_userfollowing' constraints = [models.UniqueConstraint(fields=["following_from", "follow_to"], name="unique_followers")] ordering = ("-created",) def __str__(self): return f"FROM:{self.following_from} TO:{self.follow_to}" class Profile(AbstractUser, HitCountMixin): slug = models.SlugField(null=False, unique=True) following = models.ManyToManyField("self", through=UserFollowing, related_name="followers", symmetrical=False) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.username) return super().save(*args, **kwargs) In view.py I made function to follow user: def follow_user(request): user = request.user if request.method == 'POST': user_id = request.POST.get('user_id') user_obj = Profile.objects.get(id=user_id) if user not in user_obj.followers.all(): UserFollowing.objects.get_or_create(following_from=user, follow_to=user_obj) else: UserFollowing.objects.filter(following_from=user, follow_to=user_obj).delete() return redirect('profile', slug=user_obj.slug) And in urls.py urlpatterns = [ path("followers/", follow_user, name="follow_user"), ] At least my html template: {% with total_followers=profile.followers.count %} ({{ total_followers }} Follower) <br> {% endwith %} <form action="{% url 'users:follow_user' %}" method="POST" class="follow-form" id="{{ profile.id }}"> {% csrf_token %} <input type="hidden" name="user_id" value="{{ profile.id }}"> <button type="submit" class="follow-btn{{ profile.id }}"> {% if request.user not in profile.followers.all %} Follow {% else %} Unfollow {% endif %} </button> This works very good. I can follow anad unfollw user … -
How can I access my sqlite3 database through the html template using Django?
I have a Django application where most of my backend code is in views.py. In the frontend, I'm using an html template, but currently I have hardcoded options that the user can choose from a drop down menu. Those hardcoded options are all available in the sqlite3 database which is used extensively in views.py. Is there a way that I read those fields of database from the html file directly instead of hardcoding them? -
How to add a dynamic value in settings.py Django
I want to maintain a variable TOKEN in my settings.py of my django project, and it changed with time. The token saved at db like: class FbBmToken(models.Model): manager_name = models.CharField(max_length=64) token = models.CharField(max_length=255, blank=True, null=True) effective = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'fb_bm_token' And I want use it in my django project anywhere by from django.conf import settings token = settings.TOKEN How can I make this happen? Greate thanks -
PostGIS on WSL2 - extension "postgis" has no installation script nor update path for version
I am trying to add PostGIS extension to a postgresql database on my WSL2 (with Ubuntu 20.04) for a django project. I have already installed postgresql, postgis and all dependencies with the following: sudo apt -y install postgresql-12 postgresql-client-12 sudo apt install postgis postgresql-12-postgis-3 sudo apt-get install postgresql-12-postgis-3-scripts And everything worked fine. In postgresql, I have already created my db and connected to it: sudo -u postgres psql -p 5432 -h 127.0.0.1 postgres=# CREATE DATABASE dbname; postgres=# \c dbname; But then, when I try to add the postGIS extension with: postgres=# CREATE EXTENSION postgis; I get the following error: ERROR: extension "postgis" has no installation script nor update path for version "3.0.0" And despite searching for similar questions on stackoverflow, I couldn't find any satisfactory solution for my case. Any idea what it could be wrong and how I can solve it? thank you! -
django configure apache to serve media and static files
So I have apache and mod-wsgi installed on windows. Now I need to configure apache to serve django's media files. urls.py from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('api/', include('api_backend.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) apache httpd.conf LoadModule wsgi_module "c:/users/iyapp/pycharmprojects/cloud_server/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win32.pyd" ... # custom httpd configuration WSGIPythonPath "c:/users/iyapp/pycharmprojects/cloud_server" WSGIPythonHome "c:/users/iyapp/pycharmprojects/cloud_server/venv" <VirtualHost *:80> ServerName localhost WSGIScriptAlias / "c:/users/iyapp/pycharmprojects/cloud_server/rebox_django/wsgi.py" Alias /media/ "c:/users/iyapp/pycharmprojects/cloud_server/media/" Alias /static/ "c:/users/iyapp/pycharmprojects/cloud_server/static/" <Directory "c:/users/iyapp/pycharmprojects/cloud_server/static"> Require all granted </Directory> <Directory "c:/users/iyapp/pycharmprojects/cloud_server/media"> Require all granted </Directory> <Directory "c:/users/iyapp/pycharmprojects/cloud_server/rebox_django"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> This is what I have so far. However, when I try to access a media file that the server has, I get a 404 not found error. Why is that? Can someone please help me? I am using Apache24 (32 bits with python) and the mod-wsgi python module. settings.py ROOT_URLCONF = 'rebox_django.urls' WSGI_APPLICATION = 'rebox_django.wsgi.application' STATIC_URL = '/static/' STATICFILES_DIRS = [] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') STATIC_ROOT = os.path.join(BASE_DIR, "static/") -
Python Django arrangement of posts within a category?
I wanted some help from you, if it is possible, I am working in Django, I was trying to arrange the posts in the template, but without success, so far I have displayed the posts in the template. order_by ('-data_e_postimit') the same I want to function in posts Within a category. class LajmetListView(ListView): model = Kategori model = Lajmet template_name = 'main/lajme-home.html' # <app>/<model>_<viewtype>.html context_object_name = 'lajmet' def get_context_data(self, **kwargs): context = super(LajmetListView, self).get_context_data(**kwargs) context['lajmet'] = Lajmet.objects.order_by('-data_e_postimit') context['trilajmet'] = Kategori.objects.get(pk=1) context['katego'] = Kategori.objects.all() return context <div class="slick_slider"> {% for lajmet in trilajmet.lajmet_set.all %} {% if forloop.counter < 5 %} <div class="single_iteam"> <a href="{% url 'lajme-detail' lajmet.slug %}"> <img src="media/{{lajmet.fotografit}}" alt=""></a> <div class="slider_article"> <h2><a class="slider_tittle" href="{% url 'lajme-detail' lajmet.slug %}">{{lajmet.titulli}}</a></h2> <p>{{lajmet.detajet|safe}}</p> <p>{{lajmet.data_e_postimit|date:"F d, Y H:i"}}</p> </div> </div> {% endif %} {% endfor %} -
Reverse for 'post_like_dislike' with arguments '('',)' not found. 1 pattern(s) tried: ['post_like_dislike/(?P<post_id>[0-9]+)/$']
I am building a Blogapp and Adding like , unlike buttons into it. BUT when i trying to open page, i keep getting this error. Reverse for 'post_like_dislike' with arguments '('',)' not found. 1 pattern(s) tried: ['post_like_dislike/(?P<post_id>[0-9]+)/$'] views.py def post_like_dislike(request, post_id): post = get_object_or_404(Post, pk=post_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse({'action': 'undislike_and_like'}) elif request.user in post.likes.all(): post.likes.remove(request.user) return JsonResponse({'action': 'unlike'}) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) # Dislike elif request.GET.get('submit') == 'dislike': if request.user in post.likes.all(): post.likes.remove(request.user) post.dislikes.add(request.user) return JsonResponse({'action': 'unlike_and_dislike'}) elif request.user in post.dislikes.all(): post.dislikes.remove(request.user) return JsonResponse({'action': 'undislike'}) else: post.dislikes.add(request.user) return JsonResponse({'action': 'dislike_only'}) else: messages.error(request, 'Something went wrong') return redirect('mains:posts') urls.py path('post_like_dislike/<int:post_id>/',views.post_like_dislike, name='post_like_dislike'), show_more.html <div class="card-footer"> <form method="GET" class="likeForm d-inline" action="{% url 'mains:post_like_dislike' post.id %}" data-pk="{{post.id}}"> <button type="submit" class="btn"><i class="far fa-thumbs-up"></i> <span id="id_likes{{post.id}}"> {% if user in post.likes.all %} <p style="color:#065FD4;display: inline">{{post.likes.count}}</p> {% else %} <p style="color:black;display: inline">{{post.likes.count}}</p> {% endif %} </span> Like</button> </form> <form action="{% url 'mains:post_like_dislike' post.id %}" method="GET" class="d-inline dislikeForm" data-pk="{{ post.id }}"> <button type="submit" class="btn"><i class="far fa-thumbs-down"></i> <span id="id_dislikes{{post.id}}"> {% if user in post.dislikes.all %} <p style="color:#065FD4; display: inline;">{{post.dislikes.count}}</p> {% else %} <p style="color:black; display: inline;">{{post.dislikes.count}}</p> {% endif %} </span> Dislike </button> </form> </div> I don't what am … -
django redirect under post statement doesn't work
This is the exmaple code that works, or any other if statements def login_page(request): if request.user.is_authenticated: return redirect('home') return render(request, 'Page-2.html') def home(request): return render(request, 'Page-1.html') But when I change the redirect under a request.method =='POST' statement, it doesn't redirect the page, but the print works def login_page(request): if request.user.is_authenticated: return redirect('home') if request.method == 'POST': print('test') return redirect('home') return render(request, 'Page-2.html') def home(request): return render(request, 'Page-1.html') urls of the project from django.contrib import admin from django.urls import path from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('login.urls')), ] urls of the app from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('login/', views.login_page, name='login'), path('home/', views.home, name='home') ] The original code was just for login and redirect the page, did I miss something to set up? thanks! -
Unable to view database on frontend in Django via Shell
Hello wonderful people. I am currently learning Django and trying to display the database which is created via form on inventiory_view.html I am unable to do so via shell scripting. I am able to display the objects via shell terminal but whenever I use the same command which is Form1.objects.all I am unable to display it on my desired html page. I would really appreciate your help in this matter. Thanks in advance This is the form1.html where I am getting the data from the user. {% extends 'base.html' %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> {% block title %} Title of Form1 {% endblock %} </head> {% block body %} <div class="container"> <h1>Form1</h1> <form method="POST" action=" /form1/"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlInput1">Item name</label> <input type="text" class="form-control" id="exampleFormControlInput1" name= "item" placeholder="laptop"> </div> <!-- <div class="form-group"> <label for="exampleFormControlInput1">Quantity </label> <input type="number" class="form-control" id="exampleFormControlInput1" name= "quantity" placeholder="1,2,3"> </div> --> <div class="form-group"> <label for="exampleFormControlSelect1">Quantity</label> <select class="form-control" input type="number" id="exampleFormControlSelect1" name= "quantity"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> <div class="form-group"> <label for="exampleFormControlInput1">Vendor name</label> <input type="text" class="form-control" id="exampleFormControlInput1" name= "vendor" placeholder="Nokia"> </div> … -
Python qrcode does not work inside docker
My django application generates a qrcode in the models everytime a new item is added through the form. It works perfectly fine when I run it using the python manage.py runserver command but when I dockerize the application, it shows the following error: qr_codes_img = qrcode.make(self.bag_asset_id) AttributeError: module 'qrcode' has no attribute 'make' This only happens when I build and run the docker file, otherwise it works fine. I do not have any other file or function by the name 'qrcode' and the requirements.txt file is updated perfectly. My Dockerfile looks like this: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN apt-get update RUN apt-get install -y gconf-service libasound2 libatk1.0-0 libcairo2 libcups2 libfontconfig1 libgdk-pixbuf2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libxss1 fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app -
How to create model with 2 columns unique together and autoincrement?
I have two columns in my Invoice model in Django: class Invoice(models.Model): use_in_migrations = True year = models.CharField(max_length=16, default='') index = models.IntegerField(default=0) with which I want to achieve in the database this sequence: ... 2020, 134 2020, 135 2021, 1 2021, 2 ... First I tried to add class Meta: unique_together = [['prefix', 'index']] so I will be sure that I get always unique row values in columns. The issue is that with PostgreSQL, this creates this sequence: ... 2020, 134 2020, 135 2021, 136 2021, 137 ... Any solution how to solve this in Django? I am using Django 2.2... -
How to call a function in django admin to refresh data available?
I want to refresh all data under all source fields in django admin. Below is my ModelAdmin class SourceAdmin(admin.ModelAdmin): list_display= ('id','source_name','missing_data','modified_date_missing','refresh_data','email_refresh_days','modified_date_refresh','search_appearance','modified_date_search','date_added','date_modified','email_count','refresh','stop') search_fields = ['id','source_name','email_refresh_days'] ordering = ['-date_modified'] list_editable = ['missing_data','refresh_data','search_appearance','email_refresh_days'] list_filter = [SourceidFilter, SourcenameFilter] def refresh(self, obj): return mark_safe('<input type="button" value="start">') def stop(self, obj): return mark_safe('<input type="button" value="stop">') def set_refresh(self, request): self.model.objects.all().update(refresh_data=True) self.message_user(request, "All data are now refreshed") return HttpResponseRedirect("../") def set_stop(self, request): self.model.objects.all().update(refresh_data=False) self.message_user(request, "All data are now stopped") return HttpResponseRedirect("../") def save_model(self, request, obj, form, change): if 'missing_data' in form.changed_data: obj.modified_date_missing = timezone.now() if 'refresh_data' in form.changed_data: obj.modified_date_refresh = timezone.now() if 'search_appearance' in form.changed_data: obj.modified_date_search = timezone.now() obj.modified_by = request.user obj.save() I want to call set_refresh and set_stop function using below functions when i will click start and stop which i mentioned in list_display. It should refresh data available in refresh_data one by one. def refresh(self, obj): return mark_safe('<input type="button" value="start">') def stop(self, obj): return mark_safe('<input type="button" value="stop">') Start and Stop Button -
Django POST form with 2 submit buttons, "enter" behavior
I have a form with 2 submit buttons that look like this: <select class="form-select" name="modelsz" id="modelsz"> <option selected>{{found_model}}</option> {% for i_model in searched_model %} <option>{{i_model}}</option> {% endfor %} </select> <button type="submit" name="chooseModel" class="btn btn-outline-success" value="Confirm">Confirm</button> ... <input type="text" class="form-control" placeholder="Symbol" name="symbolsz" id="symbolsz" value={{found_symbol}}> <button type="submit" name="searchProduct" class="btn btn-outline-success" value="Search">Search</button> There is no problem in handling both of them in one form but I can't figure out how to change default button when using "enter" key on my keyboard. Every time I press "enter" it chooses first button -
Implementing django-rest-passwordreset to React Native
I'm trying to add change password functionality to a Django / React app. I'm using django-rest-passwordreset library for creating Reset or Forgot Password API using Django Rest Framework. After I type the email that registered, I've managed get the token from the console But I'm struggling to find a way to send an email to their email address with the link to reset their password along the given token. I've tried the SMTP Method or SendGrid. Was trying this way and this way Can someone show me the correct way to make this work? Thanks a lot. -
i am using bootstrap 5 modal, nothing is happening when i try to trigger it
this is cart.html , i am using modal html on top of the page, but is still not working <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> {% extends 'base.html' %} {% block content %} {% load cart %} {% load custom %} <div class="container"> <div class="border rounded m-4 p-4" > <p class="display-4 ">Your Cart</p> <hr> <table class="table"> <thead> <tr> <th>Sno.</th> <th>image</th> <th>Product</th> <th>Price</th> <th>Quantity</th> <th>Total</th> </tr> </thead> <tbody> {% for product in products %} <tr> <td>{{ forloop.counter }}</td> <td><img style=" height:80px" src="{{ product.image.url }}" class="rounded-circle" alt="product image"></td> <td>{{product.name}}</td> <td>{{product.price |currency }}</td> <td>{{product|cart_count:request.session.cart}}</td> <td> {{product|price_total:request.session.cart|currency}}</td> </tr> {% endfor %} </tbody> <tfoot> <tr> <th colspan="4"></th> <th class="" colspan="">Subtotal</th> <th> {{ products|subtotal:request.session.cart|currency }}</th> </tr> <tr> <th colspan="5"></th> </tr> </tfoot> </table> <hr> <div class="m-3 p-3"> <a href="#" data-toggle="modal" data-target="#exampleModal" class="btn btn-outline-info border rounded col-lg-3 float-right">Check out</a> </div> </div> </div> <!-- Button trigger modal --> <!-- Modal --> {% endblock %} base.html which is inherited by cart.html , am i correctly using script ? … -
User model is not finding current user?
I used the default User model. Inside my models.py: from django.contrib.auth.models import User from django.contrib.auth import get_user_model class TweetModel(models.Model): text = models.TextField(max_length=150, blank=False) created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) I have tried both get_user_model and User, but they are not working. When I try to write it is saying owner field is required. But Token was provided in the request. -
What VSCode language config setting allows HTML to add extra line in a tag on enter?
What causes the extra linebreak on pressing enter between an HTML tag within VS Code (like below)? And how can you set it up in another language without using HTML as the language's formatter (like Django-HTML for instance)? -
ValueError: invalid literal for int() with base 10: 'favicon.ico' in Terminal
I am building blog app. AND i am using Django Version :- 3.8.1. AND i am stuck on an Error. views.py def detail_view(request,id): id = int(id) data = get_object_or_404(Post,id=id) comments = data.comments.order_by('-created_at') new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): comment_form.instance.post_by = data comment_form.instance.commented_by = request.user comment_form.instance.active = True new_comment = comment_form.save() return redirect('mains:detail_view',id=id) else: comment_form = CommentForm() context = {'data':data,'comments':comments,'new_comment':new_comment,'comment_form':comment_form} return render(request, 'show_more.html', context ) urls.py path('<id>',views.detail_view,name='detail_view'), Error When i start server. Everything is working Fine. Every page is opening fine, BUT when i see the terminal then It is showing ValueError: invalid literal for int() with base 10: 'favicon.ico' in terminal at every page i Click in Browser. Any help would be Appreciated . Thank You in Advance. -
When i run my Django project i am getting this error
When i run my project i am getting this errro Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\ProgramData\Anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 382, in run_checks return checks.run_checks(**kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\ProgramData\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\ProgramData\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\ProgramData\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "C:\ProgramData\Anaconda3\lib\importlib_init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in call_with_frames_removed File "C:\Users\mehra\Downloads\Covid19Chatbot-master\BLL\urls.py", line 21, in path('', include('UI.urls')), File "C:\ProgramData\Anaconda3\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\ProgramData\Anaconda3\lib\importlib_init.py", … -
Cannot login admin site in django after custom user model
My custom user model from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin # Create your models here. class mUserManager(BaseUserManager): def create_user(self, email, username, password = None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have an username") user = self.model( email = self.normalize_email(email), username = username, ) user.set_password(password) user.save() return user def create_superuser(self, email, username, password=None): u = self.create_user( email = self.normalize_email(email), username = username, password=password, ) u.is_admin = True u.is_staff = True u.is_superuser = True u.is_active = True u.save() return u class mUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) password = models.CharField(max_length=20) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] objects = mUserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True And in settings.py, I add this: AUTH_USER_MODEL = 'accounts.mUser' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.RemoteUserBackend', 'django.contrib.auth.backends.ModelBackend', ) i run makemigrations ad migrate, then createsuperuser, but i cannot login to admin site. I check the database and find the password seems to have no … -
How to create a django tenant via web/ user interface? [closed]
Is there a way not to use python shell in order to create django tenants? The goal is to allow an admin user to manage tenants like in the django.contrib.admin app he is able to manage sites, with CRUD functionalities. Is it possible? How? -
How to make a Django App standalone installable software in Windows and Linux? [closed]
I have a Django web app which uploads a VCF (Variant Call Format, that stores gene sequence variations) file to the server, process and outputs a report in PDF. As the VCF files normally in GBs in size and processing takes more than 5 minutes, I want to make web tool as a standalone software which can be installable in Windows and Linux in one click. Can someone please help me how to do this.. thanks much -
Fieldset values not displaying properly -django
models.py for member table. class Member(models.Model): fullname=models.CharField(max_length=30) companyname=models.CharField(max_length=30) Email=models.CharField(max_length=50) password=models.CharField(max_length=12) contactno = models.CharField(max_length=30,default='anything') i want to display fullname, email, companyname and company number in profile page. models.py for profile table class Profile(models.Model): fullname=models.CharField(max_length=60) contactno=models.CharField(max_length=10) worknumber=models.CharField(max_length=10) email=models.CharField(max_length=30) companyname=models.CharField(max_length=30) timezone=models.CharField(max_length=20) Instead of manually entering the values(data) for fullname, contactno, companyname and email in the fieldset, It should fetch from member table and displayed here. Can we use OneToOne Field or foreign key here, to implement this concept. Thanking You in Advance. You will be highly appreciate, if you could suggest the implementation. -
Error while submitting data from checklist using another db table
I am trying to submit data from a checklist using forms. The checklist is generated from a database and after submission the checked items are inserted into another database. I am getting the error as form is invalid. This is my models.py CustomStudent is the database from where I am taking value and Reports is the database where I am submitting values class CustomStudent(models.Model): _id = models.AutoField sname = models.CharField(max_length = 50) slname = models.CharField(max_length = 50) password = models.CharField(max_length = 255, default = '') def __str__(self): return str(self.slname) return str(self.sname) class Report(models.Model): # _id = models.AutoField() tname = models.CharField(max_length = 100) sname = models.CharField(max_length = 100) fdate = models.DateField() tdate = models.DateField() dailydate = models.DateField() objective = models.CharField(max_length = 512) tplan = models.CharField(max_length = 512) how = models.CharField(max_length = 512) material = models.CharField(max_length = 512) extra = models.CharField(max_length = 512) topic = models.CharField(max_length = 512) pftd = models.CharField(max_length = 512) activity = models.CharField(max_length = 512) comment = models.CharField(max_length = 512) thought = models.CharField(max_length = 512) admin_comment = models.CharField(max_length = 255) def __str__(self): return str(self.tname) return str(self.sname) This is code from my forms.py to use the database. sname = forms.ModelMultipleChoiceField(queryset=CustomStudent.objects.all().values_list('sname', flat=True), required = False, widget =forms.CheckboxSelectMultiple( attrs ={'class':' form-check-input' ' … -
Django: Type Error after switching to PostgreSQL from SQLite
I changed settings.py and installed psycopg2==2.8.6. I have validation checks in my models that go something like this. rating = models.PositiveIntegerField( blank=True, null=True, default=0, validators=[MaxValueValidator(10), MinValueValidator(0)] ) quantity = models.PositiveIntegerField( blank=False, null=False, default=0, validators=[MinValueValidator(1)]) When I switch to PostgreSQL, there's this error that didn't appear while I was using SQLite. TypeError: '<=' not supported between instances of 'PositiveIntegerField' and 'int' What should I do?