Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to read .env file in django celery
I used celery (5.0.5), django (3.1.1), django-dotenv project structure Project api ----task.py config ----settings.py ----celery.py manage.py Typing celry -A config worker -l INFO results in an error I don't seem to be able to read the .env file Because it works fine in db.splite3 I tried adding the code dotenv.read_dotenv(env_file) in celery.py. But it didn't work. What am I missing? > celery -A config worker -l INFO Traceback (most recent call last): File "/Users/junyoung/Dev/notification-drawer-api/venv/bin/celery", line 10, in <module> sys.exit(main()) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/bin/celery.py", line 213, in main return celery(auto_envvar_prefix="CELERY") File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/click/core.py", line 1259, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/click/core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/click/decorators.py", line 21, in new_func return f(get_current_context(), *args, **kwargs) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/bin/base.py", line 132, in caller return f(ctx, *args, **kwargs) File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/bin/worker.py", line 320, in worker worker = app.Worker( File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/worker/worker.py", line 94, in __init__ self.app.loader.init_worker() File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/loaders/base.py", line 111, in init_worker self.import_default_modules() File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/loaders/base.py", line 105, in import_default_modules raise response File "/Users/junyoung/Dev/notification-drawer-api/venv/lib/python3.8/site-packages/celery/utils/dispatch/signal.py", line 276, in send response = receiver(signal=self, sender=sender, **named) … -
django how to loop in view and print in template
i have serial numbers in my database , each serial number have coded date in it, i want to get the date from the serial number and print in data table my view.py from .models import Module month = {'1': 'Jan', '2': 'Feb', '3': 'Mar', '4': 'Apr', '5': 'May', '6': 'Jun', '7': 'Jul', '8': 'Aug', '9': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dec'} year = {'L': '2010', 'M': '2011', 'N': '2012', 'O': '2013', 'P': '2014', 'Q': '2015'} @login_required() def modules(request): modules = Module.objects.all() for module in modules: day = module.serial_number[:2] mon = module.serial_number[2:3] mon = [val for key, val in month.items() if mon in key] year1 = module.serial_number[3:4] year1 = [val for key, val in year.items() if year1 in key] print(module.serial_number, day, mon, year1) total_modules = modules.count() context = {'modules': modules, 'total_modules': total_modules, } return render(request, 'modules/modules.html', context) when print(module.serial_number, day, mon, year1) im getting what i want 044PGG01501S 04 ['Apr'] ['2014'] 127QGG01501S 12 ['Jul'] ['2015'] but cant make this work in template any ideas -
Override admin_menu.py file in django admin panel for sidebar customization
There is a file called admin_menu.py in django_adminlte_theme>templatetags. This file is used for customization of sidebar of django admin panel i.e. dropdowns menus are their order Everything is set except the main thing i.e. override this, right now I am doing this by overriding i the base file which came on the installation and we cannot upload this with other files on server. I have tried a few things like changing the templates directory in settings.py, adding site-packages or django-adminlte-theme folder in my project directory Is their anyway of doing this??? Thankyou in advance -
GET urls with different path params in DRF
I need 2 GET urls in my DRF application myapp/members/{id}/benefits myapp/members/{member_number}/benefits And i need to redirect it to 2 different viewsets also myapp/members/{id}/benefits - Viewset1 myapp/members/{member_number}/benefits - Viewset2 Is that possible. If yes, how can I design my urls.py? -
PostgreSQL and My Django app on heroku is not synching
I have a django made app on heroku and I want change the database there from sqlite to postgreSQL. I have changed the code in setting.py as follows however the data in my local sqlite is still uploaded to heroku. from socket import gethostname hostname = gethostname() if "MY-COMPUTER-NAME" in hostname: #my computer name # debug # DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } ALLOWED_HOSTS = ['*'] else: # online # DEBUG = False import dj_database_url db_from_env = dj_database_url.config() DATABASES = { 'default': dj_database_url.config() } ALLOWED_HOSTS = ['*'] My commands to deploy git add -A git commit -m "Change" git push heroku master heroku ps:scale web=1 heroku run python manage.py migrate heroku open this is a full code of srtting.py import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ":)" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ … -
I want to display registered person details like (first name , email , phone number) in profile.html page page - django
I want to display registered person details like (first name, email, phone number) in profile.html page page... what is the code use in views.py file.. can anyone help me Here is registered table in models.py class Register(models.Model): fullname=models.CharField(max_length=60) companyname=models.CharField(max_length=60) Email=models.CharField(max_length=50) password=models.CharField(max_length=12) contactno = models.CharField(max_length=30) I want to display these details in profile.html page Here is my views.py file for profile def profile(request): return render(request, 'web/profile.html') -
how to implement wishlist to have unknown number of items - Django
I want to implement a wishlist for my online shop project which is a Django project. I already implemented WishListItem table and due to my scenario, I used GenericForeignKey: class WishListItem(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50, null=True, blank=True) count = models.IntegerField(null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) add_to_list_date = models.DateTimeField(_('add to list date'), null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.title now I have to implement Wishlist table. 1- the user may have many wishlists. 2- each wish list have an unknown number of WishlistItemss. here is what I have in mind: class QuoteList(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) message = models.CharField(max_length=200) item = models.ForeignKey(WishListItem, on_delete=models.CASCADE) but I know it's not quite good. how to add many wishlistitems to one quotelist? -
How to get suggestion with a model field
I want to get suggestions in user end with order given by field following with Alphabetical order. I have written a view where now I am getting suggestion in Alphabetical order class ParentIndustry(models.Model): name = models.CharField(max_length=285, blank=True, null=True) date_added = models.DateTimeField(null=True, blank=True, auto_now_add=True) date_modified = models.DateTimeField(null=True, blank=True, auto_now=True) status = models.IntegerField(default=0) sort_data = models.IntegerField(default=0) modified_by = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return str(self.name) class Meta: verbose_name_plural = "Parent Industries" I want to get suggestion with field value sort_data = 0,1,2,3,4,5 after assigning a value in admin. Now I am getting data in User End from ascending to descending (Alphabetical order) with below view function. def industry_list_suggestion(request): name = request.GET.get('q') industry = request.GET.getlist('industry[]') if name is None: filters = models.Q() company_results = ParentIndustry.objects.filter(filters,status='1').order_by('name','-id').values('name','id').exclude(name__isnull=True).distinct('name') page = request.GET.get('page', 1) paginator = Paginator(company_results, 10) try: results = paginator.page(page) except PageNotAnInteger: results = paginator.page(1) except EmptyPage: results = paginator.page(paginator.num_pages) total_count = company_results.count() company_results = list(results) results = {'total_count':total_count,"items":company_results,"value":"market"} return JsonResponse(results,safe=False) if name is not None: term = request.GET.get('q') filters = models.Q() filters &= models.Q( name__istartswith=term, ) sources_objects_suggestion = ParentIndustry.objects.filter(filters,status='1').order_by('name','-id').values('name','id').exclude(name__isnull=True).distinct('name') page = request.GET.get('page', 1) paginator = Paginator(sources_objects_suggestion, 10) try: results = paginator.page(page) except PageNotAnInteger: results = paginator.page(1) except EmptyPage: results = paginator.page(paginator.num_pages) total_count = … -
Django Rest API. Get all data from different models in a single API call
I am trying to get all data related to model Post using one single API call. This call should include post contents, comments, upvote and downvotes. I have 4 models and Post model is a foreign key to every other model. class Post(models.Model): title = models.CharField(max_length=200, null=True, blank=True) body = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return str(self.title) class UpVote(models.Model): post = models.OneToOneField(Post, related_name="upvote_post", on_delete=models.CASCADE) upvotes = models.IntegerField(default=0) class DownVote(models.Model): post = models.OneToOneField(Post, related_name="downvote_post", on_delete=models.CASCADE) downvotes = models.IntegerField(default=0) class Comment(models.Model): post = models.ForeignKey(Post, related_name="comment_post", on_delete=models.CASCADE) comment = models.CharField(max_length=200, null=True, blank=True) I saw this solution in a post to combine data with a foreign key relationship that exists. class UpVoteSerializer(serializers.ModelSerializer): class Meta: model = UpVote fields = "__all__" class DownVoteSerializer(serializers.ModelSerializer): class Meta: model = DownVote fields = "__all__" class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = "__all__" class PostSerializer(serializers.ModelSerializer): upvote = UpVoteSerializer(read_only=True, many=False) downvote = DownVoteSerializer(read_only=True, many=False) comments = CommentSerializer(read_only=True, many=True) class Meta: model = Post fields = ("id", "title", "body", "upvote", "downvote", "comments") This is from the views.py file @api_view(['GET']) def postList(request): post = Post.objects.all().order_by('-id') serializer = PostSerializer(post, many=True) return Response(serializer.data) This is the output that get returned [ { "id": 7, "title": "1st post", "body": "Body of 1st post" … -
How do I correctly render sqlite3 data on my html Django
This is the code for getting the data inside my database, basically I want to get the winning bid of each open listing, but when I render on the html it look wrong. NEED Want the request.user close listing and then show the winning bid of that close listing Correct HTML rendering view.py def closebidview(request): if request.user.is_authenticated: listings = request.user.listing_set.all().filter(open_at=False) bid_data = [] for i in request.user.listing_set.all().filter(open_at=False): bid_data.append(i.bid.order_by("-date").first()) return render(request, "auctions/closebid.html", { "listings": listings, "bids": bid_data }) else: return render(request, "auctions/closebid.html") closebidview.html {% extends "auctions/layout.html" %} {% block body %} <h2>Closebid {{ request.user.username }}</h2> {% if user.is_authenticated %} <div style="display: flex;"> {% for listing in listings %} <div class="card-deck" style="width: 18rem; padding: 2px;"> <div class="card"> <img class="card-img-top" src="{{ listing.image.url }}" alt="{{ listing.title }}"> <div class="card-body"> <h5 class="card-title">{{ listing.title }}</h5> <p class="card-text">{{ listing.description }}</p> <p class="card-text"><strong>Price: ${{ listing.starting_price }}</strong></p> {% if user.is_authenticated %} {% for bid in bids %} {{ bid.user }} <p>{{ bid.user.username }} is the winner</p> <p>Contact:</p> <ul> <li>{{ bid.user.email }}</li> </ul> {% endfor %} {% else %} <p><a href={% url 'login' %}>Login</a> to see the winner!</p> {% endif %} </div> <div class="card-footer"> <small class="text-muted">{{ listing.create_at }} by: {{ listing.owner.username }}</small> </div> </div> </div> {% empty %} <h1>{{ request.user.username … -
How to access 2 different model filefields in View and copy paste data from one file to the other
I have 2 models with filefield: from django.db import models from django.db.models import Model class ExcelModel(Model): Excel_file = models.FileField() file_name = models.CharField(max_length=100, default='lolcakes') class CsvModel(Model): csv_file = models.FileField() file_name = models.CharField(max_length=100, default='meow') In view, I want to access each file and copy the value in row 1 and column 1 inside the meow csv file, to the excel file. I am looking into using Openpyxl for this but I cannot get past accessing the file. -
Manager used in django query
Is it possible to get the name of the manager used in making a query. say for example I did; x = Products.objects.first() y = Products.some_objects.first() where some_objects is a custom manager, would it be possible to get objects and some_objects as the manager used in making the query? -
Best way to log, then send single email using Django Mailer?
So I have this function for sending messages queued by Django Mailer: from django.core import management #send queued emails with django-mailer. def email_now(): management.call_command('send_mail') Then I overwrite the Django PasswordResetForm's send_mail() method: def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): subject = loader.render_to_string(subject_template_name, context) subject = ''.join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) email_message = EmailMultiAlternatives(subject, body, from_email, [to_email]) if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) email_message.attach_alternative(html_email, 'text/html') #log the message mailer.send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [to_email]) #then send via management command email_now() So, primarily I'm wondering if the final 2 lines, and using email_now() is an acceptable way to do this. Also, wondering if there's a way to implement this using the email_message object. Thank you. -
I am looking for a solution concerning the datefield
how to add the number of days to recover from the computer example: January 12, 2021 +10 = January 22, 2021 help me?un -
Optional parameters passed in a Django URL
Sorry if this is complete noob question, I just can't seem to get a straight answer with this very simple concept. In Django (Django Rest Framework actually, but I assume it would be the same), how do I pass optional parameters in the URL? Based on all the info I could gather, I have a urls.py that goes like this: # urls.py from .views import (HistoryIndex, from django.urls import re_path urlpatterns = [ re_path(r'^history/(?P<limit>)/$', HistoryIndex.as_view(), name='history_index'), ] The idea is to pass in a optional parameter (using the ? & syntax), limit, to limit the results passed back: # views.py from rest_framework.views import APIView from rest_framework.response import Response from .models import EventHistory from .serializers import class HistoryIndex(APIView): def get(self, request, **kwargs): user = request.user limit = int(kwargs['limit']) histories = EventHistory.objects.filter(user=user).order_by('-updated_at')[:limit] history_index = [ HistorySerializer(history).data for history in histories ] return Response(history_index) I'd like to be able to hit the endpoint like so: http://localhost:8000/history/ or http://localhost:8000/history/?limit=10 but I can't even get as far as my view. The django browsable API shows a 404, but in its list of possible endpoints, it includes ... ^history/(?P<pk>[\w-]+)/$ [name='history_index'] ... as an available endpoint. What am I missing? I'm sure it's something trivial but I … -
Custom errors in forms
I'm trying to make a custom error in a form in a class based view (CreateView). I have read the documentation and it is supposed that with the "clean()" function you can add errors, but my problem is that the form is submitted even when the error should appear. this is my class: class RecommendationCreateView(LoginRequiredMixin, CreateView): model = Recommendation template_name = 'recommendation/recommendation_new.html' form_class = NewPostForm success_url = reverse_lazy('home') def get_form_kwargs(self): """ Passes the request object to the form class. This is necessary to only display members that belong to a given user""" kwargs = super(RecommendationCreateView, self).get_form_kwargs() kwargs['request'] = self.request.user return kwargs def post(self, request): super(RecommendationCreateView, self).post(request) to_user=request.POST['to_user'] to_user = user_model.objects.filter(id = to_user).get() hobby = request.POST['hobby'] hobby = Hobby.objects.filter(id = hobby).get() recom = Recommendation.objects.create(from_user=request.user, to_user=to_user, hobby=hobby, text=request.POST['text']) recom.save() return redirect('recommendations') this is my form: class NewPostForm(forms.ModelForm): def clean(self): super(NewPostForm, self).clean() to_user = self.cleaned_data.get('to_user') to_user = user_model.objects.filter(username=to_user.username).get() if to_user.username == 'NAME': self._errors['to_user'] = 'Custom error to display' return self.cleaned_data class Meta: model = Recommendation fields = ('from_user', 'to_user', 'hobby', 'text') widgets = {'from_user': forms.HiddenInput()} this is my model: class Recommendation(models.Model): id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False ) from_user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name="recommendation_request_sent", ) to_user = … -
Django Q query with string generated query is giving error
I am trying to create a Django Q query, with any number or inputs having OR condition. E.g. there can be any number of trends from a list of 5 trends When I hardcode the query using two trends, it works fine: data.objects.filter(Q(trend__trend='Investment') | Q(trend__trend='Collaboration')) However, when I create a string of Q queries with n number of trends qString = "Q(trend__trend='Investment') | Q(trend__trend='Collaboration')" ... and pass it as data.objects.filter(qString)... it throws the following error: ValueError at /trend=Investment|Collaboration too many values to unpack (expected 2) I don't know how many trends would a user select, so have to make the query dynamic. What am I doing wrong? TIA -
Django user login session not accessible when I try to fetch it from my React frontend
I have a django app running. I have created a login_status view under my API that returns JSON:true/false if I am logged in or not. When I load this in my browser it works fine. When my React app tries to fetch this same page, Django ALWAYS returns false. Somehow my login session is invisible. How do I fix this? Note: My React app & Django app are running on two different ports. I have enabled CORS by installing django-cors-headers. I am not using the React REST Framework, just plain Django. here is my front end code: import React, {useState, useEffect} from 'react'; import ReactDOM from 'react-dom' import Modal from 'react-modal' import Vim from './Vim'; import './Main.css'; import './modal.css'; Modal.setAppElement('#root') function Main():JSX.Element { const [postId,updatePostId] = useState<number|null>(null) const [content, updateContent] = useState<string>('default text'); const [auth, updateAuth] = useState<boolean>(false) const [authModalIsOpen, setAuthModal] = useState(false) const [username, setUsername] = useState('') const [password, setPassword] = useState('') const apiUrl = 'http://127.0.0.1:8000/' function openAuthModal(){ setAuthModal(true) } function closeAuthModal(){ if(auth){ setAuthModal(false) } } function get_api(path:string){ return fetch(apiUrl+path) .then(res=>res.json()) .then(result=>result) } useEffect(()=>{ if(postId){ // Detect change in PostID & go download it. // Ignore if we are coming from null->number fetch(apiUrl+'get_post/'+postId) .then(res=>res.json()) } },[postId]) useEffect(()=>{ // if … -
Django register user extending djoser view with custom view
I'm trying to use djoser. I need to customize the registration flow. To have this I'm trying to create my custom view extending the Djoser view. But something seems wrong. I'm trying in this way: from djoser.views import UserViewSet class SignUpView(UserViewSet): def perform_create(self, serializer): super(SignUpView, self).perform_create(serializer) # My custom logic into my app urls file: urlpatterns = [ url(r'^auth/signup$', views.SignUpView.as_view(), name='sign-up'), ] I'm not able to call my custom view. If the called url is correct, using the POST method, I'm obtaining this error: CSRF verification failed. Request aborted. I stared from this link: Djoser Adjustment But, is this still correct for djoser 2.1.0 version? -
django - dash app ImportError: cannot import name 'Dash' from 'dash'
There's actually no useful solution online. I get this error : Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/.heroku/python/lib/python3.8/site-packages/django_plotly_dash/__init__.py", line 31, in <module> from .dash_wrapper import DjangoDash File "/app/.heroku/python/lib/python3.8/site-packages/django_plotly_dash/dash_wrapper.py", line 32, in <module> from dash import Dash ImportError: cannot import name 'Dash' from 'dash' (/app/.heroku/python/lib/python3.8/site-packages/dash/__init__.py) while pushing an app that contains dash components to heroku. It seems something is wrong with paths here. It happend during collectstatic phase. … -
How to deal with "Django error - Matching query does not exist" without breaking your code?
I came across this error where I was trying to retrieve a user using a query from the database. Below was my initial code which wanted to retrieve a user from a model called Order with the object writer def assigned(request): orders = Order.objects.get(writer=request.user) if orders: return render(request, 'mainapp/assigned.html', {'orders': orders}) else: return render (request, 'mainapp/assigned.html') However, after running my page I got a DoesNotExist: Comment matching query does not exist Error. This was not the correct way to handle this. -
Django project doesn't 'see' Python modules installed with Pipenv
I am just starting out with Django and I have this problem. The files are written in the Pipfile, for future reference, but my Django project cannot make use of the actual modules. I have to go to the folder where pipenv install them: C:\Users\my_name.virtualenvs\my_folder and I usually copy them from there and paste them in my working folder. That kind of defeats the purpose, and its not very convinient. How can I solve this? -
Django-admin AttributeError:
I've just started learning how to use django for some school projects.I installed django with pip but when I try to start a project with django-admin startproject abc I get error: File "c:\users\user\.virtualenvs\project-gnrbo21b\lib\site-packages\django\utils\crypto.py", line 74, in <genexpr> return ''.join(secrets.choice(allowed_chars) for i in range(length)) AttributeError: module 'secrets' has no attribute 'choice' I can't find any solutions on internet, any ideas ? Thank you -
Is there a way to include the ForeignKeys from other models in Django?
I'm creating a simpel website in Django (latest) that does the following: In the admin panel I can create a company and a team, there's a third model that contains the forms. In models.py: class Company(models.Model): companyId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) companyname = models.CharField(max_length=254) ....some other fields.... class Team(models.Model): teamId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) teamname = models.CharField(max_length=254) company = models.ForeignKey(Company, related_name='teams', on_delete=models.CASCADE) ....some other fields.... class UserForm(models.Model): UserForm_id = models.AutoField(primary_key=True) UserForm_company = models.ForeignKey(Bedrijf, related_name='UserForm_company', on_delete=models.CASCADE, null=False) UserForm_team = models.ForeignKey(Team, related_name='UserForm_team', on_delete=models.CASCADE, null=False) ....some other fields.... In views.py: class UserFormCreateView(CreateView): context_object_name = 'form_UserForm' form_class = UserFormName template_name = 'app/form.html' success_url = reverse_lazy('') #leads to index.html model = models.UserForm In the urlpatterns (urls.py) I include the following: (I have included the slugs in my models and views) urlpatterns = [ ..... path('<slug:urlCompany>/<slug:urlTeam>/<slug:urlForms>', views.UserFormCreateView.as_view(), name='UserForm'), ] Individual members are not registered. I just have multiple companies and each can have multiple teams. Teams would navigate to a url similar to: app/1239a36e-9694-42c3-a6f8-e058db218feb/b28819e0-5d97-4c3f-97aa-9d6cb55a0b07/userform which corresponds with app/urlCompany/urlTeam/urlForm So far so good. What I would like to have is that when the form is submitted, the companyname and teamname is included automatically. When I test the form, these fields (in the adminpanel) remain empty. Is there … -
Cart transfer between sites [closed]
Python/Django: Im trying to build something that would allow a user to make a cart on my site and then redirect that user to the e-commerce site where the basket is from. My problem is that I dont know how to transfer the whole basket to the e-commerce site. Could you please let me know what do you think? ( also the e-commerce site in question does not have an API, or an affiliate program I can work with )Thank you !