Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO: Is it possible to inherit a template consisting dynamically generated content in django?
I am trying to create a webpage which has two parts. An index list of all items (that persists throughout) Detail of the selected index item I created a LIST VIEW and a DETAIL VIEW for the same but the problem is both views cannot be called on the same template. I tried to list all the items in 'reports_list.html' and then inherit this template to 'report_detail.html' to see if the index list stays but it doesn't. Is there a way to accomplish this? -
How to change the button based on the user input?
I am implementing a pypi package called django-shopping-card https://pypi.org/project/django-shopping-cart/, so the users can see their saved posts. My issue is that I could not make the button to display "Remove Post" instead of "Add to Card", if the post was added already. I have tried to create a different method to pass the posts which have been saved, but that caused a an error, as I cannot access the key and values of the cart without for loop. I am new to this and I would highly appreciate any comments and suggestions. def add_fav(request, id): cart = Cart(request) post = Auction.objects.get(id=id) cart.add(product=post) return redirect("watchlist") def item_clear(request, id): cart = Cart(request) product = Auction.objects.get(id=id) cart.remove(product) return redirect("watchlist") def items_clear(request): cart = Cart(request) cart.clear() return redirect("watchlist") def get_cart(request): return render(request, 'auctions/watchlist.html', {'cart': Cart(request)}) listings.html {% block body %} {% for auction in object_list %} <div class="col-md-4"> <div class="card mb-2"> <div class="card-body"> <h5 class="card-title"><a href="{% url 'listing' auction.pk %}">{{ auction.name }}</a></h5> Price: {{ auction.price }}<br> <p class="card-text">{{ auction.description|slice:":10" }} ...</p> {{ auction.author }} Category: {{ auction.category }} <hr><img class="card-img-top" src="{{ auction.image.url }}" alt="no" ><br> {% for key,value in request.session.cart.items|slice:1 %} <br> {% if value.product_id == auction.id %} - <a href="{% url 'remove_fav' value.product_id%}">Delete</a> … -
Server error 500 on Django when deployed on Heroku when debug is set to False
Website is fine when debug is true, but when set to false it gives me a server error 500 evertime on every page. When i go into heroku logs --tail it tells me there is a status 500 issue. I have set up my allowed host so that is not an issue. Does anyone have any suggestions on what the root of the issue could be? Would appreciate any advice, thanks. -
Query database in Django
My first problem is I want to get the inserted latest id in auth_user on Django but currently it showing the name of the row database. I use the example below. The result should be Id value not the name. Please help me obj = User.objects.latest('id') The second problem is I want to insert in auth_user_user_permission table like this. The problem is how to convert this into django format. lastestid = User.objects.latest('id') insert into auth_user_user_permission where user_id=latestid and permission_id =(Select auth_permission Where name="sample" ) -
Sticky horizontal scrollbar using table-responsive
I know similar questions have already been asked but all the answers I see target only regular css tables and not Bootstrap table-responsive. I have a huge table with lots of rows but in order to see all those rows, one has to scroll at the very bottom of the page, then use the scrollbar, and then get back to the row he/she is interested in. I was wondering how I could have the scrollbar sticked to the page at all times without the user having to scroll to the very bottom of the page. The table is imported from djangotables2 so it is hard for me to edit HTML. I tried something like this but it didn't work: .table-responsive{ overflow:scroll; position:absolute; } I would be very glad if someone can help me out. Thank you. -
Django-Allauth - Errors with custom User model and custom Signup form
I am trying to implement django-allauth with a custom user model, but I keep getting errors when a new user is registering. The following is my User model: # models.py class User(AbstractUser): name = models.CharField(_("Name of User"), blank=True, max_length=255) tier = models.CharField(_("Plan"), choices=TIER_CHOICES, default='FREE', max_length=5) dateOfBirth = models.DateField(_("Date of birth"), auto_now=False, auto_now_add=False) gender = models.CharField(_('Gender'), choices=GENDER_CHOICES, default='MASC', max_length=5) city = models.CharField(_("City"), max_length=100) The fields on the model are to be completed by the user on Signup. To do this I have written a Custom Signup Form class, as per these instructions, which indicated the need for a signup() method: # forms.py class CustomSignupForm(SignupForm): name = f.CharField(label=_("First Name"), required=True, widget=f.TextInput(attrs={'placeholder': _("First Name")}) ) dateOfBirth = f.DateField(label=_("Date of birth"), required=True, initial='1990-01-01', widget=f.DateInput() ) city = f.CharField(label=_("City"), required=True, widget=f.TextInput(attrs={'placeholder': _("City")}) ) gender = f.ChoiceField(label=_("Gender"), choices=GENDER_CHOICES, required=True ) def signup(self, request, user): user.name = self.cleaned_data['name'] user.dateOfBirth = self.cleaned_data['dateOfBirth'] user.city = self.cleaned_data['city'] user.gender = self.cleaned_data['gender'] user.save() return user The same instructions also informed me I needed a custom allauth adapter (which is the basic allauth one but with the added fields such as dateOfBirth and city): # adapter.py class AccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=False): data = form.cleaned_data user.email = data['email'] user.name = data['name'] … -
Django - How to generate a document with text based on an image?
In my Django project, we are required to print a document that our client has, it's a form they use on a regular basis. What they currently do, is they have the form as an image, and with "autoforms" (I imagine in Word Office) they put the text over the image to fill the information of the form. We're trying to see if they're willing to change the form, since it's a bit unique and hard to replicate using HTML, so that's our plan A. But still, if they don't agree, I'd like to know if someone knows a way to add text over an image and print the result, in Django. We have the information to fill the form, but the form they have is an image, and it would be very convenient if the form was printed filled out from our Django website, instead of having to do it manually through Word or some other mean. Any direction would be helpful, I haven't managed to find anything of the sort that we're looking for, only libraries to "make pretty" the text in other ways, but I guess what I need is something similar to some basic image editing, … -
Unable to get the value from select form in Django
I want to show the product's option of product_option model in template and return the selected value to model of OrderItem by form, How should I process it in forms.py? model.py class product_option(models.Model): option1 = models.CharField(max_length=200) option2 = models.CharField(max_length=200) .... class Product(models.Model): product_option = models.ForeignKey(product_option, on_delete=models.SET_NULL, blank=True, null=True) class OrderItem(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE) item_option = models.CharField(null=True, max_length=200) forms.py class Item_create(forms.Form): ??????? class Meta: models = OrderItem fields = ('item_option', ) views.py def product_detail_with_form(request, slug): details = get_object_or_404(Product, slug=slug) form = Item_create(request.POST or None) if request.method == 'POST': if form.is_valid(): order_item, created = OrderItem.objects.get_or_create( item=details, user=request.user, ordered=False, item_option=form.clean_data.get('item_option') ) ..... html {% for detail in details %} <form method="post"> {% csrf_token %} {{ form.item_option }} <button type="submit">Add to cart</button> </form> {% endfor %} -
Highcharts and Django
I'm trying to use a Django chart with data from a PostgreSQL database on a Django site. I have a function that returns an array of information that I want charted out, but I can't figure out 1: How to get that data into the chart and 2: How to format the dates in an acceptable manner. I'm building a gantt chart to display relationships of "nodes" of a "state machine" I first attempted putting the for loop inside the data section of the chart, but it won't connect the dependencies, because that data might not exist when it iterates through the loop. I'm also having a difficult time getting it to understand the datetime that I'm passing it. Below is what I'm trying to do. {% load static %} {% load humanize %} <div id="container"></div> <script> var chart_data = [{% for node in nodes %}{ start: '{{node.added}}', end: '{{node.added}}', color: 'green', name: '{{node.node_name}}', dependency: '{{node.parent1}}', id: '{{node.id}}', node_parent_1: '{{node.parent1}}', node_parent_2: '{{node.parent2}}', script: '{{node.script}}', param: '{{node.parameter}}', node_status: '{{node.status}}', location: '{{node.location}}', active: '{{node.active}}', enabled: '{{node.enabled}}', trigger: '{{node.trigger}}', locked: '{{node.locked}}', api: '{{node.api_key}}', retry_amount: '{{node.retry_number}}', }, {% endfor %}] console.log(chart_data); Highcharts.ganttChart('container', { series: [{ name: 'Nodes', data: [chart_data] }], tooltip: { pointFormatter: function … -
Keep Redis data alive between docker-compose down and up in Docker container
Question is about keeping Redis data alive between docker-compose up and docker-compose down. In the docker-compose.yaml file bellow db service uses - postgres_data:/var/lib/postgresql/data/ volume to keep data alive. I would like to do something like this for redis service but I can not find workable solution to do so. Only one way I have managed to achieve this goal is to store data in local storage - ./storage/redis/data:/data. All experiments with external volume gave no results. Question is -is it possible somehow to store redis data between docker-compose down and docker-compose up in a volume likewise it made in DB service? Sorry if question is naive… Thanks version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 env_file: - ./series/.env volumes: - .:/code ports: - 8000:8000 depends_on: - db - redis db: build: context: . dockerfile: postgres.dockerfile restart: always env_file: - ./series/.env environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=1q2w3e volumes: - postgres_data:/var/lib/postgresql/data/ ports: - target: 5432 published: 5433 protocol: tcp mode: host redis: image: redis:alpine command: redis-server --appendonly yes ports: - target: 6379 published: 6380 protocol: tcp mode: host volumes: - ./storage/redis/data:/data restart: always environment: - REDIS_REPLICATION_MODE=master volumes: postgres_data: -
ManyRelatedManager' object has no attribute 'get_object_queryset'
I’m really new in python and a need your help please! I’m trying to display a list of “anomalie” objects only showing the elements that corresponds to the “User” according to the “Aisles” assigned to him (in a many-to-many relationship) So the model.py is as follows: class Aisle(models.Model): aisle_code = models.IntegerField(null=False, blank=False) aisle_name = models.CharField( max_length=60, null=False, blank=False) def __str__(self): return self.aisle_name def __nonzero__(self): return bool(self.aisle_name or self.aisle_name) class Account (AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField( verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) phone_regex = RegexValidator( regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField( validators=[phone_regex], max_length=17, blank=True) role = models.CharField(max_length=50) store = models.CharField(max_length=50) aisle = models.ManyToManyField(Aisle) user_identification = models.CharField(max_length=30, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'phone_number', 'role', 'store', 'aisle', 'user_identification'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True @property def staff(self): return self.is_staff @property def active(self): return self.is_active class Anomalie (models.Model): ANOMALIE = ( ("Etiquette absente", "Etiquette absente"), ("Etiquette decalee", "Etiquette … -
TypeError: Python UnitTests: __init__() takes from 1 to 2 positional arguments but 3 were given
I am using Django to create an interface to a project. I am trying to call this script through an action method from the django-admin. However, I am ending up with an error. What could be the possible error and solution? I know the code is messy with lot of comments, I've tried several workarounds. What I want to do is this: Pass the model instance to the unittest method, which uses the attributes of the instance to run it's tests. admin.py from io import StringIO from django.contrib import admin from .models import UploadTrackModel from .TestCases.UploadTest import Test_Upload import unittest import pytest import threading from threading import Thread # Register your models here. from selenium import webdriver def run_test(self, request, queryset): for item in queryset: stream = StringIO() suite = unittest.TestSuite() suite.addTest(Test_Upload('test_upload', item)) # runner = unittest.TextTestRunner(stream=stream) # result = runner.run(unittest.makeSuite(Test_Upload)) unittest.TextTestRunner(verbosity=2).run(suite) # result.testsRun # stream.seek(0) # print('Test output\n', stream.read()) class UploadTrackAdmin(admin.ModelAdmin): actions = [run_test] admin.site.register(UploadTrackModel,UploadTrackAdmin) Here is the class it is trying to call from ..PageObjects.Upload import Upload from ..PageObjects.HomePage import HomePage import unittest from selenium import webdriver from threading import Thread class Test_Upload(unittest.TestCase): baseURL = "<sampleURLhere>" driver = None # def __int__(self, upload_object, *args, **kwargs): # super(Test_Upload, self).__init__(self,*args, … -
OneToOneField cascade deletion problem on Django models
I have a model named Product and another model named Catalog, they're defined like this: class Product(StandardModelMixin, SoftDeletionModel): field1 = ... field2 = ... class Catalog(StandardModelMixin, SoftDeletionModel): product = models.OneToOneField( Product, on_delete=models.CASCADE, blank=False, null=False, related_name="catalog", verbose_name="Product", ) I believe, since this is a OneToOneField relationship, that every time i delete a Product model the Catalog related to it should be deleted too, in fact, in Django admin i receive the message saying that the deletion of the Product will delete the Catalog (cascade), but it doesn't delete in the end. And if i delete the Catalog, the Catalog id keeps on the Product related_name field and i can't add any other Catalog to it. I have other fields that have ForeignKeys and ManyToMany relations with Catalog and i'm starting to wonder if this has a relation with my problem or not. I've already looked at the docs, some other questions but none has the answers i'm looking for. -
django ModelForm not capturing uploaded images
Hi there I'm trying to create a form for a user on my site to be able to add a product, I made the form using ModelForm and I have managed to render it in my template but it's not functioning as required. On submitting the form I keep getting validation errors that images have not been submitted yet I did add them, any ideas Model from django.db import models class Product(models.Model): name = models.CharField(max_length=120) price = models.FloatField() image_182x182 = models.ImageField(upload_to='pdt_imgs/') image_1200x1200 = models.ImageField(upload_to='pdt_imgs/alt_imgs/') image_600x600 = models.ImageField(upload_to='pdt_imgs/alt_imgs/') image_600x600_2 = models.ImageField(upload_to='pdt_imgs/alt_imgs/') image_300x300 = models.ImageField(upload_to='pdt_imgs/alt_imgs/') img_array = [image_1200x1200, image_600x600, image_600x600_2] sku = models.IntegerField() available = models.BooleanField(default=True) discount = models.IntegerField(default = 0) category = models.ForeignKey(SubCategory, on_delete=models.CASCADE) seller = models.ForeignKey(Seller, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('pdt_detail', args=[str(self.id)]) def get_add_to_cart_url(self): return reverse('add-to-cart', args= [str(self.id)] ) Form from .models import Product from django.forms import ModelForm class ProductForm(ModelForm): class Meta: model = Product fields = [ 'name', 'price', 'image_182x182', 'image_1200x1200', 'image_600x600', 'image_600x600_2', 'image_300x300', 'sku', 'available', 'discount', 'category', 'seller' ] Views from django.utils.decorators import method_decorator from .decorators import seller_required from django.views.generic import CreateView from store.models import Product from store.forms import ProductForm from django.contrib import messages @method_decorator( seller_required , name='dispatch') class SellerProductAddView(CreateView): model = Product form_class … -
How to get value of <h1> and <p> tag(which changes dynamically time to time) from html to Django in views.py and print in def
I want data to be print which is nothing but the value of tag which is restName from HTML. When I click the submit button value of the h1 tag is printed in python -
Django insert data to manytomanyfield
I am trying to insert data using post requests And i have some data with array as they have ManyToManyField But i am getting below error while inserting the data. _setattr(self, prop, kwargs[prop]) File "/Users/soubhagyapradhan/Desktop/upwork/eligibility-checkr/backend/eligibility_env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 536, in __set__ raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead. model: class Policy(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, verbose_name=_('id')) hmo = models.ForeignKey(to=HMO, on_delete=models.CASCADE, verbose_name=_('hmo')) name = models.CharField(max_length=250, verbose_name=_('name')) number = models.CharField(max_length=250, verbose_name=_('number'), unique=True) organization = models.ForeignKey(to=Organization, on_delete=models.CASCADE, verbose_name=_('organization')) groups = models.ManyToManyField(to=Group, verbose_name=_('groups')) enrollee = models.ManyToManyField(to=Enrollee, verbose_name=_('enrollee')) start_date = models.DateField() end_date = models.DateField() commencement_date = models.DateField(null=True, blank=True) view: def create(self, request): data = request.data hmo = data.get("hmo") name = data.get("name") number = data.get("number") organization = data.get("organization") groups = data.get("groups") enrollee = data.get("enrollee") start_date = data.get("start_date") end_date = data.get("end_date") obj = models.Policy.objects.create( hmo_id=UUID(hmo), name=name, number=number, organization_id=UUID(organization), groups=groups, enrollee=enrollee, start_date=start_date, end_date=end_date ) data in body i am sending in post method: { "hmo" : "600d10ec-d5b8-449e-a521-dd986408ca98", "name" : "soubhagya", "number": "9853092550", "organization": "ab9f7b1d-51f3-460f-ba99-2b38d9c12682", "groups": ["340ba243-c692-4a09-b819-af1cf3986625"], "enrollee":["600d10ec-d5b8-449e-a521-dd986408ca98"], "start_date": "2020-10-10T00:00:00", "end_date": "2020-10-10T00:00:00" } -
Want to save the chat using websockets
I have created an small chatting app using websocket,channels..it works well..now i want to save the chat so that other user can read it later, if he/she is offline at that time.is that possible in django? -
Django REST framework serializer return format as list instead of JSON
Hello i am trying to develop a simple REST API endpoint using Django rest framework.I tried checking similar questions but did not work.I want my output as: { { "id": 1, "status": "ONLINE" }, { "id": 2, "status": "OFFLINE" } } but my output is: [ { "id": 1, "status": "ONLINE" }, { "id": 2, "status": "OFFLINE" } ] My models.py: class Device(models.Model): status = models.CharField(max_length=10, default="OFFLINE") my serializer.py: class DeviceSerializer(serializers.ModelSerializer): class Meta: model = Device fields = '__all__' and my views.py: def device_list(request): devices = Device.objects.all() serializer = DeviceSerializer(devices, many=True) return Response(serializer.data) -
Access attributes of subclassed User in Django
This seems really simple and I'm probably missing something, but I'm struggling with the following model structure: from django.contrib.auth.models import AbstractUser class User(AbstractUser): @property def is_author(self): return False @property def is_editor(self): return False class Author(User): @property def is_author(self): return True class Editor(Author): @property def is_editor(self): return True Basically I want to have a generic user class and then a subclass called Author and a subclass of that called Editor, each with slightly different properties. This seems to work at the database level, but when I get a User in the context of the app that is also an Author or Editor, I can't get access to the Author or Editor class methods/properties. I tried playing with __init__ to no real effect; have I structured this wrong? How do I call is_author on an Author that's also a User and get True back? -
pagination does not work in Django template page
I was trying to include pagination in template page. but the template syntax error was encountered when executing the project. it says : Could not parse the remainder: '==i' from 'posts.number==i' I am very frustrated about this. views.py def posts(request): posts = Post.objects.filter(active=True) myFilter = PostFilter(request.GET, queryset=posts) posts = myFilter.qs page = request.GET.get('page') paginator = Paginator(posts, 3) try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context = {'posts': posts, 'myFilter': myFilter} return render(request, 'base/posts.html', context) posts.html <div class="row"> {%if posts.has_other_pages%} <ul class="pagination"> {%for i in posts.paginator.page_range%} {%if posts.number==i%} <li class="page-item"><a class="active page-link">{{i}}</a></li> {%else%} <li class="page-item"><a href="?page={{i}}" class="page-link">{{i}}</a></li> {%endif%} {%endfor%} </ul> {%endif%} </div> -
Error when trying to migrate postgresql database Django/Gunicorn/Nginx/Docker
I try to "dockerize" a Django project. I've build my images and access my application via localhost:8002 Now I need to migrate postgresql database but it failed (cf traceback below) when I run the command docker exec -it my_djangoapp_id python manage.py migrate It seems to be a problem of port I am lost with port in my configuration but I configure port 5436 for postgresql docker-compose.yml version: '3.7' services: coverage-africa: restart: always build: context: ./coverage-africa dockerfile: Dockerfile.prod command: gunicorn coverage.wsgi:application --bind 0.0.0.0:8002 volumes: - coverage-africa_static_volume:/home/apps/coverage-africa/static - coverage-africa_media_volume:/home/apps/coverage-africa/mediafiles expose: - 8002 env_file: - ./config/coverage-africa/.env depends_on: - coverage-africa_db coverage-africa_db: restart: always image: postgres:12.0-alpine expose: - 5432 ports: - "5436:5432" volumes: - coverage-africa_postgres_data:/var/lib/postgresql/data/ env_file: - ./config/coverage-africa/.env nginx: build: ./nginx volumes: - coverage-africa_static_volume:/home/apps/coverage-africa/static - coverage-africa_media_volume:/home/apps/coverage-africa/mediafiles ports: - 8002:82 depends_on: - coverage-africa volumes: coverage-africa_postgres_data: coverage-africa_static_volume: coverage-africa_media_volume: ``` ``` Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect … -
Django: delete a Foreign Key object when empty
I am writing a dictionary app using Django where Expressions have Definitions. When an Expression is deleted, all its Definitions are deleted also (achieved through on_delete=CASCADE in foreign key field). My problem is that when the last Definition of an Expression is deleted, that Expression remains in my database without Definitions. I would like that when you delete the last Definition of an Expression the Expression gets deleted as well. How can I enforce this in my models? Here is my code right now: class Expression(models.Model): expression = models.CharField() class Definition(models.Model): definition = models.CharField() expression = models.ForeignKey(Expression, on_delete=models.CASCADE) -
Django - ForeignKey value same as object from different model
I have two models. One of them have a ForeignKey which should be related to an object in a different model: class Game(models.Model): gameday = models.CharField(max_length=120) hometeam1 = models.ForeignKey(Teams, on_delete=models.CASCADE, related_name="hometeam1", blank=True, null=True) class Tipp(models.Model): hometeam1 = models.ForeignKey(Game, on_delete=models.CASCADE, default=Game.hometeam1) week = models.CharField(max_length=120, null=True, blank=True) The hometeam1 object in the model Tipp should be the same as Game.hometeam1 and Game.hometeam1 gets his value manually. How can I assign that Tipp.hometeam1 has everytime the same value as Game.hometeam1? -
How to have two tag fields i.e. two Taggable Managers in the same model?
I have a model for uploaded files and I now need to have two tag fields in that model. One for user tags and one for admin tags. I've tried several solutions but neither worked. Here is my code now and it doesn't work. Not sure if this is to create two separate tables, one for user tags and for admin tags so any help would be appreciated. Also, if you could maybe explain to me what I'm doing because I'm lost. class UserTags(CommonGenericTaggedItemBase, TaggedItemBase): object_id = models.CharField(max_length=50, db_index=True) objects = models.Manager() class BaseTag(TagBase): pass class AdminTags(CommonGenericTaggedItemBase, TaggableManager): object_id = models.CharField(max_length=50, db_index=True) tag = models.ForeignKey(BaseTag, on_delete=models.CASCADE) objects = models.Manager() # Model for all uploaded files class Uploaded(models.Model): objects: models.Manager() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users") time_uploaded = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=50) file = models.FileField(upload_to=MEDIA_ROOT) tag = TaggableManager(blank=True, through=UserTags, related_name='user_tags') tags = TaggableManager(blank=True, through=AdminTags, related_name='admin_tags') additional_description = models.CharField(max_length=50, blank=True) def __str__(self): return f"{self.name} {self.file}" -
Django: Module not found error , on importing a model
I am fairly new to Django, in my project I have created 2 apps, web, and dashboard while trying to import my model from the web to model in the app dashboard using '''from myproject.web import models''' I am getting the following error ModuleNotFoundError: No module named 'myproject.web'. Thanks in advance