Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Microsoft MSAL React SPA, and RESTful Django API
I don't know why I can't find confirmation in the docs, maybe I am not navigating them correctly, although MSAL seems to have options to fit it into any application. This is my first time integrating a SAML sso procedure into any of my web-apps. I am just looking for some clarity on the correct, and secure way to verify the person attempting to login, is actually logged in with the IDP. I am confused at the part after confirmation of login is given to my redirect API, I currently have it all happening on the front-end, then submitting the response to my back-end. Which is a RESTful API built with Django, and postgres database. At this point, I am thinking I need to verify my accessToken for authenticity, but I am unsure if I should be creating another PublicClient instance in python, and then sending the same commands to the IDP. To guess at this point, I'm thinking this is wrong, as I need to verify the token, rather than get another Access and Refresh token. I'm thinking I just need to verify there is a session open with the IDP, and that the Access Token matches. Can anyone … -
Why Django memcached always return none?
I have 2 different cache type as follow: (I am using MySQL connector because the client wants it like this.) import os,sys from pathlib import Path sys.path.append(os.path.dirname(os.path.abspath('.'))) os.environ['DJANGO_SETTINGS_MODULE'] = 'api.settings' import django django.setup() import mysql.connector from django.core.cache import cache,caches db_crawl = mysql.connector.connect( host="xx.xx.xx.xx", user="xxx", password="xxxx", database="xxx" ) cursor_crawl = db_crawl.cursor(dictionary=True) def marketprices(): query = "some query here" cursor_crawl.execute(query) result = cursor_crawl.fetchall() m_cache = caches['marketprice'] m_cache.set('marketprices', result,1024 * 1024 * 1024) The query output has about 18 MB cache and I want to hold the cache 1024 * 1024 * 1024 times. My cache settings: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': BASE_DIR.joinpath('caches'), 'TIMEOUT':None, 'OPTIONS': { 'server_max_value_length': 1024 * 1024 * 1024, } }, 'marketprice': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', 'TIMEOUT':None, }, } I set and start the Memcached in my server and everything works fine. The service Memcached status is: ● memcached.service - memcached daemon Loaded: loaded (/lib/systemd/system/memcached.service; enabled; vendor preset: enabled) Active: active (running) since Mon 2021-07-19 22:33:49 +03; 1h 10min ago Docs: man:memcached(1) Main PID: 2126782 (memcached) Tasks: 10 (limit: 72283) Memory: 1.6M CGroup: /system.slice/memcached.service └─2126782 /usr/bin/memcached -I 256M -m 8192 -p 11211 -u memcache -l 127.0.0.1 -P /var/run/memcached/memcached.pid Jul 19 22:33:49 vmi552735.contaboserver.net systemd[1]: Started memcached daemon. … -
How can I define a base style.css file for a Django application
I am making a project in Django where I have multiple apps. For this project I defined a base.html where I have my navbar and my footer. Now I am looking to add a css file that would be available for all the apps for having a common background image. What I ended up doing is making a static folder into the project folder however django is complaining that it can not get the static file from there. How can I manage this base style.css file? My folder structure is like this: --Project |-- Project | |--static | |--Project | |--style.css |-- App1 |-- App2 |-- App3 My intention is to be able to use the style.css classes in App1, App2 and App3. The message that I get is that django can not collect the Project/style.css file because the ~/Project/Project/static folder does not exist. -
Why is Django taking so long for system checks with PostGreSQL-backend? [import 'django.db.models.sql.compiler' # <_frozen_importlib]
Even though I have used stackOverflow since ages to enlarge my programming-horizone, this is actually my ever first question on this platform and I'm pretty excited . So I set up a webpage/webapplication that is powered by Django. Previously I utilized a MySQL database as backend and everything worked out smooth, but then I tried to switch to PostGreSQL. To set up a PostGreSQL database I leveraged the Postgres.app, and followed the instructions to integrate it into Django. But when I now try to start the server in the shell with python3 manage.py runserver it keeps getting stuck at the following message: Performing system checks... From there it takes a very long time (circa 7-8 minutes) with my computer using a lot of CPU until finally the server starts with no issues: System check identified no issues (0 silenced). July 19, 2021 - 21:17:38 Django version 3.2.5, using settings 'ApolloPostGreDB.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. When I stop the process it returns [skipped lines with "..."]: import 'gc' # <class '_frozen_importlib.BuiltinImporter'> # clear builtins._ # clear sys.path # clear sys.argv # clear sys.ps1 # clear sys.ps2 # clear sys.last_type # clear sys.last_value # clear sys.last_traceback … -
NoReverseMatch at /forum/ Reverse for '' not found. '' is not a valid view function or pattern name
I'm kinda stuck here. The "Forum" button works when I'm logged in and redirects me to the forum page. However, it returns this when I'm not authenticated: NoReverseMatch at /forum/ Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/forum/ Django Version: 3.1.11 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. Here is my layout.html which home.html extends from: <body> <nav class="nav d-flex flex-row justify-content-between nav-fill navbar-expand-lg navbar-dark bg-dark sticky-top container-fluid" style=""> <div class="first"> <a class="navbar-brand mr-4 ml-4" href="#"><b>My Site</b></a> <a class="nav-item nav-link text-light" href="{% url 'home' %}">Home</a> <a class="nav-item nav-link text-light" href="{% url 'forum:index' %}">Forum</a> {% if user.is_authenticated %} <a class="nav-item nav-link text-light" href="{% url 'users_list' %}">Find New Buddies</a> </div> {% block searchform %}{% endblock searchform %} <div class="second"> <a class="nav-item nav-link text-light" href="{% url 'post-create' %}">Create Post</a> <a class="nav-item nav-link text-light" href="{% url 'my_profile' %}">Profile</a> <a class="nav-link dropdown-toggle text-light" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Messaging</a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="{% url 'postman:inbox' %}">Inbox{% if unread_count %} <strong>({{ unread_count }})</strong> {% endif %}</a> <a class="dropdown-item" href="{% url 'postman:write' %}">Write</a> <a class="dropdown-item" href="{% url 'postman:sent' %}">Sent</a> … -
Keep getting 403 "CSRF token missing or incorrect" in Django + Vue setup
I have searched through other similar questions but none of the solutions worked nor gave me any insight into what may be happening. My setup is a Vue frontend (with its own routing) plus a Django backend and API. Any GET route I try works as expected, but POST ones require CSRF protection. I have a custom render function I call on the route that brings to the index (which is then going to be handled by Vue), where I provide the CSRF token like so: def custom_render(request): # ... # from django.middleware.csrf get_token(request) # from django.shortcuts return render(request, template) This sets a cookie csrftoken with the CSRF token, which seems to work correctly, as I can see it in the devtools and if I delete it, it's there again when I refresh. Here are my relevant Django settings.py: # This one is True in production, but for now I'm testing locally CSRF_COOKIE_SECURE = False CSRF_HEADER_NAME = "X-CSRFToken" # I tried playing with both these options' values to no avail CSRF_USE_SESSIONS = False CSRF_COOKIE_HTTPONLY = False MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "django.middleware.common.BrokenLinkEmailsMiddleware", ] On the Vue side (Typescript) I'm sending a request using this: function … -
elastic beanstalk error ERROR: No such file or directory: './Library/Application Support/Google/Chrome/RunningChromeVersion
I am a bit new to AWS and Django deployment with the elastic beanstalk my details os = macOS 10.15.7 Catalina while trying to upload a Django project to elastic beanstalk I get an error see error I get after running eb create django-env to create an environment for elastic beanstalk ERROR: FileNotFoundError - [Errno 2] No such file or directory: './Library/Application Support/Google/Chrome/RunningChromeVersion' see the screenshot below that shows that something like the said missing file exists Please advise me on how to resolve this error as I urgently need to upload the Django project using Elastic beanstalk -
authenticate is returning None instead of user
I am currently working on my Django app. The scenario is I have created a custom User model. The code of my User Model is below: ... class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports using email instead of username""" email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' I customized the User model to authenticate users on the basis of email instead of the username. I have already done this before but don't know when I am trying to authenticate the user for token it returns None. Here I am using rest_framework.authtoken to for TokenAuthentication here is my serializer code: ... class AuthTokenSerializer(serializers.Serializer): """Serializer for the user authentication object""" email = serializers.CharField() password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, attrs): """Validate and authenticate the user""" email = attrs.get('email') password = attrs.get('password') user = authenticate( request=self.context.get('request'), username=email, password=password ) if not user: msg = _('Unable to authenticate with provided credentials') raise serializers.ValidationError(msg, code='authentication') attrs['user'] = user return attrs Huh! thanks to the breakpoints. I have figured out where the actual error is occurring. I found an error in authenticate() it always returns None instead of … -
get GPS data from users on webapp whit django
I wanna make a web app to get a user's location from their GPS and show it on the website. how I can do it whit django? and what I can do about it. -
Django Count not working in signals if sender and receiver are not same
if sender and receiver are not same in my Blog model the number of count not showing in my base.html. I am using signals in my models. Count is working for my blogcomment model but it's not working in my blog model if sender and receiver are different. if I use sender = blog.author and receiver = blog.author then it working and counting. see the picture for get an idea: here is my models.py #this model for author class Blog(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,max_length=100) title = models.CharField(max_length=300,unique=True) #my others fields.... #here signals stating def blog_notify(sender, instance, *args, **kwargs): blog = instance blog_title = blog.title #sender =blog.author #only count working if sender and receiver is same sender = User.objects.filter(username="admin1") receiver = blog.author if sender == blog.author and blog.is_published == "published": notify = Notifications(blog=blog, sender=sender, receiver=receiver,text_preview = blog_title[:250], notification_type="post approved") notify.save() if sender == blog.author and blog.is_published == "pending": notify = Notifications(blog=blog, sender=sender, receiver=receiver,text_preview = blog_title[:250], notification_type="pending post") notify.save() if sender == blog.author and blog.is_published == "rejected": notify = Notifications(blog=blog, sender=sender,receiver=receiver,text_preview = blog_title[:250], notification_type="post rejected") notify.save() #this model for comment user. if anyone comment on blog post class BlogComment(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True) #my others fields.... #here signals stating def user_comment(sender, instance, *args, … -
Flask in showing 404 Error in Existing Routes
I am facing a very weird Issue, In my Flask App when index route (https://sitename.com/) is called everything is fine, but as i navigate to a route like https://sitename.com/about it shows 404 Error, even when About route is created in main.py . This App works all perfect in localhost:5000 but when I deployed it too a VPS It is showing that Error of showing 404 on every route My main.py from os import environ from flask import Flask, redirect, render_template, request, url_for import requests import json import datetime def getUserData(route): if request.headers.getlist("X-Forwarded-For"): ip = request.headers.getlist("X-Forwarded-For")[0] else: ip = request.remote_addr with open("users.txt", "a") as f: f.write(f"Page Visited: {route}\n") f.write(f"User Agent: {request.headers.get('User-Agent')}\n") f.write(f"Remote Addr: {ip}\n") f.write(f"DateTime: {datetime.datetime.now()}\n") f.write(f"\n\n\n") app = Flask(__name__) app.debug = True # Website @app.route('/') def index(): getUserData("Index Page") return render_template('index.html') @app.route('/gallery') def gallery(): getUserData("Gallery") return render_template('pages/gallery.html') @app.route('/faqs') def faqs(): getUserData("FAQs") return render_template('pages/faqs.html') @app.route('/about') def about(): getUserData("About") return render_template('pages/about.html') @app.route('/contact') def contact(): getUserData("Contact") return render_template('pages/contact.html') # 404 Handling @app.errorhandler(404) def not_found(e): getUserData("404 Page") return render_template("pages/404.html") if __name__ == '__main__': app.run() -
Render the same form in template with initial data
I'a stuck with the following problem. I an Employer model, an Employee model, an HourCode model and a ReportModel. I will begin with the outcome i want to see, maybe then its clear what iam asking. Every employee has a employer and every employer has hourCodes for time registration. For Example: John is working at xerox, he worked 10 normal hours and 5 extra hours. In this case the hourcode are "normal hours" and " extra hours ". In my template i want to render a sort of table view so that de hours can be filled by the employer. So in this case he had to fill in 10 hours on "normal hours" and 5 hours on "extra hours" at John. But, the employer has ofcourse multiple employees, so he has to fill in several lines with the worked hours and extra hours per employee. Employeename. Normal hours. Extra hours John. 10. 5 Eva. 3. 5 SaveButton After savebutton pressed the forms (in this case 2, each for every employee) has to be saved to the ReportModel. The Reportmodel has some fields (ForeignKey fields to employer, employee and hourcodes. Long story, my question how can i render the view … -
AttributeError: 'QuerySet' object has no attribute '_meta'
I'm trying to do login() with Discord OAuth2 and a custom authentication backend but I get an error. When a user logs in for the first time, it works but if they log out and then log in again, this error pops up. def discord_login_redirect(request, *args, **kwargs): code = request.GET.get("code") exchange_user = exchange_code(code) discord_user_auth = DiscordAuthenticationBackend.authenticate(request=request, user=exchange_user) # discord_user_auth = list(discord_user_auth).pop() login(request, discord_user_auth) return redirect("/app") Full Traceback: Internal Server Error: /app/oauth2/login/redirect Traceback (most recent call last): File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Internet\Desktop\Programming\Discord\exo_website\website\exo_dashboard\dashboard\home\views.py", line 188, in discord_login_redirect return redirect("/app") File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 126, in login request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) AttributeError: 'QuerySet' object has no attribute '_meta' [19/Jul/2021 14:20:18] "GET /app/oauth2/login/redirect?code=code HTTP/1.1" 500 79016 -
Object of type MultipleObjectsReturned is not JSON serializable
I've been receiving this error from our crash reporting service in Django, I have not been able to replicate the issue but it happens several times a day apparently without crashing the web app, any hints on where to look will be appreciated, I've been stuck on this for a week now Internal Server Error: /api/v1/users/ TypeError at /api/v1/users/ Object of type MultipleObjectsReturned is not JSON serializable Request Method: POST Request URL: url/api/v1/users/ Django Version: 3.0.2 Python Executable: /layers/google.python.pip/pip/bin/python3 Python Version: 3.7.10 PATH_INFO = '/api/v1/users/' QUERY_STRING = '' RAW_URI = '/api/v1/users/' REMOTE_ADDR = '127.0.0.1' REMOTE_PORT = '25307' REQUEST_METHOD = 'POST' SCRIPT_NAME = '' SERVER_NAME = '0.0.0.0' SERVER_PORT = '8081' SERVER_PROTOCOL = 'HTTP/1.1' SERVER_SOFTWARE = 'gunicorn/20.0.4' gunicorn.socket = <socket.socket fd=10, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 8081), raddr=('127.0.0.1', 25307)> wsgi.errors = <gunicorn.http.wsgi.WSGIErrorsWrapper object at 0x3e87ac0ea1d0> wsgi.file_wrapper = '' wsgi.input = <gunicorn.http.body.Body object at 0x3e87ac136b10> I've omitted some of the stack trace for security reasons but this is the view that's causing this issue: @api_view(['GET']) @permission_classes([IsUserAuthenticated, IsUserAdmin]) def get_users(request): limit = int(request.GET.get('limit', 0)) offset = int(request.GET.get('offset', 0)) first_name = request.GET.get('first_name', '') last_name = request.GET.get('last_name', '') email = request.GET.get('email', '') paid = request.GET.get('paid', '') gender = request.GET.get('gender', '') country = request.GET.get('country', '') sign_in_device = request.GET.get('sign_in_device', … -
How to set an unspecified value to Meta class (How to create a template table class) django_tables2
I have more than 30 tables, so I don`t want to write the same code for all of them. Even its copypaste. All my tables should look like this one: class MyTable(tables.Table): edit_link = tables.columns.Column(viewname='edit_table_field', kwargs={'table_name': 'MyModel', 'pk': A('pk')}, text='edit) ... class Meta: model = MyModel ... I want to make a tamplate from this class which will take the name of the model (MyModel) as an argument and create the same tablestables for each of them in one class. I don't know how to pass a value from a class to a metaclass. Also, maybe someone know any frameworks for python that implements the mapping and CRUD methods for my tables like it`s in Vaadin (Java)? -
Unsupported operand type(s) for /: 'int' and 'NoneType' on Custom Save - Django Form
I am trying to make a custom save on Django form because I have some variables that depends on other's values. When I use the admin form, it works perfectly, all the variables on my custom save are created with no problems and with the correct values. But when I use my form (the one from my template), I get the error: Traceback (most recent call last): File "/home/monique/.local/share/virtualenvs/SISTEMA-rPBRM75u/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/monique/.local/share/virtualenvs/SISTEMA-rPBRM75u/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/monique/MEGA/FORREST/SISTEMA/sepProdMachos/views.py", line 17, in add obj = form.save() File "/home/monique/.local/share/virtualenvs/SISTEMA-rPBRM75u/lib/python3.8/site-packages/django/forms/models.py", line 468, in save self.instance.save() File "/home/monique/MEGA/FORREST/SISTEMA/sepProdMachos/models.py", line 50, in save self.porcContaminacao = (self.nFemeasCQ*100)/self.amostragemTotal Exception Type: TypeError at /sepProdMachos/add/ Exception Value: unsupported operand type(s) for /: 'int' and 'NoneType' My model code is: from hatching.models import Hatching from django.db import models # Create your models here. class SepProdMachos(models.Model): created = models.DateTimeField(auto_now_add=True, null=True, blank=True) hatching = models.OneToOneField(Hatching, on_delete=models.PROTECT, null=True, blank=True) data = models.DateField(null=True, blank=True) inicio = models.TimeField(null=True, blank=True) fim = models.TimeField(null=True, blank=True) nBandejas = models.IntegerField(null=True, blank=True) bandejasDescartadas = models.IntegerField(null=True, blank=True) bandejasSeparadas = models.IntegerField(null=True, blank=True) mlMachos = models.FloatField(null=True, blank=True) mlMachosRepassado = models.FloatField(null=True, blank=True) mlFemeas = models.FloatField(null=True, blank=True) nOperadores = models.IntegerField(null=True, blank=True) nFemeasCQ = models.IntegerField(null=True, … -
how can I load qr_code in xhtml2pdf in django?
I am trying to print qrcode in xhtml2pdf but it didn't work with my. It is working on normal html template but when I render html2pdf it is not displaying. This my html2pdf template. I am using xhtml2pdf library. {% for company in companys %} <table> <tr> <td style="padding-left:40px;width:70px;"> {% load qr_code %} {% qr_from_text 'Hello World!' %} <img style="width:70px;height:70px;" src="./staticfiles/toyota.png"> </td> <td style="padding-right:30px;font-size:25px;">{{ company.name }}</td> <td style="padding-right:20px;width:110px;"> <img style="width:70px;height:70px;" src="../staticfiles/isuzu.png"> </td> </tr> <tr> <td style="width:150px;"></td> <td style="padding-right:30px;font-size:15px;">{{ company.tel }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ company.address }}</td> <td></td> </tr> <tr> <td style="width:150px;"></td> <td style="padding-right:30px;font-size:15px;">{{ company.tax_num }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ company.com_num }}</td> <td></td> </tr> </table> {% endfor %} -
save() got an unexpected keyword argument 'commit'
I am implementing a feature that allows a user to upload images to their blog. When the user uploads a single image I get the error 'PostImages' object is not iterable and when a user uploads multiple images I get the error save() got an unexpected keyword argument 'commit' this is the one I am currently trying to fix view def DetailPostView(request, pk): model = Post post = Post.objects.get(pk=pk) formImages = PostImagesForm if request.method == 'POST': formImages = PostImagesForm(request.POST, request.FILES) files = request.FILES.getlist('images') if formImages.is_valid(): for f in files: formImages = formImages.save(commit=False) formImages.post = Post.objects.get(pk=pk) formImages.save() else: print(formImages.errors) context = { 'post':post, 'formImages':formImages, } return render(request, 'blog/post_detail.html', context) form class PostImagesForm(ModelForm): class Meta: model = PostImages fields = ('images',) widgets = { 'images': forms.ClearableFileInput(attrs={'multiple': True}), } I found this stack post that was also dealing with the same error but I dont really understand it. I have done the same thing on all my other forms without issue. -
Django-Admin not found despite installing Django
I am a beginner with Django, and when it comes to stuff dealing with installing packages on computers, I get confused very easily. I've already installed Django, and yet when I try to create a project, the following message appears... can't open file 'U:\django-admin': [Errno 2] No such file or directory I've seen on other questions asked, that it would require one to have a virtual environment; however, on the tutorials I've been following, it doesn't install an environment. -
Factory Boy SelfAttribute is not returning what I expect
I have the following model that I am trying to replicate the functionality of in tests: class Client(TimeStampedModel): user = models.OneToOneField(User, related_name="client", on_delete=models.CASCADE) business_name = models.CharField(_("business name"), max_length=255, blank=True) business_phone = PhoneNumberField(_("business phone"), blank=True, null=True) business_address = models.CharField( _("business address"), max_length=255, blank=True ) business_city = models.CharField(_("business city"), max_length=255, blank=True) business_state = USStateField(_("business state"), blank=True) business_zip = USZipCodeField(_("business zip"), max_length=255, blank=True) business_url = models.URLField(_("business website"), blank=True) @property def email(self): return self.user.email def __str__(self): return f"{self.business_name}" The thing that is causing issues is the email property. It should return the email address of a user. With DjangoModelFactory, I am creating a user and client with the following two factories: class UserFactory(DjangoModelFactory): class Meta: model = get_user_model() django_get_or_create = ["username"] username = Faker("user_name") email = Faker("email") phone_number = Faker("phone_number") first_name = Faker("first_name") last_name = Faker("last_name") city = Faker("city") state = Faker("state_abbr") zip = Faker("zipcode_plus4") # these are overrideable password = "fakePassword" is_staff = False @classmethod def _create(cls, model_class, *args, **kwargs): """Override ``_create``""" kwargs["password"] = make_password(kwargs["password"]) kwargs["is_staff"] = kwargs["is_staff"] return super(UserFactory, cls)._create(model_class, *args, **kwargs) class ClientFactory(DjangoModelFactory): class Meta: model = Client user = factory.SubFactory( UserFactory, ) business_name = Faker("company") business_address = Faker("street_address") business_city = Faker("city") business_state = Faker("state_abbr") business_zip = Faker("postalcode") email = factory.SelfAttribute("user.email") … -
Using jQuery DateTimePicker in Django Admin form get error - Enter a list of values
It looks like when you use DateTimeField in Django, it expects to return two values, one with date and one with time, then adds and writes to the database in one field. What I have is it returns one value="2021-07-19 20:17:43". Help solve the problem. model.py start_date = models.DateTimeField(blank=True, null=True) end_date = models.DateTimeField(blank=True, null=True) widgets.py from django.forms import DateTimeInput class DateTimePicker(DateTimeInput): template_name = 'widgets/datetimepicker.html' def get_context(self, name, value, attrs): datetimepicker_id = f'datetimepicker_{name}' if attrs is None: attrs = dict() attrs['data-target'] = f'#{datetimepicker_id}' attrs['class'] = 'form-control datetimepicker-input' context = super().get_context(name, value, attrs) context['widget']['datetimepicker_id'] = datetimepicker_id return context class Media: css = { "all": ( "//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css", "//cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.39.0/css/tempusdominus-bootstrap-4.min.css", ) } js = ( '//cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js', '//cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.39.0/js/tempusdominus-bootstrap-4.min.js', ) widgets/datetimepicker.html <div class="input-group date" id="{{ widget.datetimepicker_id }}" data-target-input="nearest"> {% include "django/forms/widgets/input.html" %} <div class="input-group-append" data-target="#{{ widget.datetimepicker_id }}" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> <script> django.jQuery(document).ready(function ($) { $("#{{ widget.datetimepicker_id }}").datetimepicker({ format: 'YYYY-MM-DD HH:mm:ss', }); }); </script> admin.py formfield_overrides = { models.DateTimeField: {'widget': DateTimePicker}, } widget error when saving Thanks for reading and for the help. -
Define CSS variables from Django Models
I'm trying to create an app where the user would be able to customize the design. As for now, I would like to make something very simple and just let the user define the value of some colors like this: class PageSettings(models.Model): base_color = ColorField(default='#FFFF00') mi css code define variables like this: :root { --blue: #0061f2; --indigo: #5800e8; --purple: #6900c7; --pink: #e30059; --red: #e81500; --orange: #f76400; --yellow: #f4a100; I'm wondering if there's a way where I can tell mi CSS file not to use some color, let's say 'blue' as #0061f2, but insted use the value of 'base_color'. -
Custom auth system django
I have an app with ability to unite users by groups. So you can auth in it using built-in django auth system and use app in single mode, but also login in group (that adds additional functionality). Need to auth user in group-mode using group data, then write that group in user's foreign key for group. So I have user model like this: class CustomUser(AbstractUser): ... note_group = models.ForeignKey(NoteGroup, on_delete=models.DO_NOTHING, null=True, blank=True) ... And group model: class NoteGroup(models.Model): id = models.BigAutoField(primary_key=True) group_name = models.CharField(max_length=25) password = models.CharField(max_length=25) For now I have this view: def group_notes_view(request): if request.method == 'POST': form = GroupSignInForm(request.POST) if form.is_valid(): group = NoteGroup.objects.get(group_name=form.instance.group_name) if group: if group.password == form.instance.password: user = request.user user.note_group = group user.save() ... else: form = GroupSignInForm() ... Form looks lie this by now class GroupSignInForm(ModelForm): class Meta: model = NoteGroup fields = ('group_name', 'password') It's working but I believe there is much better way to do it. -
Django Stripe account link return_url and refresh_url redirects causes user to be logged out of web application platform
I'm integrating stripe into my Django web application platform. When sellers onboard with Stripe Connect, an Account is created for them, and an AccountLink is created with a specified return_url and refresh_url that Stripe uses to redirect back to my web application. However, when the sellers are redirected back to my web application they are no longer logged into the web application. Is there a better solution than forcing the user to log back in? The following are some code snippets: views.py def stripe_on_boarding(request): if request.method == "GET": stripe_sk = settings.STRIPE_SECRET_KEY stripe.api_key = stripe_sk user = request.user account = None print("I'm logged in as and am onboarding stripe [" + user.first_name + "]") if user.stripe_account is None: account = stripe.Account.create(type='express') user.stripe_account = account.id user.save() print("Saved User Object!") else: account = stripe.Account.retrieve(user.stripe_account) if account is not None and not account.details_submitted: account_links = stripe.AccountLink.create( account=account.id, refresh_url='http://098c818fbf8a.ngrok.io/marketplace/stripe_on_boarding_refresh', return_url='http://098c818fbf8a.ngrok.io/marketplace/seller_return', type='account_onboarding', ) return redirect(account_links.url) return render(request, 'become_seller_part_1.html', {'msg' : "You've already registered with stripe.", 'is_registered' : True}) # TODO: render a page if this view was triggered by a method other than GET. Could this be happening because I'm using ngrok to redirect to my localhost? -
NoReverseMatch at / Reverse for 'products' with arguments '('',)' not found. 1 pattern(s) tried: ['products/(?P<pk>[^/]+)/$']
I have tried viewing the other solutions of the community, but nothing came in help. I was just trying to match the inputs to database entries and thus show a result in the "products.html" page. Would be grateful if anyone could breakdown the solution. views.py from django.shortcuts import render, redirect from .forms import ProductForm from .models import Product def home(request): form = ProductForm() if request.method == "POST": form = ProductForm(request.POST) form.save() if form.is_valid(): return redirect('/') context = { 'form':form } return render(request, 'bye/home.html', context) def products(request, pk): product = Product.objects.get(id = pk) if request.method == "POST": return redirect('/') context = { 'product': product } return render(request, 'bye/products.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name ='home'), path('products/<str:pk>/', views.products, name = 'products') ] home.html </div> <div class = "col-md-12"><a href = "{% url 'products' product.id %}" class="btn btn-info btn-sm">Submit</a></div> </div> products.html {% extends 'bye/base.html' %} {% block content %} <p></p> {{product.name}} {% endblock %} Traceback Traceback (most recent call last): File "D:\DJPROJ\try\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\DJPROJ\try\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\DJPROJ\try\okay\bye\views.py", line 17, in home return render(request, 'bye/home.html', context) File "D:\DJPROJ\try\env\lib\site-packages\django\shortcuts.py", line …