Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want add culumn for django custom user
register is using django custom user modelpython manage.py makemigrations register # register.models from django.db import models from django.core.mail import send_mail from django.contrib.auth.models import PermissionsMixin, UserManager from django.contrib.auth.base_user import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ from django.utils import timezone class CustomUserManager(UserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be 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_staff', False) 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_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) # /_/_/ I added a column, type of image /_/_/ image = models.ImageField(upload_to='images', null=True, blank=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) objects = … -
How do I keep reference in Django, when editing existing object?
So I have a field in my model which references another model. Like below. (simplified) class Contents(models.Model): objects = models.Manager() body = models.CharField(max_length=10000, blank=True) image = models.ImageField(null=True, blank=True, upload_to='imgs') created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now_add=False) class SavedContents(models.Model): objects = models.Manager() ref_content = models.ForeignKey(Contents, on_delete=models.CASCADE, related_name='refcontent', null=True) The problem is, the Foreign Key relationship, where the Saved Contents references Contents, is broken when making changes to an existing Content object. Below is my views.py def update_content(request, content_id): content_to_update = Contents.objects.get(id = content_id) content_form = ContentsForm(request.POST, request.FILES) if request.method == 'POST': if ans_form.is_valid(): instance = content_form.save(commit=False) instance.updated_at = str(today) content_to_update.delete() instance.save() return redirect('/') I know it's quite obvious that the referencing relationship is removed, since the original one is deleted. Is there any way that I can keep the foreign key relationship between that specific Content object and Saved Content object, no matter how many times a user makes changes to the content? Thanks in advance. -
Invalid Syntax Django Python
There is an error on VS code. I don't see it. Maybe somebody can help me path('', TaskList.as_view(), name ='tasks'), ^ invalid syntax -
Using Django REST framework for real-time chat?
I'm trying create a real-time chat app with Django and Vuejs. I would like to use django-rest-framework for this but I don't know how to make it real-time. I have used django-channels before but I'm curious if I can use only django-rest-framework as an alternative or maybe integrated it with django-channels. -
Django Models filter only last records
I m developing a CRM using Django , my goal is to get a list of only last records of a model, my models like below class Rapport(models.Model): added=models.DateField(default=timezone.now,blank=True,db_index=True) user=models.ForeignKey(User,on_delete=models.CASCADE) image=models.ImageField(upload_to=upload_location) image2=models.ImageField(blank=True,null=True,upload_to=upload_location2) can_update=models.BooleanField(default=False) note=models.PositiveIntegerField(default=0,db_index=True) observation=models.TextField(blank=True,null=True) class Visite(models.Model): rapport=models.ForeignKey(Rapport,on_delete=models.CASCADE) observation=models.TextField() medecin=models.ForeignKey(Medecin,on_delete=models.CASCADE) produits=models.ManyToManyField(Produit,through='produits.ProduitVisite') priority=models.PositiveIntegerField(default=0,db_index=True) class Medecin(models.Model): nom=models.CharField(max_length=255,db_index=True) telephone=models.CharField(max_length=10) email=models.EmailField(blank=True,null=True) commune=models.ForeignKey(Commune,on_delete=models.CASCADE) adresse=models.CharField(max_length=255) flag=models.BooleanField(default=False) updatable=models.BooleanField(default=True) contact=models.CharField(max_length=255,blank=True,null=True) users=models.ManyToManyField(User) I want to get only the last Visite object of each Medecin . -
Is there way to add multiple items in Stripe checkout?
Hello i struggle I would like to have in Stripe checkout multiple items but I have no idea how. If there is no way to do it I will not change anything and just charge people from cart.total. views.py try: cart = Cart.objects.get(order_user=request.user) checkout_session = stripe.checkout.Session.create( payment_method_types=['card', 'p24'], line_items=[{ 'price_data': { 'currency': 'eur', 'product_data': { 'name': "Total" }, 'unit_amount': cart.total, }, 'quantity': 1, }], mode='payment', success_url = request.build_absolute_uri(reverse('success-page'))+ '?session_id={CHECKOUT_SESSION_ID}', cancel_url = request.build_absolute_uri(reverse('cancel-page')), ) models.py class Item(Visits, models.Model): title = models.CharField(max_length=150) price = models.IntegerField(default=1000) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) class OrderItem(models.Model): order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Cart(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) order_items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) total = models.IntegerField(default=1000) -
Django - Testing Login View - AttributeError: 'HttpRequest' object has no attribute 'user'
I'm trying to test Django Login View with TestCase but I'm getting the following error - ERROR: test_login_form (accounts.tests.LoginPageTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/farhan/Documents/_playground_new/django_playground/cbv-dfb/accounts/tests.py", line 53, in test_login_form logged_in = self.client.force_login(new_user) File "/home/farhan/Documents/_playground_new/django_playground/cbv-dfb/venv/lib/python3.8/site-packages/django/test/client.py", line 619, in force_login self._login(user, backend) File "/home/farhan/Documents/_playground_new/django_playground/cbv-dfb/venv/lib/python3.8/site-packages/django/test/client.py", line 631, in _login login(request, user, backend) File "/home/farhan/Documents/_playground_new/django_playground/cbv-dfb/venv/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 135, in login user_logged_in.send(sender=user.__class__, request=request, user=user) File "/home/farhan/Documents/_playground_new/django_playground/cbv-dfb/venv/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ File "/home/farhan/Documents/_playground_new/django_playground/cbv-dfb/venv/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/home/farhan/Documents/_playground_new/django_playground/cbv-dfb/accounts/views.py", line 29, in on_user_logged_out f"{request.user.username} successfully logged in!", AttributeError: 'HttpRequest' object has no attribute 'user' I have a user_logged_in signal that adds a message by Django messages framework upon logging in. Here is the code - @receiver(user_logged_in) def on_user_logged_in(sender, request, **kwargs): messages.add_message( request, messages.INFO, f"{request.user.username} successfully logged in!", ) And here is the code for the unit test - class LoginPageTests(TestCase): username = "newuser" email = "newuser@email.com" password = "averydeifficultpasswordtobreak" def test_login_page_status_code(self): response = self.client.get("/accounts/login/") self.assertEqual(response.status_code, 200) def test_view_url_by_name(self): response = self.client.get(reverse("login")) self.assertEqual(response.status_code, 200) def test_view_uses_correct_template(self): response = self.client.get(reverse("login")) self.assertTemplateUsed(response, "registration/login.html") def test_login_form(self): new_user = get_user_model().objects.create_user(self.username, self.email) new_user.set_password(self.password) new_user.save() logged_in = self.client.login(username=self.username, password=self.password) self.assertEqual(logged_in, True) If I just simply comment out the signal code, the test runs fine. How can … -
Annotating a Subquery with queryset filtering methods from another model through Many to Many fields
I'm not sure how to make this possible, but I'm hoping to understand the intended method to do the following: I have a simple model: class Author(models.Model): id = models.TextField(primary_key=True, default=uuid4) name = models.TextField() main_titles = models.ManyToManyField( "Book", through="BookMainAuthor", related_name="main_authors", ) objects = AuthorManager.from_queryset(AuthorQuerySet)() class Book(models.Model): id = models.TextField(primary_key=True, default=uuid4) title = models.TextField() genre = models.ForeignKey("Genre", on_delete=models.CASCADE) objects = BookManager.from_queryset(BookQuerySet)() class BookQuerySet(QuerySet): def by_genre_scifi(self) -> QuerySet: return self.filter(**self.LOOKUP_POPULAR_SCIFI) I'd like to add a new QuerySet method for AuthorQuerySet to annotate Author objects using the method from BookQuerySet above. I've tried the following, which is incorrect: class AuthorQuerySet(QuerySet): def annotate_with_total_titles_by_genres(self) -> QuerySet: main_titles_by_genre_sci_fi_query = Book.objects.filter(main_authors__in[OuterRef('pk')]).all() .by_genre_sci_fi() .annotate(cnt=Count('*')) .values('cnt')[:1] return self.annotate(sci_fi_titles_total = Subquery(main_titles_by_genre_sci_fi_query, output_field=IntegerField())) Intended usage: annotated_authors = Author.objects.filter(<some filter>).annotate_with_total_titles_by_genres() The method here is working, and returns a BookQuerySet filtered by the lookup: Book.objects.filter(main_authors__in['some_author_id']).all().by_genre_sci_fi() However when I try to annotate using the above, I get None for every entry. -
show post whose comment have more likes than the post
In django i want to show some posts on homepage with 1 or 2 comments. I want only those post to be shown whose comments have more likes than the post's likes. class Post: ... likes = models.ManyToManyField(User,...) ... class Comment: ... post = models.ForeignKey(Post,...) likes = models.ManyToManyField(User,...) ... -
How to fetch JSON data using last filter in Django html template?
I want to get JSON data using last filter in my html template, but only getting key and not value. When I use: # template.html {{ daily_data|last }} I get: {'date': '2021-09-03T00:00:00.000Z', 'marketCap': 2550604613800.0, 'enterpriseVal': 2638345613800.0, 'peRatio': 29.8568111455, 'pbRatio': 40.0575834365, 'trailingPEG1Y': 0.2940443522 When I use: #template.html {% for data in daily_data|last %} {{ data }} {% endfor %} I get: date marketCap enterpriseVal peRatio pbRatio trailingPEG1Y How do I get only the values of marketCap, peRatio and so on? -
SQLite backend does not support timezone-aware times even if USE_TZ = True
I am now developping a small django projects which needs to work with aware datetime.time objects. When the user registers, he has to fill a time input. This data is then transformed to an aware time object in my views.py file just like that: ... if form.cleaned_data['reviews_time']: form.cleaned_data['reviews_time'] = form.cleaned_data['reviews_time'].replace(tzinfo=get_current_timezone()) else: form.cleaned_data['reviews_time'] = time(hour=0,minute=0,tzinfo=get_current_timezone()) *save the created user account* ... The problem is that when I submitt the form, I get the following error : SQLite backend does not support timezone-aware times. Even if I have USE_TZ enabled. I would like to know why this error happens and how to fix it. If anyone could help me I would be very grateful (and feel free to ask for extra code/explanations)enter code here -
request django API using https doesn't work
When I want to request an API using https it doesn't work and I don't know why.. Example : `http://myIp:8888/getValue` --> it works `https://myIp:8888/getValue` --> it doesn't work There is my dockerfile : FROM python:3.7-buster ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ ENV PYTHONUNBUFFERED 1 ENV LANG C.UTF-8 ENV DEBIAN_FRONTEND=noninteractive ENV PORT=8888 RUN apt-get update && apt-get install -y --no-install-recommends \ tzdata \ python3-setuptools \ python3-pip \ python3-dev \ python3-venv \ git \ && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* EXPOSE 8888 CMD gunicorn Documents_management_back.wsgi:application --bind 0.0.0.0:$PORT And my docker-compose version: "3.9" services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" Someone understand why I can't request using https ? Thanks a lot ! -
How to load image in django server from react build folder?
I have developed a website using react as frontend and django as backend, i have completed the project and made npm run build and i have added the index.html into the django templates DIR and static files which are inside the build folder But logo, favicon.ico and some other images which is inside the public and build folder are not visible in django page which localhost:8000, these logo's are visible in react page which is in localhost:3000 Project Structure: Project |__backend |__settings.py |__urls.py |__base --app |__views.py |__models.py |__build -- reactjs npm run build |__assets - folder which has images |__static -- css and scss folder |__manifest.json |__favicon.ico |__index.html |__public |__src |__static -- django static folder settings.py STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ BASE_DIR / 'static', BASE_DIR / 'build/static', os.path.join(BASE_DIR, 'build/assets'), ] MEDIA_ROOT = 'static/images' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='index.html')) ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Errors in terminal: Not Found: /assets/img/icon-img/prev.png [04/Sep/2021 14:06:11] "GET /assets/img/icon-img/prev.png HTTP/1.1" 404 2833 Not Found: /assets/img/logo/logo.png [04/Sep/2021 14:06:05] "GET /assets/img/logo/logo.png HTTP/1.1" 404 2821 Not Found: /service-worker.js [04/Sep/2021 14:05:28] "GET /service-worker.js HTTP/1.1" 404 2800 Not Found: /manifest.json [04/Sep/2021 14:03:50] "GET /manifest.json HTTP/1.1" 404 2788 -
__init__() got an unexpected keyword argument 'required' on in Django unittesting
I got an assertion and a type Error while writing Django's unit test for my application, can anyone please check and help me solving this. Both invalid and valid tests are running fine, only thing differs is the output when form.is_invalid() is called. Error1: Traceback (most recent call last): File "D:\open-source\localflavourtest\test_np\tests.py", line 104, in test_NepalPostalCodeFieldTest self.assertFieldOutput(NepalDetailsTestForm, valid, invalid) File "C:\Users\Asus\Envs\test\lib\site-packages\django\test\testcases.py", line 753, in assertFieldOutput optional = fieldclass(*field_args, **{**field_kwargs, 'required': False}) TypeError: __init__() got an unexpected keyword argument 'required' Error 2 FAIL: test_NepalPostalCodeFieldTest (test_np.tests.NepalCodeTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\open-source\localflavourtest\test_np\tests.py", line 113, in test_NepalPostalCodeFieldTest self.assertEqual(form.errors['postal_code'], error_format) AssertionError: ['Ensure this value has at most 5 characters [51 chars]XXX'] != ['Enter a postal code in the format XXXXX'] This is my code I have marked, the line where I am getting these errors, class NepalPostalCodeValidator(RegexValidator): default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXX'), } def __init__(self,*args, **kwargs): super().__init__(re.compile(r'^\d{5}$'), *args,**kwargs) class PostalCodeFormField(RegexField): default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXX'), } def __init__(self,max_length = 5, **kwargs): super().__init__(r'^\d{5}$', max_length = max_length, **kwargs) class PostalCodeField(models.CharField): description = _("Postal Code") def __init__(self, *args, **kwargs): kwargs['max_length'] = 5 super().__init__(*args, **kwargs) self.validators.append(NepalPostalCodeValidator()) def formfield(self, **kwargs): defaults = {'form_class': PostalCodeFormField} … -
django-prometheus missing metrics after restart
I have django-prometheus installed in my app.it exports metrics for me but i have a problem: when server restarts it miss all the metrics and metrics are loosed.is any solution for this? -
TypeError at /register 'CustomUser' object is not subscriptable
I am trying to register a new user and getting this error. I tried other similar issues and solutions but not getting headway. full traceback Internal Server Error: /register Traceback (most recent call last): File "/home/sharhan/DEV/PYTHON/DEVELOPMENT/allauth-tutorial/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/sharhan/DEV/PYTHON/DEVELOPMENT/allauth-tutorial/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/sharhan/DEV/PYTHON/DEVELOPMENT/allauth-tutorial/authentication/views.py", line 38, in register_view CustomUser.objects.get(email__iexact=email)[0] TypeError: 'CustomUser' object is not subscriptable register_view in views.py def register_view(request): if request.user.is_authenticated: return redirect('home') else: form = CustomUserCreationForm() if request.method == 'POST': form = CustomUserCreationForm(request.POST or None) if form.is_valid(): form.save() user_name = form.cleaned_data['username'] messages.info(request, 'Account created for ' + user_name) return redirect('login') else: form = CustomUserCreationForm(request.POST) else: form = CustomUserCreationForm() return render(request, 'register.html', {'form': form}) models.py class CustomUser(AbstractUser): # add additional fields in here country = models.CharField(max_length=200, null=True, blank=True) age = models.IntegerField(default=False, null=True, blank=True) status = models.BooleanField(default=False, null=True, blank=True) def __str__(self): return self.email forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ['username', 'email', 'country', 'age', 'status', 'password1', 'password2'] The second is that I'm also trying to implement functionality which I don't know where to start. If a new user uses the same email again to register, it should throw an error. It should be unique and … -
Uploading a file via Angular (using FormData) to django-rest-framework
I have rummaged thru every possible StackOverflow question and blog post online, and I'm still facing issues. I'm trying to upload a file to a django-rest-framework endpoint using Angular 12. This is the frontend code: uploadCameraImage(id: CameraInterface["id"], image: File): Observable<CameraInterface> { const formData: FormData = new FormData(); formData.append("image", image); const httpOptions = { headers: new HttpHeaders({ "Content-Type": "multipart/form-data", "Content-Disposition": `attachment; filename=${image.name}` }) }; return this.http.put<CameraInterface>(`${this.configUrl}/camera/${id}/image/`, formData, httpOptions); } These are the relevang django-rest-framework parts: # This is the main base serializer used for other operations class EquipmentItemSerializer(serializers.Serializer): class Meta: fields = [ 'created_by', 'created', 'updated', 'brand', 'name', 'image', ] read_only_fields = ['image'] abstract = True # This is the base serializer only used for the image upload class EquipmentItemImageSerializer(serializers.Serializer): class Meta: fields = ['image'] abstract = True # This is the main serializer used for all other operations (create/delete...) class CameraSerializer(EquipmentItemSerializer, serializers.ModelSerializer): class Meta: model = Camera fields = '__all__' # This is the serializer used for the image upload in the @action below class CameraImageSerializer(EquipmentItemImageSerializer, serializers.ModelSerializer): class Meta: model = Camera fields = EquipmentItemImageSerializer.Meta.fields # This is the base view set class EquipmentItemViewSet(viewsets.ModelViewSet): renderer_classes = [BrowsableAPIRenderer, CamelCaseJSONRenderer] permission_classes = [IsEquipmentModeratorOrReadOnly] http_method_names = ['get', 'post', 'head', 'put', 'patch'] def get_queryset(self): … -
MailQueue in django!!can we set sender's name instead of the sender's email address in MailerMessage?
This is my code, Can we set sender's name instead of sender's email address using Mailqueue?Anyone help me! -
Django User matching query does not exist on foreign-key relation
I am trying to create a system in django by which user will login through phone number. Used AbstractBaseUser to use the number as user id. Now I am trying to create a foreign key relation of every transaction with the number. While I try to push a transaction it says "User matching query does not exist". I am getting where I made mistake. User model: class User(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField("Phone number", max_length=100, unique=True, error_messages={ 'unique': ("number_existsssss"), }) name = models.TextField("Name") time_stamp = models.DateTimeField("Time-Date", auto_now=True) request_type = models.CharField(max_length=100, default="check" is_staff = models.BooleanField(verbose_name=('staff status'), default=False) is_active = models.BooleanField(verbose_name=('active'), default=True) Transaction Model: class TransactionModel(models.Model): trxID = models.CharField(max_length=15, null=True, unique=True) User = models.ForeignKey(to=User, to_field="phone_number", related_name='transaction', on_delete=models.DO_NOTHING, default=1) time = models.DateTimeField(auto_now=True, null=True) amount = models.CharField(max_length=5, null=True) pay_method = models.CharField(max_length=10, null=True) amountReceivedFrom = models.CharField(max_length=26, null=True) transactionStatus = models.CharField(max_length=15, null=True, default='False') I think I made some mistake on foreign key relation. the error shows: raise self.model.DoesNotExist( user_signup.models.User.DoesNotExist: User matching query does not exist. [04/Sep/2021 18:44:22] "POST /add-cash/b-kash HTTP/1.1" 500 20728 -
How to update a different models instance based on a PATCH request of a different model in django rest framework?
I have two models, one Master model which stores information coming from batch and trial models. Now what I need is when I perform a PATCH request on the batch I want the Master entries for that batch to be updated as well. But the catch is that I have overridden the save method in a way that whenever I call the save method, all info goes on to the Master model, same goes for trial as well. How can I achieve this? -
Word count in a row
3 larg email messag render slowli 3 profil manag xml pars error 4 click sidebar tab set focu sidebar Suppose this is my txt file dataset in a short form. I want to count every word in a row and replace that word into that word count no. But i can't. In python how to do that code. -
django add parents to field valurs
I have a Product model that has a ManyToMany to Category. Category has a ForeignKey to itself named parent. I want to add all parents of selected category to category field. example for category: digital appliance->None __ Mobile->digital appliance __ Samsung->Mobile and... when choose Samsung for category of a product, I want to add Mobile and digital appliance to category it's my models, the save method doesn't do anything Class Product: class Product(models.Model): STATUS_CHOICES = ( ('s', 'show'), ('h', 'hide'), ) title = models.CharField(max_length=150) slug = models.SlugField(max_length=170, unique=True) category = models.ManyToManyField(Category) thumbnail = models.ImageField(upload_to='images/products', default='images/no-image-available.png') image_list = ImageSpecField(source='thumbnail', processors=[ResizeToFill(400, 200)], format='JPEG',options={'quality': 75}) image_detail = ImageSpecField(source='thumbnail', processors=[ResizeToFill(1000, 500)], format='JPEG',options={'quality': 100}) description = models.TextField() inventory = models.IntegerField() features = models.ManyToManyField(Feature) status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='s') def __str__(self): return self.title class Meta: verbose_name = "product" verbose_name_plural = "products" def save(self, *args, **kwargs): for cat in self.category.all(): if cat.parent: self.category.add(cat.parent) return super(Product, self).save(*args, **kwargs) objects = ProductManager() Category and CategoryManager: class CategoryManager(models.Manager): def no_parent(self): return self.filter(parent=None) def get_parent(self, parent): return self.filter(parent=parent) class Category(models.Model): parent = models.ForeignKey('self', default=None, null=True, blank=True, on_delete=models.SET_NULL,related_name='children') title = models.CharField(max_length=40) slug = models.SlugField() status = models.BooleanField(default=True) -
How to change the Django admin filter to use a dropdown instead of list that can also be searched?
Before you mark this as Duplicate, I have read the solutions to this question. In Django Admin I have lots of values. The team that works on that data, currently can use CTRL+F to atleast find the required field. To fix the UI I have the Dropdown rendering option available in the solution of the question tagged above. But, as I said I need it to be searchable. -
Why would someone set primary_key=True on an One to one reationship (OneToOneField)?
I was watching a video on django-orm and the instructor stated that: We should set primary_key=True to prevent a Model from having duplicate rows in a OneToOne relationship (Ex: Prevent a user from having multiple profiles). I know this statement is wrong! AFAIK, an OneToOne field is just a ForeignKey with unique parameter set to True. But I got curious and looked-up the Django documentation, Sure enough they are using primary=True in their example. class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(models.Model): place = models.OneToOneField( Place, on_delete=models.CASCADE, primary_key=True, ) So, why would someone set primary_key=True on an OneToOne relation? My guess is that it's just reasonable to have that field as a primary key and there is no technical background behind it. -
In Django project method authenticate returns None
I have a problem with authenticate() method. It always returns None. I checked all my arguments and they are not empty. In models i have USERNAME_FIELD = 'username', in settings i have AUTH_USER_MODEL = 'account.User'. I really cant understand why it's not working. Help please models.py class User(AbstractBaseUser): id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='id') email = models.EmailField() username = models.CharField(max_length=25, unique=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) education = models.CharField(max_length=100, blank=True) date_of_birth = models.DateField(blank=True, null=True) name = models.CharField(max_length=25, blank=True) last_name = models.CharField(max_length=25, blank=True) objects = UserManager() USERNAME_FIELD = 'username' views.py class UserLoginView(ObtainAuthToken): serializer_class = UserLoginSerializer serializers.py class UserLoginSerializer(serializers.Serializer): username = serializers.CharField(required=True) password = serializers.CharField(required=True) def validate_username(self, username): if not User.objects.filter(username=username).exists(): raise serializers.ValidationError('User wasn\'t found') print(User.objects.get(username=username).password) return username def validate(self, data): # authentications request = self.context.get('request') username = data.get('username') # test_name password = data.get('password') # newpassword11 if username and password: user = authenticate(username=username, password=password, request=request) print(user) if not user: raise serializers.ValidationError('Invalid password') else: raise serializers.ValidationError('You have to type you\'re mail and password') data['user'] = user return data