Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: two viewsets for one router
I want to have TWO DIFFERENT viewsets (for example, one implements only the GET method, the other implements only the POST method), but which will have the same url: GET /tournament/ - returns concrete object of the model Tournament; POST /tournament/ - create object of the model Tournament. But it is important that they must have the same url /tournament/! I trying something like this: models.py class Tournament(Model): ... viewsets.py class PublicTournamentEndpoint( mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet ): queryset = Tournament.objects.all() authentication_classes = [] # empty! class PrivateTournamentEndpoint( mixins.CreateModelMixin, viewsets.GenericViewSet ): queryset = Tournament.objects.all() authentication_classes = ['SomeAuthBackend'] # not empty! routers.py class TournamentRouter(SimpleRouter): routes = [ Route( url=r'^{prefix}/tournament/$', mapping={ 'get': 'retrieve', 'post': 'create', }, name='{basename}', detail=True, initkwargs={}, ), urls.py tournament_router = TournamentRouter() tournament_router.register( 'tournaments', PublicTournamentEndpoint, basename='tournaments', ) tournament_router.register( 'tournaments', PrivateTournamentEndpoint, basename='tournaments', ) urlpatterns += tournament_router.urls But my urlpatterns has next values: [ <URLPattern '^tournaments/tournament/$' [name='tournaments']>, <URLPattern '^tournaments/tournament/$' [name='tournaments']> ] and so when I send a POST /tournament/ request, I get the following error: 405 "Method \"POST\" not allowed." because the first match url does not have a POST method, but only GET. How can i resolve this problems? Thank you! -
How can I relate some, but not all, models to users using Django?
I have a project which includes two different apps: users and school. In my current implementation, the users app contains a custom user class derived from Djagno's AbstractUser. It defines allowed user types as student or teacher, and the user must select one during registration. The school app contains a classroom model which I need to relate to students and one or more teachers. I have two main problems here. The first is regarding how to relate the classroom model to only specific users restricting their access based on their user type. I have tried using a ManyToManyField relation in the classroom model in order to associate the instance with the user who created it (and then I would later allow the user to add students). It appears I don't understand this field correctly -- it actually all users to all classroom instances. This obviously does not meet my requirement to restrict access among different classroom instances. OneToOneField and ForeignKey do not seem to meet my needs either. I have tried adding those fields to my user, but then I am restricted to a single classroom per user which is not acceptable either. I have also played around with creating … -
How do I create a queryset to display products that are linked to a category, that is shown by each category slug?
I have a product model and a productcategory model. The products are linked to the productcategory by a category attribute. I want to create a query that displays ONLY products that are in a category, when the webpage is displayed for that specific category. The way I have my views currently setup, I get an attribute error, saying the view has no attribute of slug. Models: class ProductCategory(models.Model): title = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.PROTECT) class Product(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(ProductCategory, related_name='ProductsCategory', null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(blank=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) image = models.ImageField(upload_to='products/', null=True, blank=True) Views: class ProductListView(ListView): look_up = 'slug' template_name = 'products/products.html' def get_queryset(self, *args, **kwargs): category = ProductCategory.objects.get(self.slug) products = Product.filter(category=category) return products -
How to set a variable inside for loop inside template in Django2.1?
I have a context dictionary containing data to be passed into the template. I need to toggle two divs based on some flag variable which I have implemented using {% with %} Django template tag. However, when I try to set the variable using {% set %} syntax I am getting following error:- set', expected 'endwith'. Did you forget to register or load this tag? I following the solution given here but it gives me error. index.html {% with flag=1 %} {% for benefit in content.benefits %} <div style="background-color: #fff;" class="row mt-5"> {% if not flag %} <div class="col-lg-4 col-md-4 col-sm-12"> <img src="{% static "{{benefit.image}}" %}" alt="tablet" class="img-responsive mx-auto mt-5 w-100 h-75 h-md-50 working-img"> </div> {% endif %} <div class="col-lg-8 col-md-8 col-sm-12 h-100"> {% for desc in benefit.heading %} <div class="d-flex h-25 w-100 m-1 mt-4"> <div class="col-3 col-sm-2 h-100"> <div class="mx-auto"> <i class="fas fa-check fa-2x" style="color: #6fe33d"></i> </div> </div> <div class="col-9 col-sm-10"> <div class="d-flex flex-column"> <div class="working-caption font-weight-bold">{{ desc }}</div> {# <div class="py-2 working-description-courses text-muted">{{ description }}</div>#} </div> </div> </div> {% endfor %} </div> {% if flag %} <div class="col-lg-4 col-md-4 col-sm-12"> <img src="{% static "{{benefit.image}}" %}" alt="tablet" class="img-responsive mx-auto mt-5 w-100 h-75 h-md-50 working-img"> </div> {% endif %} </div> … -
How can run multiple celery tasks in parallel?
I have a two tasks. @app.task def run2(): while True: print(1) time.sleep(5) return HttpResponse('ok') @app.task def run3(): while True: print(2) time.sleep(2) return How can I run these two tasks at the same time from the same console, from one command (preferably with a different number of workers). -
Mutation not working with django graphene - AttributeError refers to non-existent attribute
I'm making project with Django and graphene-django. I have the following models: from django.db import models class Address(models.Model): class Meta: verbose_name_plural = "Addresses" number = models.CharField(max_length=4) street = models.CharField(max_length=100) city = models.CharField(max_length=100) postcode = models.CharField(max_length=7) class Person(models.Model): class Meta: verbose_name_plural = "Persons" avatar = models.ImageField(upload_to='images/avatars/') first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) address = models.ForeignKey(Address, on_delete=models.CASCADE) personal_image = models.ImageField(upload_to='images/personal_images/') def get_fullname(self): return self.first_name + ' ' + self.last_name My root schema is: import people.person.schema import graphene from graphene_django.debug import DjangoDebug class Query( people.person.schema.Query, graphene.ObjectType, ): debug = graphene.Field(DjangoDebug, name="_debug") class Mutations( people.person.schema.Mutations, graphene.ObjectType, ): debug = graphene.Field(DjangoDebug, name="_debug") schema = graphene.Schema(query=Query, mutation=Mutations) And my app schema is: import graphene from graphene_django.types import DjangoObjectType from .models import Person, Address class PersonType(DjangoObjectType): class Meta: model = Person class AddressType(DjangoObjectType): class Meta: model = Address class Query(object): person = graphene.Field(PersonType, id=graphene.Int(), first_name=graphene.String()) all_persons = graphene.List(PersonType) address = graphene.Field( AddressType, id=graphene.Int(), name=graphene.String() ) all_addresses = graphene.List(AddressType) def resolve_all_persons(self, context): return Person.objects.all() def resolve_all_addresses(self, context): # We can easily optimize query count in the resolve method return Address.objects.select_related("person").all() def resolve_person(self, context, id=None, firstName=None, lastName=None): if id is not None: return Person.objects.get(pk=id) if firstName is not None: return Person.objects.get(first_name=firstName) if lastName is not None: return Person.objects.get(first_name=firstName) return … -
Error: django.db.utils.OperationalError: FATAL: password authentication failed for user "mydatabaseuser"
This is the full error I am recieving: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/psycopg2/init.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "mydatabaseuser" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in init self.build_graph() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/Users/ayushigupta/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/utils.py", line … -
Default Manager "Objects" is not working for me
I'm very new in Python & Django and I'm following a tutorial but for some reason, a similar exercise I'm trying to do is not working for me. I'm creating a simple views.py and a simple class MissingBusiness. Trying to refer to the "objects" default manager for the model class is not recognized. I want to use MissingBusiness.objects.all() to get all records from the database. How to make objects to be recognized? This is my views.py from django.http import HttpResponse from django.shortcuts import render from .models import MissingBusiness def indexRoot (request): **BusinessList = MissingBusiness.objects.all()** return render(request,'index.html') This is my models.py from django.db import models class MissingBusiness(models.Model): businessName = models.CharField(max_length=255) category = models.IntegerField() Seems the default manager "objects" is not recognized for some reason. getting an error: AttributeErrorat /ManageMissingBusinesses/ 'function' object has no attribute 'objects' Request Method: GET Request URL: http://localhost:59564/ManageMissingBusinesses/ Django Version: 2.2.5 Exception Type: AttributeError Exception Value: 'function' object has no attribute 'objects' Exception Location: C:\Python\BankAccountUI\BankAccountUI\ManageMissingBusinesses\views.py in indexRoot, line 7 Python Executable: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\python.exe Python Version: 3.6.3 Python Path: ['C:\Python\BankAccountUI\BankAccountUI', 'C:\Python\BankAccountUI\BankAccountUI', 'C:\Program Files (x86)\Microsoft Visual ' 'Studio\Shared\Python36_64\python36.zip', 'C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\DLLs', 'C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib', 'C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64', 'C:\Program Files (x86)\Microsoft Visual … -
How to redirect user to a URL when he choce from dropdown Form Django?
i am working on a form that i integrated with facebook pixel, and i have a Dropdown nationality field with two choices (Khaleegy - not khaleegy) when user submitting a form redirect him to Thanks_page.html but i when the user choice (Khaleegy) he redirect to Thanks_page.html that have a facebook pixel code - and when he choice (not khaleegy) he redirect to another Thanks_page this is a Form models.py class User(models.Model): first_name = models.CharField(max_length=100) second_name = models.CharField(max_length=100) E_mail = models.EmailField(max_length=254) COUNTRY_CHOICES = [('saudi arabia +966','SAUDI ARABIA +966'), ('oman +968','OMAN +968'), ('kuwait +965','KWUAIT +965'), ('Qatar +948','QATAR +948')] country = models.CharField(max_length=250, choices=COUNTRY_CHOICES, null=True) phone = models.IntegerField(null=True) phone_code = models.IntegerField(null=True) birthday = models.IntegerField(null=True) NATIONALITY_CHOICES = [('not khaleegy','Khaleegy'), ('not khaleegy','Khaleegy')] nationality = models.CharField(max_length=250, choices=NATIONALITY_CHOICES, null=True) def __str__(self): return self.first_name forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'second_name', 'E_mail', 'country', 'phone', 'phone_code','birthday', 'nationality',) widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'الاسم الاول'}), 'second_name': forms.TextInput(attrs={'placeholder': 'الاسم الثاني'}), 'E_mail': forms.EmailInput(attrs={'placeholder': 'joe@schmoe.com'}), } views.py def form_page(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() return redirect('LandingPage:thank_you') else: form = UserForm() posts = Article.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'LandingPage/form_page.html', {'form': form, 'posts': posts}) # Thank you page. def thank_you(request): return render(request, 'LandingPage/thank_you_page.html', {}) url.py urlpatterns = [ … -
Django object related and manyTomany, prefetch_related?
I have three models: class Season(models.Model): name = models.CharField(max_length=512) class Clothes(models.Model): season = models.ForeignKey(Season, related_name='season_clothes', on_delete=models.CASCADE) name = models.CharField(max_length=512) class User(models.Model): name = models.CharField() clothes = models.ManyToManyField(Clothes) How How can I get User's all clothes with season in template, if I know for which User this request. Something like this: Winter - (It's a Season name) Сoat - (name of clothes) Scarf - (name of clothes) Boots - (name of clothes) Summer - (It's a Season name) Shorts - (name of clothes) Swimming trunks - (name of clothes) Sneakers - (name of clothes) -
How can I query fields of a one to many related object?
So if I have model Run and ExceutedTestResults class Run(TimeStampedModel): RUN_TYPE_CHOICES = ( (MANUAL_RUN, 'Manual'), (AUTOMATED_RUN, 'Automated'), ) run_type = models.CharField(max_length=1, choices=RUN_TYPE_CHOICES) class ExecutedTestResult(Duration): """Lists the results of every test case executed.""" run = models.ForeignKey(Run, on_delete=models.CASCADE, related_name='run_results') RESULT_TYPE_CHOICES = ( ('P', 'Passed'), ('F', 'Failed'), ('N', 'No Run'), ('B', 'Blocked'), ) result = models.CharField(max_length=1, choices=RESULT_TYPE_CHOICES) I want to create a queryset method in class RunQuerySet(QuerySet): which would return a queryset of runs that are all passed/no run within a single run I'm not sure how to do this on a one to many relationship. Suggestions? -
Django apps shared python api client
Let's say I have an external python client that I use as a data source. Let's call it api. It's a pretty standard API, so creating a session object is easy and allows you to connect to the data source. I have a few Django apps that will depend on this api, and I'd like to have as few handles to this api per site as possible (one per process I'm guessing). I was thinking of two approaches: Write a non Django slim wrapper around my API implementing the singleton pattern, with one session object per site. Use it in my Django apps. Write a Django app with a custom signal that sends the instance once connected. It's one of these the best approach, or is there a more ad hoc way? -
Django / Jinja2: How do I extend a variable name dynamically with the value of another variable (e.g. in a for-loop)?
In my django db model I have e.g. 5x ImageField, which I want to use for a carousel in the front end: slider_image_1 = models.ImageField(upload_to='images/', blank=True) slider_image_2 = models.ImageField(upload_to='images/', blank=True) slider_image_3 = models.ImageField(upload_to='images/', blank=True) slider_image_4 = models.ImageField(upload_to='images/', blank=True) slider_image_5 = models.ImageField(upload_to='images/', blank=True) Depending whether the images were uploaded or not, I want to display the images and I am looking for an approach similar to something like this: {% for FOO in range(5) %} {% if object.slider_image_|extend_name_with:FOO %} <img src="{{ object.slider_image_|extend_name_with:FOO.url }}"> {% endif %} {% endfor %} Is something similar possible? What are other good approaches for this problem? -
Django - Rest Framework foreignkey field to be a selectField in my react app
I`m trying to create my serializers for my React app but I met some problems. I will give you an exemple class City(models.Model): city_name = models.CharField(max_length=100) class Profile(models.Model): city = models.ForeignKey(City, on_delete=models.DO_NOTHING) .......more fields....... Right now I thinking how to do the serializer. In GET request things are simple but on POST or PUT request I need all data from City model in my React app to select an option. I thing to do two serializers and in React to have two axios but I`m trying to find another solution. Can anyone faced with this problem to help me? Sorry for my english -
How can run webdriver (selenium) using Celery in Django?
I need to run webdriver periodically (e.g. every minute). I chose crontab. But when I start celery -A proj beat -l info, I get only Sending due task task-number-one (app.tasks.run1) CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'app.tasks.run1', 'schedule': crontab(minute='*/1') }, tasks.py @app.task def run1(): print(333) driver = init_driver() parse2(driver) driver.quit() return HttpResponse('ok') -
seek() takes 2 positional arguments but 3 were given
I am uploading an image to memory then I want to save it to an imageField(). I use django-storages that uploads files from image/fileField() to AWS S3. I download the image to the memory: r = requests.get(url, headers=header) image = Image.open(BytesIO(r.content)) image_in_memory = InMemoryUploadedFile(image, None, "foo.png", 'image/png', image.size, None) image_in_memory_file = image_in_memory.file Some verifications: print(type(image_in_memory)) --- <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> When I save this: my_object.cover.save(name="foo.png", content=image_in_memory) Django generates this error: web_1 | link.cover.save(name="foo.png", content=image_in_memory) web_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/files.py", line 87, in save web_1 | self.name = self.storage.save(name, content, max_length=self.field.max_length) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/files/storage.py", line 52, in save web_1 | return self._save(name, content) web_1 | File "/usr/local/lib/python3.7/site-packages/storages/backends/s3boto3.py", line 491, in _save web_1 | self._save_content(obj, content, parameters=parameters) web_1 | File "/usr/local/lib/python3.7/site-packages/storages/backends/s3boto3.py", line 505, in _save_content web_1 | content.seek(0, os.SEEK_SET) web_1 | TypeError: seek() takes 2 positional arguments but 3 were given Do you see the problem? -
Fetch parent child relation with level from the same table [ django / python ]
Hi I'm new with django and python. # function for fecthing the child def get_childern(request, username): Q = list(Profile.objects.filter(sponsor_id__exact=username)) populate(request, Q, username) # Iterate the Queryset def populate(request, quesryset, username): if quesryset: messages.success(request, username+' has '+str(len(quesryset))+' child') messages.info(request, quesryset) for user in quesryset: get_childern(request, user.user_id) else: messages.warning(request, 'User '+username+' has no child') return False # calling all children get_childern(request, username) and I want to add the level, how to break it down further. Please help me, invest lots of time and mind. Thanks to all :) -
AttributeError: 'tuple' object has no attribute 'stripe_customer_id'
I am receiving the error below when attempting to submit a purchase using stripe api within django app. line 115, in post if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None: AttributeError: 'tuple' object has no attribute 'stripe_customer_id' [09/Oct/2019 19:18:26] "POST /api/checkout/ HTTP/1.1" 500 16291 Everything was working until i made alterations based on 22:33. This is line 115: if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None: customer = stripe.Customer.retrieve( userprofile.stripe_customer_id) customer.sources.create(source=token) Here is the full code where line 115 exists: from django_countries import countries from django.db.models import Q from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.http import Http404 from django.shortcuts import render, get_object_or_404 from django.utils import timezone from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView 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, Address, Payment, Coupon, Refund, UserProfile, Variation, ItemVariation from .serializers import AddressSerializer, ItemSerializer, OrderSerializer, ItemDetailSerializer import stripe stripe.api_key = settings.STRIPE_SECRET_KEY class UserIDView(APIView): def get(self, request, *args, **kwargs): return Response({'userID': request.user.id}, status=HTTP_200_OK) class ItemListView(ListAPIView): permission_classes = (AllowAny,) serializer_class = ItemSerializer queryset = Item.objects.all() class ItemDetailView(RetrieveAPIView): permission_classes = (AllowAny,) serializer_class = ItemDetailSerializer queryset = Item.objects.all() class AddToCartView(APIView): def post(self, request, *args, **kwargs): … -
FTP file upload immediately goes to "Failed transfers" with reason "Transferring"
I got a small 2,3kb Activate file for Django, which I need to manually transfer to my server with some fixed code. When I try to upload the file, it goes as the title says immediately to the "Failed transfers" tab. I have deactivated all virtual envs which could be using the file, and testing shows that I can't upload any files at all suddenly. Any ideas what this might be? First time I run into something like this without any errors. -
How to send editext data to firestore in timestamp format?
I'm new to android development and i face a problem in send data of editext to firestore database in format of timestamp . -
In Django, how do I enable users to join a group if the user knows the group password?
In Django I'd like to allow logged-in users to join a group if they enter the right PIN/password. Users should not be able to see what groups exist, instead the user enters a PIN and if that PIN matches the PIN for an existing group, then the user becomes a member of that group. Most of the answers I find are related to user authentication. class Group(models.Model): name = models.CharField(max_length=16) pin = models.IntegerField(unique=True) members = models.ManyToManyField(User, related_name='members', blank=True) Using the model above, I'd like any user who enters a pin that matches an existing pin to become a member of the corresponding group. I'm also open to other ways to structure this, if you can offer a recommendation. I'd like to avoid inviting users to join the group via email or other ways. -
Learning more advanced object oriented patterns in python
Hopefully this question will be useful to others that are looking into learning better practices in python and will serve as a future resource. What are some good resources to learn more advanced python object oriented programming. For example, understanding patterns such as used in the django source code: class FieldFile(File): def __init__(self, instance, field, name): super().__init__(None, name) self.instance = instance self.field = field self.storage = field.storage self._committed = True def __eq__(self, other): # Older code may be expecting FileField values to be simple strings. # By overriding the == operator, it can remain backwards compatibility. if hasattr(other, 'name'): return self.name == other.name return self.name == other def __hash__(self): return hash(self.name) # The standard File contains most of the necessary properties, but # FieldFiles can be instantiated without a name, so that needs to # be checked for here. def _require_file(self): if not self: raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) -
Manager isn't available; 'auth.User' has been swapped for 'users.User'
1 I have a problem with my code when I want signup error to appear Manager isn't available; 'auth.User' has been swapped for 'users.User' , I try a solution of other questions the same as Manager isn't available; 'auth.User' has been swapped for 'members.customer' but all of them asking to replace User = User = get_user_model() but I am not use any User in my code or I dont know where I used that.I'm new in django, python, js and etc so if my question is silly to forgive me. AttributeError at /accounts/signup/ Manager isn't available; 'auth.User' has been swapped for 'users.User' Setting.Py: AUTH_USER_MODEL = 'users.User' LOGOUT_REDIRECT_URL = '/' LOGIN_REDIRECT_URL = '/' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'users.backends.EmailBackend', ) **# Application definition** INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'avatar', 'homepage', 'products',`enter code here` #user part 'users', ] user/models.py: from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth import get_user_model # Create your models here. class User(AbstractUser): nickname = models.CharField(max_length = 50, blank = True) class Meta(AbstractUser.Meta): pass accounts/models.py: from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User #from django_countries.fields import CountryField from django.conf import settings User= … -
NameError: name 'Profile' is not defined
i am trying to update a profile in profile page and create a form. i import form and use ModelForm but my model is not accepting profile data. and it is showing name error. i can not find suitable answer for this problem. -
he SECRET_KEY setting must not be empty - Even when SECRET_KEY is set in settings.py
I keep getting this error when i try to import my models.py file into views.py or any of the other python script in my App directory, i have the SECRET_KEY in settings.py, i have my app in the list of installed_APPS, wsgi.py contains os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings') - i replaced my project name manage.py also contains os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings') this is all i saw was wrong with other people's installations in all the other stackoverflow posts. My code works but importing models just breaks it i use this command to import my class from app_name.models import suscribers and subscribers is defined thus class subscribers(models.Model): name = models.CharField('Name', max_length=120) email = models.CharField('Email', max_length=120) access_token = models.TextField() expires_in = models.DateTimeField('token expiry date') i have already executed makemigrations and migrate commands but being a newbie i don't know where else to look. Please save a soul its been 3 days thanks.