Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'User' object has no attribute 'is_staff' Django
i am getting an AttributeError while creating superuser for my model, that's showing AttributeError at /admin/login/ it would be great if anybody could help me out where i am doing thing wrong. thank you so much in advance. here below is my working code; models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=50) last_name = models.CharField(_('last name'), max_length=50, blank=True) avatar =models.ImageField(upload_to='avatar' , blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] managers.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('email must me set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Super User must have is_superuser=True') return self._create_user(email, password, **extra_fields) -
Using Ajax to receive total amount due before submitting to database
Trying to use Ajax to calculate and display the sum before I submit anything to the database. At the moment this is what I have, but I can't seem to get anything to display. I'm trying to start small and see if I'm even able to display the values in the fields.. Is my view for final_price wrong? Or did I mess up somewhere in the Jquery? I'm still new to Ajax, so I'm not sure where I went wrong (following tutorials) Book Price: $10 (input field) Delivery charge: $3 (input field) Delivery type: $5 (input field) [calculate] [submit] Final Result: $18 (result of adding the fields above when user clicks the calculate button) calculate button will display $18 submit button will finalize the results and send the values to the database. This is my model for the table class book(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) book_price = models.IntegerField() delivery_charge = models.IntegerField() delivery_type = models.IntegerField() final_result = models.IntegerField() def save(self, *args, **kwargs): self.final_result = self.book_price + self.delivery_charge + self.delivery_type print(self.final_result) super(book, self).save(*args, **kwargs) views.py for the form def final_price(request): response_data = {} if request.method == 'POST': form = RequestForm(request.POST) book_price = request.POST.get('book_price') delivery_charge = request.POST.get('delivery_charge') delivery_type = request.POST.get('delivery_type') response_data['book_price'] … -
Get profile from user's foreign key django
I am trying to get my customer's details but, having issues filtering it in the serial from the foreign key Customer. Here is what I have now: Serializers: class CustomerOrderSerializer(serializers.ModelSerializer): customer = OrderCustomerSerializer() class Meta: model = CustomerDetails fields = ('id', 'current_selfie', 'customer', 'phone') class OrderSerializer(serializers.ModelSerializer): customer= OrderCustomerSerializer() driver = OrderDriverSerializer() dispensary = OrderDispensarySerializer() order_details = OrderDetailSerializer(many=True) status = serializers.ReadOnlyField(source="get_status_display") customer_details = CustomerOrderSerializer.OneToOneField(customer, related_name='customer_details') class Meta: model = Order fields = ("id", "customer", "customer_details", "dispensary", 'delivery_signature', 'order_rated', "driver", "order_details", "total", "status", "address", "created_at") Model class Order(models.Model): a = 1 b = 2 c = 3 d = 4 e = 5 STATUS_CHOICES = ( (a, "ah"), (b, "bb"), (c, "cc"), (d, "dd"), (CANCELED, "Canceled/Refunded") ) address = models.CharField(max_length=500) created_at = models.DateTimeField(default=timezone.now) customer = models.ForeignKey(CustomerDetails, on_delete=models.CASCADE) delivery_signature = models.ImageField( upload_to='delivery_selfie/', blank=True, default='') delivered_at = models.DateTimeField(default=timezone.now) dispensary = models.ForeignKey(Dispensary, on_delete=models.CASCADE) driver = models.ForeignKey( Driver, blank=True, null=True, on_delete=models.CASCADE) picked_at = models.DateTimeField(default=timezone.now) order_rated = models.BooleanField(default=False) status = models.IntegerField(choices=STATUS_CHOICES) total = models.FloatField() def __str__(self): return str(self.id) class CustomerDetails(models.Model): age = models.IntegerField(default="21", blank=True) address = models.CharField( default='', max_length=254, null=True, blank=True) nick_name = models.CharField(max_length=500, blank=True) average_order = models.FloatField(default="0.0", blank=True) completed_orders = models.IntegerField(default="0", blank=True) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, related_name='customer') customer_type = MultiSelectField( choices=CUSTYPE, default=CUSTYPE, max_length=100) current_selfie = … -
Django API Log to LogStash
I am working on an API in Django and when the API call is finished, we need to log that data using the ELK stack. Here the Setup is Done Properly as I can see new logs showing up in the Logstash but not in Filebeat using which we push the Data to Kibanna. I am uploading screenshots for the configuration file and other details here. Please be Patient Code Segment from Django logger = logging.getLogger(__name__) logging.config.dictConfig( { "version": 1, "disable_existing_loggers": False, "formatters": { "console": {"format": "%(name)-12s %(levelname)-8s %(message)s"}, "file": {"format": "%(asctime)s %(levelname)s-%(message)s"}, }, "handlers": { "console": {"class": "logging.StreamHandler", "formatter": "console"}, "file": { "level": "DEBUG", "class": "logging.FileHandler", "formatter": "file", "filename": "/home/dhruv/elk_log/debug.log", }, }, "loggers": {"": {"level": "DEBUG", "handlers": ["console", "file"]}}, } ) # Create your views here. class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_data = request.data["file"] decoded_file = file_data.read().decode("utf-8").splitlines() file_serializer = FileSerializer(data=request.data) print("File data is", request.data["file"]) read_data = csv.DictReader(decoded_file) # s = smtplib.SMTP("smtp.gmail.com", 587) # s.starttls() id, password = settings.GMAIL_ID, settings.GMAIL_PASSWORD print(f"The gmail id and password is {id} {password}") # s.login(id, password) # Reading the Data as for item in read_data: # print(item) print( item["Email ID"], item["To"], item["cc"], item["bcc"], item["subject "], item["body"], ) # msg … -
how to create a django project using pycharm terminal
I created a project in the pycharm called pyshop. After that I downloaded the django 2.1 in my pycharm terminal. Then i went to create a project using the terminal of the pycharm. But it is showing an error like: (venv) C:\Users\shan\PycharmProjects\PyShop>django-admin startproject pyshop. CommandError: 'pyshop.' is not a valid project name. Please make sure the name is a valid identifier. what should i give as a valid identifier ? -
Service makemigrations has neither an image nor a build context specified
Hello I am trying to make workable a project. But when I run the following instruction : docker-compose up I got the following error : ERROR: The Compose file is invalid because: Service makemigrations has neither an image nor a build context specified. At least one must be provided. Here is the yml file docker-compose.yml : version: '3' services: db: image: postgres expose: - "5432" environment: - "POSTGRES_HOST_AUTH_METHOD=trust" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/myproject/ ports: - "8000:8000" - "3000:3000" depends_on: - db - makemigrations - migrations makemigrations: command: python manage.py makemigrations --noinput volumes: - .:/myproject/ depends_on: - db migrations: command: python manage.py migrate --noinput volumes: - .:/myproject/ depends_on: - db Could you help me please ? -
I want to group by the same date the errors (in django models)
I want to group together the errors that had been created on the same date class Error(models.Model): # Audit fields created_on = models.DateTimeField(auto_now_add=True) @classmethod def update_repeat_count(cls, app_error: 'Error'): # Sí el error es del mismo día que agrupe los errores sino nada if app_error.created_on.datetime.date[0] == app_error.created_on.datetime.date[1]:#I am not sure if the "if" is right because I can't try it in develop cls.objects.filter(pk=app_error.pk).update(repeat_count=F('repeat_count') + 1) app_error.repeat_count += 1 post_save.send(sender=cls, instance=app_error, created=False, update_fields=('repeat_count',)) Lots of thx for hellping me -
How can I use template blocks in django?
I'm trying to load a header template into my index with {% block %} but I can't get it to load index.html <body> <header> {% block header %}{% endblock %} </header> <h1>Hello</h1> </body> header.html {% extends "index.html" %} {% block header %} <div class="header"> <a href="/category/"><i class="fas fa-archive"></i></a> <a href="../"><i class="fas fa-home"></i></a> <h1>hey</h1> </div> {% endblock %} views.py def index(request): categories = Category.objects.all() context = {'categories': categories} return render(request, 'category/index.html', context) The app is installed in the settings. -
Django join models based on unique key
I have a situation where I can't join models based on foreign key. I want to join them based on common key that is basically foreign key to third table. Have a look at code: class Thread(models.Model): timestamp = models.DateTimeField(default=datetime.now) class Chat(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) message = models.CharField(max_length=2000) thread = models.ForeignKey(Thread, on_delete=models.CASCADE) read = models.BooleanField(default= 0) timestamp = models.DateTimeField(default=datetime.now) class User_Thread(models.Model): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE) reciever = models.ForeignKey(User, related_name='reciever', on_delete=models.CASCADE) I want to join Chat and User_Thread models based on same thread. How can I achieve this? Any thoughts? -
MultiValueDictKeyError - stripeToken Django error
the error message i am receiving in my template is --MultiValueDictKeyError at /checkout/ 'stripeToken'-- I can't seem to find a solution anywhere online. i have highlighted areas in the code where stripeToken occurs. Any suggestions would be appreciated as I am stuck on this for quite some time now! views.py import time import stripe from django.contrib.auth.decorators import login_required from django.conf import settings from django.shortcuts import render, HttpResponseRedirect from django.urls import reverse # Create your views here. from users.forms import UserAddressForm from carts.models import Cart from .models import Order from users.models import Profile, UserAddress, UserAddressManager from .utils import id_generator try: stripe_pub = settings.STRIPE_PUBLISHABLE_KEY stripe_secret = settings.STRIPE_SECRET_KEY except Exception as e: raise NotImplementedError(str(e)) # stripe_pub = "pk_test_AueCfYJ1QIxjLej496MIA43t00BNIWgUb6" stripe.api_key = stripe_secret def orders(request): context = {} template = "orders/user.html" return render(request, template, context) @login_required def checkout(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse("cart")) try: new_order = Order.objects.get(cart=cart) except Order.DoesNotExist: new_order = Order() new_order.cart=cart new_order.user = Profile.objects.get(user=request.user) # new_order.user = Profile.objects.get(user=request.user) new_order.order_id = id_generator() new_order.save() except: return HttpResponseRedirect(reverse("cart")) try: address_added = request.GET.get("address_added") except: address_added = None if address_added is None: address_form = UserAddressForm() else: address_form = None current_addresses = UserAddress.objects.filter(user=request.user) billing_addresses = UserAddress.objects.get_billing_addresses(user=request.user) # if 'stripeToken' in request.POST: … -
Cannot upload photo to Django With Rest Framework
I am attempting to make a request to upload a photo and change one text field. When I call my api, I get an error: . This is what I am trying: @csrf_exempt def driver_complete_order(request): # Get token driver = CustomJWTAuthenticator().authenticate(request)[0].driver # driver = access_token.user.driver print(request.POST) order = CompletedOrderSerializer(Order.objects.get( id=request.POST['order_id'] )) order.status = Order.DELIVERED order.delivery_signature = request.FILES['delivery_signature'] if order.is_valid(): order.save(commit=False) print(order.validated_data) order.save() return JsonResponse({"status": "success"}) When I attempt to upload a delivery signature I get a "django.utils.datastructures.MultiValueDictKeyError: "'order_id'" but, when I print the value, I get <QueryDict: {'access_token': ['eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODg2MDcyMDUsInVzZXJfaWQiOjI2MSwidG9rZW5fdHlwZSI6ImFjY2VzcyIsImp0aSI6IjUwZmYzOGVmYjNlNzQ1YTdhYmNhN2QyYmM3YTg2ZDg4In0.kxUNYcQ99xSOwMBw1g6rZtwuF1BLM5YrGY5-ykUlzq0'], 'order_Id': ['9'], 'delivery_signature': ['iVBORw0KGgoAAAANSUhEUgAAAY4AAAM4CAYAAADbCAU9AAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAUPSURBVHic7cEBDQAAAMKg909tDjegAAAACAVwMIpAABbE5p6AAAAABJRU5ErkJggg==']}> So I know there is data hitting the server. Not sure why it will not let me upload the data. -
Django url showed error: unresolved reference
I have a url path in urls.py: urlpatterns = [ ... url(r'^accounts/', include('allauth.urls')), ... ] but the url will show: unresolved reference 'url'. Did I miss something to import? -
Separate AJAX Forms on Single Django View
I'm not using Django's built in forms to display the form: Inside view.html is: <div> <form id="note-form" method="POST"> {% csrf_token %} <input type="hidden" name="form_name" value="noteForm" /> <textarea id="note-body" class="uk-textarea" style="resize: none;"></textarea> <button type="submit" class="uk-button uk-button-primary uk-button-small uk-margin-small-top">Add Note</button> </form> </div> Inside veiw.py is: if request.POST.get('action') == 'post': note_body = request.POST.get('note_body') response_data.update(note_author = request.user.first_name + ' ' + request.user.last_name) response_data.update(note_time = datetime.now().strftime('%B %m, %Y at %I:%M %p')) response_data['note_body'] = note_body Note.objects.create(item_id = id, body = note_body, author = request.user) return JsonResponse(response_data) Inside view.js is: $(document).on('submit', '#note-form', function(event) { event.preventDefault() $.ajax({ type: 'POST', data: { note_body: $('#note-body').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function(json) { document.getElementById("note-form").reset(); $('#notes').prepend( '<div>' + json.note_body + '<div class="uk-text-meta">Created by ' + json.note_author + ' on ' + json.note_time + '</div>' + '</div>' ) }, error: function(xhr, errmsg, err) { console.log(xhr.status + ": " + xhr.responseText); } }); }); This works, and it works like a well-oiled dream, until I attempt to add another form to the page. I need a way, using this existing code (or as much as it as possible), to separate the POSTs and I can't figure it out. I've attempted to change my view.py to incorporate a hidden field: if request.method == 'POST': … -
Creating dynamic choice field in Django forms, based on a view
I have been stuck for a while on this rather simple yet complicated task. Its actually a bit difficult to describe the problem, so hopefully you'll bare with me. I have these 3 models: class Subject(models.Model): batch = models.CharField(choices=LEVEL_CHOICES, max_length=2) subject_name = models.CharField(max_length=50) ... class StudentRegistration(models.Model): subject = models.ManyToManyField(Subject) ... class Season(models.Model): season = models.CharField(max_length=2, primary_key=True) subject = models.ManyToManyField(Subject) running = models.BooleanField(default=False) I want to create a StudentRegistration form for a certain Subject on a certain Season. For this I have first created a form where the user selects the Season and the batch. The view looks like this: def admission(request): if request.method == 'POST': form = DeterminingForm(request.POST) if form.is_valid(): selected_season = form.cleaned_data['season'] selected_batch = form.cleaned_data['batch'] form = DeterminingForm() After this I want to create the StudentRegistration form, where the user will have the option to select the subject(s) that are available for that selected_season and selected_batch. I have created a ModelForm for this, but I don't know how to query the database by taking the value form the view into the form, and display the available options in the choicefield (or any other field that is applicable). Currently all I have for that is this form: class StudentRegistrationForm(forms.ModelForm): class … -
Weasyprint or Reportlab for generating Django reports on Heroku
Trying to decide on the best route for generating server-side pdf reports within my app currently deployed on Heroku. I've read several posts that say both require installation external libraries- but haven't found anything describing functionality & ease of install on Heroku. Does anyone here have experience installing either to an app on Heroku? Is it a difficult process- is one easier to setup on Heroku than the other? Or if I am able to install on my local system and run PIP Freeze, will that take care of any installs necessary on Heroku? Thanks!! -
how fix docker when goes to restarting status after docker-compose in django on ubuntu
I use postgresql and docker in my django project. after docker-compose my container goes to restarting status. I tried fix it by stop and remove but didn't work docker-compose.yml: version: '3' services: blog_postgresql: image: postgres:12 container_name: blog_postgresql volumes: - blog_postgresql:/var/lib/postgresql/data restart: always env_file: .env ports: - "5432:5432" networks: - blog_network volumes: blog_postgresql: external: true networks: blog_network: external: true and terminal show this: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e8aa3e604ba3 postgres:12 "docker-entrypoint.s…" 3 days ago Restarting (126) 14 seconds ago blog_postgresql -
Is django-CMS and cookiecutter-django compatible?
I just tried to port my Django-CMS project into Django Cookiecutter (cookiecutter-django) in ordert to get it to run in Docker. It seems Django-CMS is using the default Django user model and Cookie-Cutter is using a custom model (from allauth?). I found this https://github.com/pydanny/cookiecutter-django/pull/248 thread and it suggests changing the order in which the apps are loaded but that doesn't cut the mustard. Are Django-CMS and Cookiecutter at odds with each other? -
ValueError at /checkout/ The view accounts2.views.CheckoutView didn't return an HttpResponse object. It returned None instead
Can anyone please help me fix this error? I'm trying to develop an e-commerce website using Django. Why is this error being thrown? It's in my views.py. But what's the problem actually and what does this error mean? My accounts2.views.py: class CheckoutView(View): def get(self, *args, **kwargs): the_id = self.request.session['cart_id'] cart = Cart.objects.get(id=the_id) form = CheckoutForm() context = {"form": form, "cart": cart} return render(self.request, "orders/checkout.html", context) def post(self, *args, **kwargs): form = CheckoutForm(self.request.POST or None) try: the_id = self.request.session['cart_id'] cart = Cart.objects.get(id=the_id) order = Order.objects.get(cart=cart) except Order.DoesNotExist: order = Order(cart=cart) order.cart = cart order.user = self.request.user order.order_id = id_generator() order.save() if form.is_valid(): street_address = form.cleaned_data.get('street_address') apartment_address = form.cleaned_data.get('apartment_address') country = form.cleaned_data.get('country') zip = form.cleaned_data.get('zip') # same_shipping_address = form.cleaned_data.get('same_billing_address') # save_info = form.cleaned_data.get('save_info') payment_option = form.cleaned_data.get('payment_option') billing_address = BillingAddress( user = self.request.user, street_address = street_address, apartment_address = apartment_address, country = country, zip = zip ) billing_address.save() order.billing_address = billing_address order.save() return redirect('checkout') messages.warning(self.request, "Failed checkout") return redirect('checkout') except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect('/') -
Empty query returns all fields from database. Django
In the search form field, If I don't enter anything, but push on the button to search the query. The query returns every each field from the database. Company.objects.exclude(Q(name__isnull=True)).exclude(Q(name__exact='')) Somehow, doesn't help me. If I use them together or separate. The code in views.py is: class className(listView) model=Company template_name='name_of_the_template.html' def get_queryset(self): query=self.request.Get.get('q') query=query.replace('#',' ') //same for ?\/$%^+*()[] *tried to set exclude code here if query == ' ': object_list = Company.objects.filter(Q(name__icontains='None'))//sending to the empty object return object_list else: // *tried to set exclude code here object_list = Company.objects.filter(Q(name__icontains=query)) return object_list None of exclude code helps. I believe I do simple mistake somewhere... because code suppose to work, but somehow still. I just also tried to get rid off if else statement and use exclude statements for queries such as '', ' ' and null and after that filter for query... And now excluding queries for ' ' also doesn't work... Django doesn't tell me the exclude doesn't work, all works, except, it is like not in the code. -
How to add description to the User Change Page in Django Admin
I'm working on Django and wanted to add a description under the heading at the red mark in the User change page as shown in the pic my admin.py file look like this: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) fieldsets = ( ('Personal Information', { 'classes': ('wide',), 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','password')}), ('Permissions', {'fields': ('is_superuser','is_staff', 'is_active','date_joined')}), ) So what should I do to get a description at the red mark in the user creation page?? Thanks in advance!! -
How do I go about creating two objects that are tied to each other by a foreign key in one form/view in django?
So, I have a messaging component of an app I am creating. There is a Conversation object, which has a ManyToMany field to user. Then, there is the actual InsantMessage object, which has a sender field to user, textfield and another field called receiver that is a foreign key to my conversation object. Now what I am attempting to do is to create a link underneath another user's profile, and then pass their pk in that link to my view which will check to first see if their already exists a conversation object with request.user and the other user, and if so, will create a message object and then automatically pass in the Convo object pk for the foreign key field conversation in my Message object. Now, I think I have the basic understanding of how to do this, perhaps just using an if statement and a nested form. But, where I'm stuck in is, how do I get the conversation pk to automatically pass? And how would if the conversation object is being created, how can I get request.user/other user to be automatically put in the conversation object? Even if you don't want to write out my code, just … -
django with angular on elastic beanstalk
I have been using Django and I am used to serving HTML pages using its templates. Using the same to host it on elastic beanstalk has been straight forward. Now if I have to use Django only for its admin and rest APIs while using angular as a frontend framework, what are changes to be made within Django to accommodate angular and how to deploy it on elastic beanstalk with ci/cd preferably through bitbucket. -
Add through field of user to serializer
I'm having the following models class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) display_name = models.Charfield() class Team(models.Model): display_name = models.Charfield() users = models.ManyToManyField(User, through='TeamUser') class TeamUser(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) role = models.IntegerField(_('role'), choices=[(g.id, g.name) for g in TeamRoles.all()], default=0) color = models.CharField(_('color'), max_length=10) class Meta: unique_together = ('team_id', 'user_id',) I want to add role and color to Serializers (using request.user) How can I make TeamSerializer for that? -
how to make shopping cart using django
I'm making a shopping cart with two class models, one user can order multiple products I used the many-to-many relationships. but I'm facing some issues like if two users has order same product then the last user's selected qty will show in both user's order. and many times it shows all orders in the user's cart by default. please tell the correct way to write these models. So each users cart can't affect others class OrderItem(models.Model): id = models.AutoField(primary_key=True) product = models.OneToOneField(Product, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) date_added = models.DateTimeField(auto_now=True) qty = models.IntegerField(default=1) def __str__(self): return self.product.Productname class Cart(models.Model): owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem, default=None, blank=True) -
Django test runner not running with non-standard project structure
I've got a Django project with a slightly non-standard structure (shown below) and the Django test runner isn't working. root_dir ├ src | ├ myapp_dir (apps.py, etc.) | ├ project_files_dir (settings.py, wsgi.py, etc.) | ├ utils_dir, etc. | └ manage.py ├ tests | ├ test_settings.py | └ myapp_tests_dir (tests1.py, tests2.py, etc.) ├ setup.py └ runtests.py apps.py contains: from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' settings.py includes INSTALLED_APPS = [..., myapp] test_settings.py includes INSTALLED_APPS = [..., myapp, tests] runtests.py contains: import os import sys import django from django.conf import settings from django.test.utils import get_runner if __name__ == "__main__": os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(["tests"]) sys.exit(bool(failures)) When I to run the tests with python runtests.py I get ModuleNotFoundError: No module named 'myapp' If try to change test_settings.py to include INSTALLED_APPS = [..., src.myapp, tests] I then get django.core.exceptions.ImproperlyConfigured: Cannot import 'myapp'. Check that 'src.myapp.apps.MyAppConfig.name' is correct. It's probably also worth mentioning that runserver runs fine from the working directory root_dir when calling it like this: > python src/manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 22, 2020 - 16:06:19 Django version 3.0.5, …