Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Request req_5BdKqxhl1rXEbe: No such customer: cus_FLh58K7EslblSw django
when i try to add stripe to this project https://github.com/justdjango/django-ecommerce i have got this error Request req_5BdKqxhl1rXEbe: No such customer: cus_FLh58K7EslblSw even I added secret key and public key to the project same issue -
Getting the next Item in a queryset
Here's a snippet from Voting web project, and i'm trying to get the next category after voting @login_required def Nominees(request, category_id): categories = Category.objects.get(id=category_id) next_category = categories.id +1 college_id = categories.College.id if lastday < today: messages.info(request, "Window closed") context = {'categories':categories, 'college_id':college_id, 'lastday':lastday, 'today':today,'next_category':next_category} return render(request, 'nomination/contestants.html', context ) def Voting(request): if request.method == "POST": vote_user = request.POST.get('vote_user') vote_contestant = request.POST.get('vote_contestant') vote_category = request.POST.get('vote_category') next_category = request.POST.get('next_cat') vote_college = request.POST.get('vote_college') college = College.objects.get(pk=int(vote_college)) college_id = college.id nex = int(next_category)-1 try: Vote.objects.filter(user_id=request.user.id, category_id=vote_category)[0] messages.error(request, "You've already voted") return HttpResponseRedirect(reverse('nomination:nominees', args=(vote_category,))) except(IndexError, Vote.DoesNotExist): if lastday < today: messages.error(request, "Too late") return HttpResponseRedirect(reverse('nomination:nominees', args=(vote_category,))) else: new_vote = Vote(contestant_id=vote_contestant, category_id=vote_category, college_id=vote_college, user_id=vote_user) new_vote.save() messages.success(request, "Successfully voted!!") try: categories = college.category_set.filter(id=next_category, College_id=college_id)[nex] category_id=categories.id return HttpResponseRedirect(reverse('nomination:nominees', args=(category_id,))) except (IndexError, Category.DoesNotExist): categories = college.category_set.first() category_id = categories.id return HttpResponseRedirect(reverse('nomination:categories', args=(college_id,))) I would also appreciate it if i could get a better way of doing this like maybe using the nect function which ive tried but still it;s giving me issues, thank you so much -
How to add an attribute to request like the 'user' variable
I want to create a new variable which is always available like how the 'user' variable works. Here is my myapp/context_processors.py def patient_selected(request): print(hasattr(request, 'patient_selected_id')) print( 'patient_selected_id' in locals()) print( 'patient_selected_id' in globals()) if not hasattr(request, 'patient_selected_id'): request.patient_selected_id = 0 return {"patient_selected_id": 0} The problem is, it always prints 'false'. It seems like I cannot add an attribute to the request, nor create a variable constantly available. BTW, I have added this context_processors.py to settings. Here is my setting: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'hrs.context_processors.patient_selected', ], }, }, ] -
Django server inaccessible
I have a Django 2.2.5 server running on a Windows 7 machine. I'd like to access it from my Android phone to make sure that the website being served by the Django server works well on the Android device. However, the website fails to load on the Android device. I've look around and found some things to try, but nothing has worked. Here'a list of things I've tried, all of which have failed: Debug = False ALLOWED_HOSTS = ['*'] Allowing any traffic through port 8000 through firewall Turning firewall off Accessing from raspberry pi I've also tried some testing on the Windows 7 machine: When ALLOWED_HOSTS = [], I can access the site with localhost:8000/my_site and 127.0.0.1:8000/my_site, but not my_ip_address:8000/my_site. This may be expected behavior, and I am okay with that. When ALLOWED_HOSTS = ['localhost', my_ip_address], if I'm not mistaken, localhost:8000/my_site should work, 127.0.0.1:8000/my_site should not work, and my_ip_address:8000/my_site should work. As expected, localhost:8000/my_site works and 127.0.0.1:8000/my_site does not work. my_ip_address:8000/my_site, however, does not work. Can anybody explain this to me and help me access my Django server from my Android phone? -
AJAX success not render properly since second request
I use ajax to render output to below HTML element. <p class="result-box" id="result-box">The result is : <br><strong id="result"></strong></p> When I update my input, the console changes and prints desired data but the webpage including the text does not change. I get Cannot read property 'setAttribute' of null at canvas_and_ploton the 2nd+ time refresh below, If I remove setAttribute, I get Cannot read property 'getAttribute' of null at canvas_and_plot. $(document).on('submit','#cat_select',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/cat_select', data:{ l2:$('#l2').val(), l3:$('#l3').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function server_response(response) { const r = JSON.parse(response); console.log(r); //refreshed var cat_result = r.cat_result; console.log(cat_result[0]) //refreshed, below rendering to HTML does not refresh var text=$('<i></i>'); $.each(cat_result, function(idx, value) { text.append('<id="result'+idx+'">' + cat_result[idx][0]+ '<br>'); text.append('<canvas id="canv_'+idx+'" width="200" height="200"></canvas><br>'); }); $('#result').replaceWith(text); $.each(cat_result, function(idx, value) { canvas_and_plot(idx,cat_result[idx][9],cat_result[idx][10],cat_result[idx][11])}); } function canvas_and_plot(idx,a,b,c) { var canv = document.getElementById('canv_'+idx); canv.setAttribute('id', 'canv_'+idx); var C = document.getElementById(canv.getAttribute('id')); //plot... } I tried adding cache: false and adding random number to the url but neither of them works. Why only error after the first request? How can I fix this? Thanks -
Error occurring when setting up postgresql with Django
I am creating a project in Django which aims to use postgresql as the database. I have gone into the settings file added all the required properties to setup the postgresql database. When I attempt the run the server, a prompt to install psycopg2-binary occurs. This is expected, as I have encountered this issue in my other projects. When I install in my other projects, It successfully gets installed and I can apply migrations and run the server. However for this project, when I type in pipenv install psycopg2-binary, an error occurs which I haven't encountered before. Error: `exceptions.InstallationError: Command "python setup.py egg_info" failed with error code 1 in /var/folders/wq/c85_j_cd4n7by1kyz4z2_yq40000gn/T/tmpthm8df6cbuild/psycopg2-binary/` Note that I am using the latest version of python(3.8), and the latest version of pip. Anyone know how to fix this and successfully complete the install of psycopg2-binary? Thank you. -
How to login with e-mail in Django?
I am trying to change the way the user do log in by changing from username to email. I put in settings.py: AUTHENTICATION_BACKENDS = ['apps.myapp.ModelBackend'] In myapp I created the file backends.py with the code: from django.contrib.auth import backends, get_user_model from django.db.models import Q UserModel = get_user_model() class ModelBackend(backends.ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: # user = UserModel._default_manager.get_by_natural_key(username) # You can customise what the given username is checked against, here I compare to both username and email fields of the User model user = UserModel.objects.get(Q(username__iexact=username) | Q(email__iexact=username)) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user return super().authenticate(request, username, password, **kwargs) And on myapp in models.py I did: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): USERNAME_FIELD = 'email' email = models.EmailField(unique=True, name='email address') REQUIRED_FIELDS = [] But when I run makemigrations I get the following error: SystemCheckError: System check identified some issues: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for … -
How to add a new pip package to a deployed application with heroku
I have deployed a django rest api with heroku. And I have some updates regarding the code, For updating the source code is easy just updating the source code and commit changes with git. But I have trouble adding a new pip package. Is there a solution for this problem or do I need to re-deploy the application? -
Encrypting communication between between Microservices
I am dealing with communication between microservices. Microservice A - Angular6/django Microservice B - NodeJS My Microservice A is in company network and Microservice B is in AWS. we need to find a way to communicate between them securely like using VPN or other encryption. what is the best way to architecture this communication? -
Django and JQuery - Find and Replace Text
I want to transfer data from one tag to the other. This is how far I got: <a id="oldartist"> {{ object.user }}</a> <a id="newartist"></a> function newArt() { var artistname = document.getElementById("oldartist"); $('#newartist').text(artistname); }; But I get https:// mywebsite.com/johndoe instead of johndoe Why is this happening and how can I fix it? Thank you for any help -
Getting token of user
I am new to django/python. I currently use api-token-auth to generate user auth token successfully. But i will like to write an api function to get and validate the token before executing. ie my app need validated user to access certain resources. How can i write the get the valid auth token and pass it to the rest of the process? I am using the below code but get errors Thank you -
DRF - combine django_filter and ordering
I use drf alongside with django-filters. The problem is I can't make work django-filters with ordering. from django_filters import rest_framework from rest_framework import viewsets from feeds_core.imports.models import SourceFeedFetch from feeds_core.imports.serializers import SourceFeedFetchSerializer from products.filters import ProductFilter from products.models import Product from products.serializers import ProductSerializer class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer filter_backends = (rest_framework.DjangoFilterBackend,) filter_class = ProductFilter def get_queryset(self): return Product.objects.all() class ProductFilter(FilterSet): ordering = OrderingFilter( fields=( ('name', 'name'), ), ) class Meta: model = Product fields = {'name': ['icontains']} When I go to http://127.0.0.1:8000/api/products/ it raises: TemplateDoesNotExist at /api/products/ django_filters/rest_framework/form.html Do you know what is wrong with that? -
ImportError: cannot import name 'OrderDetailView' from 'core.api.views' in Django and ReactJs
after i Build OrderDetailView Class, i run python manage.py migrate in backend it show error as from .views import ( ImportError: cannot import name 'OrderDetailView' from 'core.api.views' (C:\Users\Dell\project7\core\api\views.py) In frontend, it show an error as Network Error "message":"Network Error","name":"Error","stack":"Error: Network Error\n at >createError (http://localhost:3000/static/js/0.chunk.js:1970:15)\n at XMLHttpRequest.handleError api > urls.py from django.urls import path from .views import ( ItemListView, AddToCartView, OrderDetailView ) urlpatterns = [ path('product-list/', ItemListView.as_view(), name='product-list'), path('add-to-cart/', AddToCartView.as_view(), name='add-to-cart'), path('order-summary/', OrderDetailView.as_view(), name='order-summary') ] api> views.py from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render, get_object_or_404 from django.utils import timezone from rest_framework.generics import ListAPIView, RetrieveAPIView from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST from core.models import Item, OrderItem, Order from .serializers import ItemSerializer, OrderSerializer class ItemListView(ListAPIView): permission_classes = (AllowAny,) serializer_class = ItemSerializer queryset = Item.objects.all() class OrderDetailView(RetrieveAPIView): serializer_class = OrderSerializer permission_classes = (IsAuthenticated,) def get_object(self): try: order = Order.objects.get( user=self.request.user, ordered=False) except ObjectDoesNotExist: return Response({"message": "You do not have an active order"}, status=HTTP_400_BAD_REQUEST) constants.js const localhost = "http://127.0.0.1:8000"; const apiURL = "/api"; export const endpoint = `${localhost}${apiURL}`; export const productListURL = `${endpoint}/product-list/`; export const addToCartURL = `${endpoint}/add-to-cart/`; export const orderSummaryURL = `${endpoint}/order-summary/`; -
How to display the Form properly?
I just want to show a Form on a HTML Page. When I put it on the Page and look via Web Browser, there seems to show me the memory address instead of rendering the form.. [forms.py] from django import forms MODES=[('top10', 'Top 10 Songs'), ('last10', 'Last 10 Songs'), ('recentX', 'Recent X Songs')] class chooseMode(): first_name = forms.CharField(required=True) selectMode = forms.ChoiceField(label='Choose Mode', widget=forms.RadioSelect,choices=MODES) [views.py] def home(request): modusFormular = chooseMode() return render(request, 'home.html', {'modusForm' : modusFormular}) [home.html] somewhere in body: {{ modusForm }} I expected the form to be shown on the page, but it shows me the following: -
TemplateDoesNotExist at /accountparents/login/
The signup.html is working fine but if i click the login and logout, The error show this: TemplateDoesNotExist at /accountparents/login/ registration/login.html I dont know where I can locate that registration/login.html This is my settings.py INSTALLED_APPS = [ 'accounts', 'Homepage', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'Homepage/templates','accounts/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] and this is my URLS.py urlpatterns = [ path('home/', Homepage.views.home, name='home'), path('login/', LoginView.as_view(template_name='Homepage/login.html'), name='login'), path('logout/', LoginView.as_view(template_name='Homepage/logout.html'), name='logout'), path('staff/', Homepage.views.staff, name='staff') ] -
Redirect to same page in django
I keep getting an ERR_TOO_MANY_REDIRECTS error each time i try to redirect to same page in django. I tried using return HttpResponseRedirect('') but it shows a blank screen. I have equally tried : from django.http import HttpResponseRedirect **views.py** class Test(DetailView): def get(self, request, *args, **kwargs): if not .....: return HttpResponseRedirect(self.request.path_info) -
Django: Template Form action not redirecting
My Form action is not redirecting to the passed view. I am calling simple_upload view method from login_form.html form action. Instead, upon clicking the login button, it stays on the same page. Below is my code: urls.py: from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from uploads.core import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', views.login_form, name='login_form'), url(r'^upload/', views.simple_upload, name='simple_upload'), url(r'^drop_down/$', views.drop_down, name='drop_down'), url(r'^visualize_view/$', views.visualize_view, name='visualize_view'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.AKASH_ROOT) login_form.html: {% block content %} <button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Login</button> <div id="id01" class="modal"> <form class="modal-content animate" action="{% url 'simple_upload' %}" method="get"> {% csrf_token %} <div class="imgcontainer"> <span class="close" title="Close Modal">&times;</span> <img src="https://www.w3schools.com/howto/img_avatar2.png" alt="Avatar" class="avatar"> </div> <div class="container"> <label for="uname"><b>Username</b></label> <input type="text" placeholder="Enter Username" name="uname" required> <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="psw" required> <button type="submit">Login</button> <label> <input type="checkbox" checked="checked" name="remember"> Remember me </label> </div> <div class="container" style="background-color:#f1f1f1"> <button type="button" class="cancelbtn">Cancel</button> <span class="psw">Forgot <a href="">password?</a></span> </div> </form> </div> <script> // Get the modal var modal = document.getElementById('id01'); // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } </script> {% endblock %} views.py: from django.http import HttpResponse from django.shortcuts … -
docker compose error when "building wheel for psycopg2
Im pretty new with docker. I ran the command docker-compose up -d using docker for windows and it went fine, but now that I'm doing it in ubuntu, it doesn't work. This is the error Building wheel for psycopg2 (setup.py): started ERROR: Command errored out with exit status 1: command: /usr/local/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-7u_i6jh4/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-7u_i6jh4/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-bjao_ppd --python-tag cp38 cwd: /tmp/pip-install-7u_i6jh4/psycopg2/ Complete output (72 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/psycopg2 copying lib/psycopg1.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/sql.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.8/psycopg2 creating build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_green.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_types_extras.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_bugX000.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_module.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_types_basic.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_with.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_errcodes.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/dbapi20_tpc.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_async.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_quote.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_ipaddress.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_lobject.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_cancel.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/dbapi20.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_replication.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_extras_dictcursor.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying … -
Django CBV method firing order
I'm trying to dig deeper into class-based views and I couldn't find any advanced references of how exactly Django CBV's work under the hood. Let's take as an example a ListView. How can I determine methods firing order of this class? I love Django because of it's 'simplicity' but there is a moment in time when I'd like to be 100% sure of code I write. Best regards, Wojtek -
How to work BaseInlineFormSet inside Django form?
I'm so beginner in django so BaseInlineFormSet how to work i don't understand . class BaseAnswerInlineFormSet(forms.BaseInlineFormSet): def clean(self): super().clean() has_one_correct_answer = False for form in self.forms: if not form.cleaned_data.get('DELETE', False): if form.cleaned_data.get('is_correct', False): has_one_correct_answer = True break if not has_one_correct_answer: raise ValidationError('Mark at least one answer as correct.', code='no_correct_answer') -
Algorithm/Query For Determine Weighted Reward
I'm working on a game where a user is given a random reward with each reward's chance of being delivered weighted by a "share" system. To illustrate the issue, let's look at an example: Let's say I was going to give a pure random reward, out of set: [A, B, C]. It would be as simple as getting a random index and returning whatever reward from the array. In my use case, however, the reward set is weight with a "share" system. So we have a situation like below: A - Weight of 2. B - Weight of 3. C - Weight of 5. So the set looks like something like this: [A, A, B, B, B, C, C, C, C, C]. Now, I could just build out that array and get a random result like that, but I'm concerned about performance implications. These rewards are stored in a database (using Django and PSQL as the backend if that factors in), and there may be upwards of 100 potential rewards, each with a weight of 1-100 (or more). So I'm trying to figure out an efficient method to pull a random reward based on such weight. As I'm writing this, … -
Django - Post list not appearing
Django blog posts not appearing I am new to Django and am trying to return a list of published blog posts. The page is appearing and no errors are produced, however no posts are showing. I have checked in the admin page and all posts are published. Model: class BlogPost(models.Model): title = models.CharField(max_length=200) snippet = models.CharField(max_length=400, null=True) Blog_pic = models.ImageField(upload_to='blog_pics',blank=True) hero_pic = models.ImageField(upload_to='blog_pics',blank=True) content = models.TextField() blogcategory = models.CharField(max_length=200, default='uncategorised') create_date = models.DateTimeField(default=timezone.now()) published_date = models.DateTimeField(blank=True, null=True) #def publish(self): # self.published_date = timezone.now() # self.save() def get_absolute_url(self): return reverse("BlogPost_detail",kwargs={'pk':self.pk}) Views: class BlogPostListView(ListView): model = BlogPost def get_queryset(self): return BlogPost.objects.all().order_by('-published_date') class BlogPostDetailView(DetailView): model = BlogPost Template: {% for BlogPost in BlogPost_list %} <div class="col-sm-6"> <a href="{% url 'BlogPost_detail' pk=BlogPost.pk %}"> <div class="card"> <img src="#"> <div class=""> <h4><span class="">{{ BlogPost.category }}</span></h4> <p class="">{{ BlogPost.tile }}</p> <p class="">{{ BlogPost.snippet }}</p> <p style="">{{ BlogPost.published_date }</p> <p style="">x min</p> </div> </div> </a> </div> {% endfor %} -
Setting a sender name when sending an email with smtplib and python
I am creating an endpoint where a user can get sent an email with a code to reset their password with. When sending the email, I am using the built in smtplib that comes bundled with python. When a request is made to the endpoint, I want the sender name to appear instead of the raw email. How can I accomplish this? Here's my code: code = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)) content = 'Subject: {}\n\n{}'.format('Your code to reset your password:', 'Your Code: {}'.format(code)) mail = smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() mail.starttls() mail.login(os.environ.get('email'), os.environ.get('password')) mail.sendmail(os.environ.get('email'), user.email, content) mail.close() When searching the web for similar questions, the only solution that came across was to add this line of code: content['From'] = "Your name " Adding this line of code didn't send the email at all. Does anybody know how to add the sender name to the email? Thank You. -
Define Django Model Constraints
I want to add a constraint onto a model that involves a reference to another model object. In the code below, I want to have, on the ProjectMember model, the project_member field constrained to be different from the project_creator in the project model. class User(models.Model): fullname = models.CharField(max_length=200) email = models.EmailField(max_length=254) password = models.CharField(max_length=254) class Project(models.Model): name = models.CharField(max_length=200) timestamp = models.DateTimeField("date created", auto_now=True) project_creator = models.ForeignKey(User, on_delete=models.CASCADE) class ProjectMember(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) project_member = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="member of the project" ) class Meta: order_with_respect_to = 'user_member' constraints = [ models.CheckConstraint(check= , name='project creator not project member'), ] -
Django - AttributeError: module 'os' has no attribute 'environment'
In the context of learning Django, I need to populate Sqlite with random data using Faker module. Several models have been created under models.py : from django.db import models class Topic(models.Model): top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic,on_delete=models.DO_NOTHING) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage,on_delete=models.DO_NOTHING) date = models.DateField() def __str__(self): return str(self.date) To randomly populate these models, I'm using the following script (populate_first_app.py): import os os.environment.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() ##FAKE POP SCRIPT import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print('populating script!') populate(20) print('populating complete') When I'm running populate_first_app.py, I got the following error: AttributeError: module 'os' has no attribute 'environment' Using Visual Studio Code (v1.39.2), I'm stuck. Visual code is highlighting error on following lines: t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] Class 'Topic' has no 'objects' memberpylint(no-member) I installed pylint using the following command: pip3 install pylint-django But still stuck.