Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and waypoints Infinite scroll not working
I have tried all the answers on stack and the infinite scroll is still not working. My home.html is still displaying the pagination. I suspect the problem is with jquery or the js files or with how the static file is loaded? Here is my home.html: {% block content %} {% load static %} <div class="infinite-container"> {% for post in posts %} <div class="infinite-item"> <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> </div> {% endfor %} </div> <div class="d-flex d-none position-fixed" style="top:35vh;left:46vw"> <button class="btn btn-primary loading"> <span class="spinner-border spinner-border-sm"></span> Please wait... </button> </div> <!--pagination logic --> <div class="col-12"> {% if page_obj.has_next %} <a class="infinite-more-link" href="?page={{ page_obj.next_page_number }}">next</a> {% endif %} </div> <script src="/static/js/jquery.waypoints.min.js"></script> <script src="/static/js/infinite.min.js"></script> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], offset: 'bottom-in-view', onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function () { $('.loading').hide(); } }); </script> {% endblock content %} In my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [Path(BASE_DIR, 'static'),] The directory of my js files. I have added the following … -
Django display each categories url on base.html
I am a beginner in Django and create video streaming apps, the functions are basically to add videos and display those on different pages by categories. I am struggling to obtain URL for each category to display limited videos on each page. I could display categories and the link in one page by using for loop. However, I want to have those URLs on the Nav bar on base.html. videos/models.py from tabnanny import verbose from unicodedata import category import uuid from django.contrib.auth import get_user_model from django.db import models from django.conf import settings class VideoCategory(models.Model): name = models.CharField(choices=settings.CATEGORIES, max_length=45) def __str__(self): return self.name class Meta: verbose_name = 'カテゴリー' verbose_name_plural = 'カテゴリー' # Create your models here. class VideoContent(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True, ) title = models.CharField('タイトル', max_length=50) comment = models.CharField('内容',max_length=500) url = models.URLField('URL', max_length=200) published_date = models.DateTimeField('投稿日', auto_now_add=True) category = models.ForeignKey( VideoCategory, verbose_name = 'カテゴリー', on_delete=models.PROTECT, null=True, blank=True ) def __str__(self): return self.title class Meta: verbose_name = '動画投稿' verbose_name_plural = '動画投稿' video/views.py from django.contrib.auth.mixins import LoginRequiredMixin from unicodedata import category from django.shortcuts import render, get_object_or_404 from .models import VideoCategory, VideoContent from django.urls import reverse_lazy, reverse from django.shortcuts import render from django.views.generic import ( ListView, CreateView, UpdateView, DeleteView, ) … -
Define an aggregated check constraint using Django ORM
Think of two models like below: class Storage(Model): capacity = IntegerField() ... class FillStorage(Model): storage = ForeignKey(Storage, ...) amount = IntegerField() ... I need to have a check constraint on FillStorage model, preventing Sum of amounts of a single storage exceed its capacity; or be less than 0. What is the best solution? -
python django project hosting error on pythonanywhere.com
2022-07-03 04:54:11,060: Error running WSGI application 2022-07-03 04:54:11,078: django.core.exceptions.ImproperlyConfigured: 'user.apps.AppConfig' must supply a name attribute. 2022-07-03 04:54:11,078: File "/var/www/atmadevrt99_pythonanywhere_com_wsgi.py", line 16, in 2022-07-03 04:54:11,078: application = get_wsgi_application() 2022-07-03 04:54:11,078: 2022-07-03 04:54:11,078: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2022-07-03 04:54:11,079: django.setup(set_prefix=False) 2022-07-03 04:54:11,079: 2022-07-03 04:54:11,079: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/init.py", line 24, in setup 2022-07-03 04:54:11,079: apps.populate(settings.INSTALLED_APPS) 2022-07-03 04:54:11,079: 2022-07-03 04:54:11,079: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate 2022-07-03 04:54:11,080: app_config = AppConfig.create(entry) 2022-07-03 04:54:11,080: 2022-07-03 04:54:11,080: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/config.py", line 239, in create 2022-07-03 04:54:11,080: "'%s' must supply a name attribute." % entry 2022-07-03 04:54:11,080: *************************************************** 2022-07-03 04:54:11,081: If you're seeing an import error and don't know why, 2022-07-03 04:54:11,081: we have a dedicated help page to help you debug: 2022-07-03 04:54:11,081: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2022-07-03 04:54:11,081: *************************************************** 2022-07-03 04:54:13,244: Error running WSGI application 2022-07-03 04:54:13,244: django.core.exceptions.ImproperlyConfigured: 'user.apps.AppConfig' must supply a name attribute. 2022-07-03 04:54:13,244: File "/var/www/atmadevrt99_pythonanywhere_com_wsgi.py", line 16, in 2022-07-03 04:54:13,245: application = get_wsgi_application() 2022-07-03 04:54:13,245: 2022-07-03 04:54:13,245: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2022-07-03 04:54:13,245: django.setup(set_prefix=False) 2022-07-03 04:54:13,245: 2022-07-03 04:54:13,245: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/init.py", line 24, in setup 2022-07-03 04:54:13,245: apps.populate(settings.INSTALLED_APPS) 2022-07-03 04:54:13,245: 2022-07-03 04:54:13,245: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate 2022-07-03 04:54:13,245: app_config = AppConfig.create(entry) 2022-07-03 04:54:13,246: 2022-07-03 04:54:13,246: File "/home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/config.py", line 239, in create 2022-07-03 … -
How to get only ID on URL bar in selenium python
I have code like this: if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): text = form['look'].value() chrome_options = Options() chrome_options.add_experimental_option( "excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option( 'useAutomationExtension', False) chrome_options.add_experimental_option("prefs", { "download.prompt_for_download": False, "safebrowsing.enabled": True }) driver = webdriver.Chrome( ChromeDriverManager().install(), options=chrome_options) driver.maximize_window() driver.get(text) ... Then I get a URL like this: https://lovepik.com/image-610179440/cartoon-mothers-day-vector-material.html But I want the returned result to only get the ID of 610179440, what should I do? -
Why AuthenticationForm() in Django is not being valid?
So I've been trying to create a function in Django for users to log into their accounts. But it is only working for super users. When I try to log in from other accounts, it keeps resetting the password and gives error message 'Please enter a correct username and password'. However, both username and password are correct. Data from request.POST is coming as a QuerySet (keys-'csrfmiddlewaretoken','username','password'). When I put request.POST into AuthenticationForm(), it is not going through 'if form.is_valid():' part. What should I do to make this work? Please, can someone help me? Thanks, in advance. Here is the code: form=AuthenticationForm() if request.method=="POST": form=AuthenticationForm(request, data=request.POST) if form.is_valid(): username=form.cleaned_data.get('username') password=form.cleaned_data.get('password') user=authenticate(username=username,password=password) if user is not None: login(request,user) messages.info(request,'You have successfully logged in!') return redirect('news') else: messages.error(request,'Invalid data!') else: messages.error(request,'Invalid data!') return render(request,'post/login.html',{'form':form})``` -
Why django drf_yasg generate more unecessary APIs documentation than expecected?
I create Swagger APIs of a GET request, but drf_yasg generates a POST and a GET request. Here is my settings.py INSTALLED_APPS = [ 'django.contrib....', ... 'drf_yasg', 'business' ] Here is my APIs #TODO: Get all #URL: ('/CartItem/get-all', methods=['GET']) class GetAll(generics.CreateAPIView): serializer_class = CartItemFilter @Logging def get(self, request): request_data = dict(zip(request.GET.keys(), request.GET.values())) serializer = self.serializer_class(data=request_data) serializer.is_valid(raise_exception=True) request_data["deleted_at__isnull"] = True cartItem = CartItem.objects.filter(**request_data).values() return Response.NewResponse(status.HTTP_200_OK, "Success", list(cartItem)) Here is the app url file path('cart-item/get-all', CartItem.GetAll.as_view(), name="Get all cart item"), Here is the url file in the root folder schema_view = get_schema_view( openapi.Info( title="6********", default_version='1.0', description="API *******" ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('admin/', admin.site.urls), path('documentation', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('', include('business.urls')), ] I dont see anythign wrong with my setup, but when I turn on my swagger I see this The cart-item/get-all path has an extra POST request. Making my swagger becomes very messy since there are many unnecessary APIs -
CORS not filtering anything out
I'm trying to see if CORS is working on my Django application. I call my own API from a JS static file in my project. After implementing CORS to not allow any requests to my API, I still am able to call the API successfully from my script. Shouldn't CORS reject my call since I'm not on the "ALLOWED_ORIGINS"? CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = [] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', .... ] INSTALLED_APPS = [ ... 'corsheaders', ] -
Uploading files in subdirectories in media directory in Django
I am using Django 3. I am trying to upload files to specific directories. location='media/dentist/diplomas/' and location='media/dentist/government_docs/' directories. But still files are directly uploaded to /media directory. But i want files to be uploaded into dentist directory under media directory. def create_account_dentist(request): if request.method == 'POST': #Upload Dentist Diploma and Government Document uploaded_file_url = "" uploaded_file_url2 = "" if request.FILES['customFileInput1']: myfile = request.FILES['customFileInput1'] fs = FileSystemStorage(location='media/dentist/diplomas/') filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) if request.FILES['customFileInput2']: myfile2 = request.FILES['customFileInput2'] fs2 = FileSystemStorage(location='media/dentist/government_docs/') filename2 = fs2.save(myfile2.name, myfile2) uploaded_file_url2 = fs.url(filename2) print(uploaded_file_url2) return redirect(reverse('dentist-section')) #Forward to Dentist Main Page return render(request, 'create-account-dentist.html') -
GraphQL Code Generator - Failed to load schema from http://localhost:8000/graphql - Request with GET/HEAD method cannot have body
I've built a GraphQL API using strawberry and strawberry-django-plus that is hosted on http://localhost:8000/graphql using Django. I am able to successfully interact with the API using GraphiQL on the localhost page. I'm now trying to access the API from my frontend using GraphQL Code Generator and React Query. When I run the command yarn graphql-codegen, the following error occurs: ✔ Parse configuration ❯ Generate outputs ❯ Generate src/generated/graphql.ts ✖ Load GraphQL schemas → Failed to load schema Load GraphQL documents Generate ❯ Generate ./graphql.schema.json ✖ Load GraphQL schemas → Failed to load schema Load GraphQL documents Generate Found 2 errors ✖ ./graphql.schema.json Failed to load schema from http://localhost:8000/graphql: Request with GET/HEAD method cannot have body. TypeError: Request with GET/HEAD method cannot have body. at new Request (mydir/.yarn/cache/undici-npm-5.6.0-b513316628-b9052c2cb9.zip/node_modules/ undici/lib/fetch/request.js:437:13) at Agent.fetch (mydir/.yarn/cache/undici-npm-5.6.0-b513316628-b9052c2cb9.zip/node_modules/ undici/lib/fetch/index.js:114:21) at fetch (mydir/.yarn/cache/undici-npm-5.6.0-b513316628-b9052c2cb9.zip/node_modules/undici /index.js:90:22) at fetch (mydir/.yarn/cache/cross-undici-fetch-npm-0.4.8-4bdc960eeb-7645fde142.zip/node_mo dules/cross-undici-fetch/dist/create-node-ponyfill.js:130:16) at fetch (mydir/.yarn/cache/cross-undici-fetch-npm-0.4.8-4bdc960eeb-7645fde142.zip/node_mo dules/cross-undici-fetch/dist/create-node-ponyfill.js:125:18) at defaultAsyncFetch (mydir/.yarn/__virtual__/@graphql-tools-url-loader-virtual-1d0d6b13ee /0/cache/@graphql-tools-url-loader-npm-7.12.0-ad4affabf8-6db87eec05.zip/node_modules/@graphql-tools/url-loader/cjs/defaultAsyncFetch.js:6:43) at mydir/.yarn/__virtual__/@graphql-tools-url-loader-virtual-1d0d6b13ee/0/cache/@graphql-t ools-url-loader-npm-7.12.0-ad4affabf8-6db87eec05.zip/node_modules/@graphql-tools/url-loader/cjs/index.js:212:36 at new ValueOrPromise (mydir/.yarn/cache/value-or-promise-npm-1.0.11-924f226d8c-13f8f2ef62 .zip/node_modules/value-or-promise/build/main/ValueOrPromise.js:14:21) at executor (mydir/.yarn/__virtual__/@graphql-tools-url-loader-virtual-1d0d6b13ee/0/cache/ @graphql-tools-url-loader-npm-7.12.0-ad4affabf8-6db87eec05.zip/node_modules/@graphql-tools/url-loader/cjs/index.js:186:20) at mydir/.yarn/__virtual__/@graphql-tools-url-loader-virtual-1d0d6b13ee/0/cache/@graphql-t ools-url-loader-npm-7.12.0-ad4affabf8-6db87eec05.zip/node_modules/@graphql-tools/url-loader/cjs/index.js:504:35 GraphQL Code Generator supports: - ES Modules and CommonJS exports (export as default or named export "schema") - Introspection JSON File - URL of GraphQL endpoint - Multiple files with type definitions (glob expression) - String in … -
Use Serializer Method Field in another Method field
In my serializer, I have a method field, that I would want to use in another method field. This will be best explained in code: class ExampleSerializer(serializers.ModelSerializer): data = serializers.CharField() analyzed_data = serializers.SerializerMethodField() analyzed_analyzed_data = serializers.SerializerMethodField() class Meta: model = DataProviderModel fields = "__all__" def get_analyzed_data(self, obj): pass def get_analyzed_analyzed_data(self): # use analyzed_data here pass So I want users to see the first step of data analysis and then analyze the same data further. Is that possible? Maybe that is something I shouldn't do? -
Why is CORS better than just checking request.headers['origin'] = 'example.com?
I'm using Django REST framework. Why is it better to use CORS framework instead of just checking that the request origin is from my own site? Why can't I just check in my view that request.headers['origin'] (exists) and request.headers['origin'] == 'example.com' as opposed to using the Django CORS framework? -
Display the README.md file content in my website
i want to display the content of the README.md file in GitHub from my repository on my website. I'm relatively new to programming so im a little bit lost. as far as i can tell: i need to input my repository URL which displays the readme.md file in the front page then access the markdown file's information and copy it (and possibly translate) into my HTML page im using Django if it makes any difference -
how to make React i18next accessing json file in django
I'm using React build folder inside Django. When React i18next uploads locales/en/translation.json from the build folder in Django I get an error as wsgiserver uploads the file as text/html instead of json. is there a way to call this file as json or make wsgiserver/django ignor upload it as json ? can i add function to this line in i18n.js to make sure it's fetched as json : backend: { loadPath: '/locales/{{lng}}/{{ns}}.json', }, i18n.js ; import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import Backend from 'i18next-http-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; // don't want to use this? // have a look at the Quick start guide // for passing in lng and translations on init const Languages = ['ar', 'en', 'fr'] i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) // passes i18n down to react-i18next .init({ lng: 'en', react: { useSuspense: true, }, // the translations // (tip move them in a JSON file and import them, // or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui) supported: ["en", "fr", "ar"], fallbackLng: "en", detection: { order: ['path', 'cookie', 'htmlTag', 'localStorage', 'subdomain'], caches: ['cookie'], }, debug: true, whitelist: Languages, interpolation: { escapeValue: false, // not needed for react as it escapes by default … -
Django: Change Queryset of already defined Prefetch object
Context I really want to, but I don't understand how I can limit an already existing Prefetch object Models class MyUser(AbstractUser): pass class Absence(Model): employee = ForeignKey(MyUser, related_name='absences', on_delete=PROTECT) start_date = DateField() end_date = DateField() View class UserAbsencesListAPIView(ListAPIView): queryset = MyUser.objects.order_by('first_name') serializer_class = serializers.UserWithAbsencesSerializer filterset_class = filters.UserAbsencesFilterSet Filter class UserAbsencesFilterSet(FilterSet): first_name = CharFilter(lookup_expr='icontains', field_name='first_name') from_ = DateFilter(method='filter_from', distinct=True) to = DateFilter(method='filter_to', distinct=True) What do I need With the Request there are two arguments from_ and to. I should return Users with their Absences, which (Absences) are bounded by from_ and/or to intervals. It's very simple for a single argument, i can limit the set using Prefetch object: def filter_from(self, queryset, name, value): return queryset.prefetch_related( Prefetch( 'absences', Absence.objects.filter(Q(start_date__gte=value) | Q(start_date__lte=value, end_date__gte=value)), ) ) Similarly for to. But what if I want to get a limit by two arguments at once? When the from_ attribute is requested - 'filter_from' method is executed; for the to argument, another method filter_to is executed. I can't use prefetch_related twice, I get an exception ValueError: 'absences' lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups.. I've tried using to_attr, but it looks like I can't access it … -
Model Relationship django
I'd appreciate your help. I have two models. In the Bids model you will find current_bid_cmp. I would like from the ListingAuctions model to be able to access the corresponding current_bid_cmp of the Bids model. I only have found information to do querys from the model which contains the foreingKey. My view: I use get_context_data because I have been trying anothers querys. perhaps its not the more aproppiate class index(ListView): model = ListingAuctions template_name = "auctions/index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['object'] = ListingAuctions.objects.all() return context My Models: class ListingAuctions(BaseModel): title_auction = models.CharField('Title of the auction',max_length = 150, unique = True) description = models.TextField('Description') user = models.ForeignKey(User, on_delete = models.CASCADE) category = models.ForeignKey(Category, on_delete = models.CASCADE) initial_bid = models.FloatField(default=False) content = models.TextField('Content of auction') image = models.ImageField('Referential Image', null=True, upload_to = 'images_auctions', max_length = 255, default= 'noimage.png') class Bids(BaseModel): user = models.ForeignKey(User, on_delete = models.CASCADE, related_name='offer_user') listing_auctions = models.ForeignKey(ListingAuctions,null=True, on_delete= models.CASCADE, related_name='l_auctions') initialized_bid = models.BooleanField(default=False) current_bid_cmp = models.FloatField('Current Bid Cmp',blank=True, null=True ) offer = models.FloatField(default=0 ,null=True, blank=True) My HTML Current bid: $ {{post.l_auctions.current_bid_cmp}} its my attemp l_auctions is the relate name from listing_auctions in Bids model. Post is a ListingAuction object: {% for post in object_list %} <div class=" … -
I am trying to python manage.py runserver but keep getting the Django ModuleNotFoundError: No module named 'website.settings'
This is the first time that I use django for my website. I have been 5 hours trying to figure out the django and still haven't gotten to the HTML. I have had this same error (no module named 'website.settings' for the past 3 hours. I have been trying everything and looked it up various times but don't know what to do. Any help? here I append my whole github repository. You should be able to download it. Thanks -
I want to learn Full stack development what to do? [closed]
I want to be a full-stack web developer, I have learned HTML, a little bit of CSS, and currently learning Django. Should I learn React and javascript to get handy with the front end? Will I be able to get jobs on the internet or companies? -
Django static tag on css(style-bg-image)
so I am trying to make a webpage in django everything works well -> {% static 'website/img/core-img/s1.png' %} but when I try to do static style="background-image: url({% static 'website/img/bg-img/1.jpg'%}); it gives me those stupid errors althougt it seems to be fine according to my googling skills... so please help me static tag -
Getting Subtitles from ccextractor binary
How can I get subtitles of a video using ccextractor binary in our Django project? -
Django deploy to heroku: fatal: could not read Username for 'https://github.com': No such device or address
I am deploying a Django website to Heroku. The website project uses several standalone Django apps, which are in private Github repositories. This is what my requirements.txt file looks like for my website project: requirements.txt asgiref==3.5.0 Babel==2.9.1 certifi==2021.10.8 charset-normalizer==2.0.12 coverage==6.4.1 dj-database-url==0.5.0 Django==3.2 django-appconf==1.0.5 django-crispy-forms==1.14.0 django-js-asset==2.0.0 gunicorn==20.1.0 idna==3.3 psycopg2-binary==2.9.3 python-decouple==3.6 pytz==2022.1 requests==2.27.1 six==1.16.0 sqlparse==0.4.2 urllib3==1.26.9 webencodings==0.5.1 whitenoise==6.0.0 django-app1 @ git+https://github.com/MyUserName/django-app1.git@main django-app2 @ git+https://github.com/MyUserName/django-app2.git@main # #... truncated for brevity When I run git push heroku main this is the console output: remote: -----> Installing pip 22.1.2, setuptools 60.10.0 and wheel 0.37.1 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting django-app1@ git+https://github.com/MyUserName/django-app1.git@main remote: Cloning https://github.com/MyUserName/django-app1.git (to revision main) to /tmp/pip-install-l1stp7n7/django-app1_3d3e9f55670d48a6bf618c93771a0885 remote: Running command git clone --filter=blob:none --quiet https://github.com/MyUserName/django-app1.git /tmp/pip-install-l1stp7n7/django-app1_3d3e9f55670d48a6bf618c93771a0885 remote: fatal: could not read Username for 'https://github.com': No such device or address remote: error: subprocess-exited-with-error remote: I have configured GitHub integration in the Deploy tab of apps in the Heroku Dashboard - but I can't figure out how to add more than one app (i.e. repository). How do I resolve this error, so I can push to heroku? -
Django : Automatically add user to group with signals
I am currently try to add users automatically to a particular group using signals. It works when I edit the user fields but not when I add a group to it. @receiver(pre_save, sender=User) def addToPiloteGroup(sender, instance, *args, **kwargs): group = Group.objects.get(name='Pro') instance.groups.add(group) # => doesn't work instance.last_name = 'some name' # => works print('user has been group : ' + group.name) -
AttributeError: 'str' object has no attribute '_meta' when attempting to use Many to Many field on self with through model - Django
Django version - 4.0.4 I am making a recipe engine website and I am trying to create a table Ingredient where each ingredient may have substitutable ingredients. For example, ingredient "acorn squash" has the following substituable ingredients: ingredient title: butternut squash. Conversion: 1 cup acorn squash = 1 cup butternut squash ingredient title: pumpkin. Conversion: 1 cup acorn squash = 1 cup pumpkin To achieve this, I have a class Ingredient and a class SubstitutableIngredient in models.py. I use a many to many field in Ingredient which uses "through" to link to the SubstitutableIngredient table, as I have extra fields such as "conversion". I use 'self' as a substitutable ingredient is still an ingredient. When attempting to makemigrations or migrate, I get the following error: AttributeError: 'str' object has no attribute '_meta' when attempting to makemigrations or migrate. Stack trace shown further below. My code in Models.py is: from django.db import models # Create your models here. class Ingredient(models.Model): title = models.CharField(max_length=200, unique=True) # unique field. There may only be one ingredient in the database with the same title. # many to many field substitutableIngredients = models.ManyToManyField( 'self', through='SubstitutableIngredient', through_fields=('originalIngredient', 'newIngredient'), ) def __str__(self): return self.title class SubstitutableIngredient: originalIngredient = … -
Altering model after field validation
I'm implementing a tagging system. Currently, the models look like this: class Tag(models.Model): label = models.CharField(max_length=MAX_TAG_LENGTH) class TagManager(models.Model): tags = models.ManyToManyField(Tag, related_name="referrers") def associate_tag(self, tag_label: str): . . . And I have a custom field that cuts its input on commas so the user can enter tags as a comma-separated list: class TagsField(forms.CharField): def to_python(self, value): if not value: return [] return [tag.strip() for tag in value.split(',')] Finally, I have the model and form where these are used: class Thing(models.Model): tags = models.OneToOneField(TagManager, on_delete=models.SET_NULL, null=True) class ThingForm(forms.ModelForm): tags = TagsField(widget=forms.TextInput(attrs={"placeholder": "Tags", "required": False})) class Meta: model = Thing fields = ["tags"] Problem My issue is that if I populate and validate the form: form = ThingForm(data={"tags": ["One", "Two"]}) form.is_valid() I get errors: {'tags': ["“["One", "Two"]” value must be an integer."]} Which I'm guessing is because it's trying to place the stringified list in the OneToOneField, which isn't going to work. What I really need to do is after validating the field, I need to iterate the results of to_python, and call thing_instance.tags.associate_tag on each of the validated tag strings. Is there a "hook" method on forms that will allow me to do this cleanly? I've read over the docs and … -
Error with CMD ["gunicorn", "foodgram.wsgi:application", "--bind,", "0:8000"] comand
I'm using docker-compose to run containers. backend container keeps restarting with error: standard_init_linux.go:228: exec user process caused: exec format error dockerfile: FROM python:3.8-slim WORKDIR /app COPY requirements.txt . RUN pip install --upgrade pip RUN pip install -r requirements.txt --no-cache-dir COPY . /app CMD ["gunicorn", "foodgram.wsgi:application", "--bind,", "0:8000"] i have tryed CMD ["gunicorn", "foodgram.wsgi:application", "--bind,", "0:8000"], CMD gunicorn foodgram.wsgi:application --bind 0:8000 same error docker-compose.yml version: '3.3' volumes: postgres_data: static: media: static_value: media_value: frontend_data: services: db: image: postgres:12.4 volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ../backend/.env backend: image: mastermind777nest/foodgram:latest restart: always volumes: - static_value:/app/static/ - media_value:/app/media/ depends_on: - db env_file: - ../backend/.env frontend: build: context: ../frontend dockerfile: Dockerfile volumes: - ../frontend/:/app/result_build/ nginx: image: nginx:1.19.3 ports: - "10080:80" - "10443:443" volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf - ../frontend/build:/usr/share/nginx/html/ - ../docs/:/usr/share/nginx/html/api/docs/ - static:/app/static/ - media:/app/media/ - static_value:/var/html/static/ - media_value:/var/html/media/ restart: always depends_on: - backend - frontend