Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to over write or add words to Django URL?
When I go on my product detail page I get http://xxx.x.x.x:x000/product/PN/ I want to change the URL from PN to the name of the product. So my URL should look like this if everything works right http://xxx.x.x.x:x000/product/name/: model.py class Product(): name = models.CharField(max_length=400, db_index=True) PN = models.CharField(max_length=100, default=random_string) view.py def product_detail(request, PN): product = get_object_or_404(Product, PN=PN) return render(request, 'productdetail.html', {'product': product}) url.py urlpatterns = [ url(r"^", include("users.urls")), path('product/<str:PN>/', productdetail, name='productdetail') ] -
Django model instance caching - for the same record
I've a standard django model class and I'd like to cache a method's return value: class Sth(models.Model): pr = models.CharField(max_length=128) ... def some_method(self): return 'some result' . So, if an Sth instance has not been saved, I'd like to cache the result of the some_method, but if it has been saved, I'd like to recalculate the result of the some_method method for the first run. Is there any solution for that? I've memcached for cache, and to make it complicated, Django version is 1.11.16 . -
Passing a parameter to a ModelForm and using min_value
I want to pass a parameter to my ModelForm so I can use it as an argument for min_value. I also don't know where can I use min_value inside a ModelForm. views.py: return render(request, "page.html", { "form": createBiding(minAmount) }) forms.py: class createBiding(forms.ModelForm): #How do i accept minAmount as a parameter #where do i put min_value class Meta: model = bid fields = [ 'bidAmount' ] widgets = { 'bidAmount': forms.NumberInput(attrs={ 'class': "form-control", 'style': '', 'placeholder': 'Place your bid' }) } I am new to Django and programing in general. Help is appreciated. -
Return a value of a model based on the max value of another field of the model
My Model class Energy_Consuption(models.Model): name=models.IntegerField() meter=models.IntegerField() class Meta: db_table:'Energy_Consuption' My Views def details (request): top_meter = Energy_Consuption.objects.aggregate(Max('meter')) return render(request,'details.html', {'top_meter':top_meter}) hello guys, I am having a model in Django with two fields, name and meter. I have created a views file and I want to find and print the name with the biggest meter. The code below find and prints the biggest meter itself which is good but now what I want. I want to print the name that is related to that meter. Any idea how to do so? def details (request): top_meter = Energy_Consuption.objects.aggregate(Max('meter')) return render(request,'details.html', {'top_meter':top_meter}) the view is connected to an HTML page -
Django Scopes - How to get current tenant?
I'm fairly new to Django and I'm building a multi tenant app. I'm not really sure how to get the logged in user's current tenant in order to use it as a filter in views. Example: Post.objects.filter(tenant=current_tenant) Example Models: from django.db import models class Tenant(models.Model): name = models.CharField(…) class Post(models.Model): tenant = models.ForeignKey(Tenant, …) title = models.CharField(…) class Comment(models.Model): post = models.ForeignKey(Post, …) text = models.CharField(…) Where should I write the get_current_tenant function and how should I write it? Any help would be greatly appreciated. -
Django iterate through a dictionary and render to a template
This code gives me the output that I need on the terminal but when I try to render it in the template it gives me only the last result. I read a couple of other answers but nothing leads me to understand where is the mistake. Thank you. def forecast(request): if request.method == 'POST': city = urllib.parse.quote_plus(request.POST['city']) source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/forecast?q='+ city +'&units=metric&appid=ab3d24d85590d1d71fd413f0bcac6611').read() list_of_data = json.loads(source) pprint.pprint(list_of_data) forecast_data = {} for each in list_of_data['list']: forecast_data['wind_speed'] = each["wind"]['speed'] forecast_data['wind_gust'] = each["wind"]['gust'] forecast_data['wind_deg'] = each["wind"]['deg'] forecast_data["coordinate"] = str(list_of_data['city']['coord']['lon']) + ', ' + str(list_of_data['city']['coord']['lat']) forecast_data["name"] = list_of_data["city"]["name"] forecast_data["dt_txt"] = each["dt_txt"] # uncomment for see the result in the terminal print(forecast_data) fore = {'forecast_data':forecast_data} else: list_of_data = [] fore = {} return render(request, "WindApp/forecast.html",fore) and this is the HTML part: <div class="row"> {% for x,y in forecast_data.items %} <div class="col d-flex justify-content-center" "> <div id="output" class=" card text-black bg-light mb-6"> <div id="form" class=" card-body"> <h4><span class="badge badge-primary">City:</span> {{forecast_data.name}}</h4> <h4><span class="badge badge-primary">Coordinate:</span> {{forecast_data.coordinate}}</h4> <h4><span class="badge badge-primary">Day/Time:</span> {{forecast_data.dt_txt}}</h4> <h4><span class="badge badge-primary">Wind Speed: </span> {{forecast_data.wind_speed}} Kt</h4> <h4><span class="badge badge-primary">Wind Gust : </span> {{forecast_data.wind_gust}} Kt <img src="{% static 'img/wind.png' %}" width="64" height="64" alt="wind"></h4> <h4><span class="badge badge-primary">Wind direction : </span> {{forecast_data.wind_deg}} <img src="{% static 'img/cardinal.png' %}" width="64" height="64" alt="dir"></h4> </div> … -
How to append element to div in a specific order?
I have 4 div and n elements that I want to append like this: 1el in 1div 2el in 2div 3el in 3div 4el in 4div And 5el in 1div so on and so forth I am using python and django. Any help would be highly appreciated... -
Each user will have a subdomaine (username.domaine.com) + the possibility to add a custom domaine (ustomUserDomaine.com)?
Basically what am creating is a platform which is simillar to Shopify, it's simillar because each user will have his own profile at a subdomaine: user.domaine .com, also I want to give the user the possibility to link his own custom domain userDomaine .com, so instead of the subdomaine, he will have a custom domain linking to his profile, of couse by adding the CNAMS. So I need from Django to generate a new subdomain for each new user and also the possibility to link a custom domaine to be used instead of the subdomaine. How can I achieve all this ?? any infos ? any tutorials ? any packages that will help ?? thank you in advance. -
Unable to makemigrations with PostgreSQL setup
I am trying to setup PostgreSQL locally on my computer, but when I try to initially set up my Django application with it using python manage.py makemigrations, I am given this warning: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': fe_sendauth: no password supplied My database table in my settings.py is as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get("DB_NAME"), 'USER': os.environ.get("DB_USER"), 'PASSWORD': os.environ.get("DB_PASSWORD"), 'HOST': os.environ.get("DB_HOST"), 'PORT': os.environ.get("DB_PORT"), } } My .env file is located in the same directory as my manage.py file: DB_NAME=Smash DB_PASSWORD=root DB_USER=SmashDatabase DB_HOST=localhost DB_PORT=5432 DEBUG=1 I tried following this link's instructions but none of the offered solutions fixed the problem. I don't know what is wrong or what causes this issue. -
django get_or_create throws Integrity Error
I have read this thread: get_or_create throws Integrity Error But still not fully understand when get_or_create returns False or IntegrityError. I have the following code: django_username = 'me' user = get_user_model().objects.filter(username=django_username).first() action_history, action_added = ActionModel.objects.get_or_create( date=date_obj, # date object account_name=unique_name, # e.g. account1234 target=follower_obj, # another model in django user=user, # connected django user defaults={'identifier': history['user_id']} ) While the model looks like: class ActionModel(models.Model): """ A model to store action history. """ identifier = models.BigIntegerField( _("identifier"), null=True, blank=True) # target id account_name = models.CharField(_("AccountName"), max_length=150, null=True, blank=True) # account name of the client date = models.DateField(_("Date"), auto_now=False, auto_now_add=False) # action date target = models.ForeignKey(Follower, verbose_name=_("Target"), on_delete=models.CASCADE) # username of the done-on action user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, editable=False, db_index=True, ) # django user that performed the action class Meta: verbose_name = _("Action") verbose_name_plural = _("Actions") unique_together = [ ['account_name','date','target'], ] Sometimes it return IntegrityError, and sometimes (when unique constrain exists it will return False on created). -
how to use aws secret manager values of a postgres database in terraform ecs task definition
I have the settings.py file below of a django application using terraform , docker compose and im trying to get the value of the database stored in aws secret manager in ecs task definition settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ.get("POSTGRES_DB"), "USER": os.environ.get("POSTGRES_USER"), "PASSWORD": os.environ.get("POSTGRES_PASSWORD"), "HOST": os.environ.get("POSTGRES_HOST"), "PORT": 5432, } } task definition resource "aws_ecs_task_definition" "ecs_task_definition" { family = "ecs_container" network_mode = "awsvpc" requires_compatibilities = ["FARGATE"] cpu = 256 memory = 512 execution_role_arn = data.aws_iam_role.fargate.arn task_role_arn = data.aws_iam_role.fargate.arn container_definitions = jsonencode([ { "name" : "ecs_test_backend", "image" : "${aws_ecr_repository.ecr_repository.repository_url}:latest", "cpu" : 256, "memory" : 512, "essential" : true, "portMappings" : [ { containerPort = 8000 } ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-region": "us-east-1", "awslogs-group": "/ecs/ecs_test_backend", "awslogs-stream-prefix": "ecs" } } "environment" : [ { "name": "POSTGRES_DB", "value": "${var.POSTGRES_NAME}" <=== HERE }, { "name": "POSTGRES_PASSWORD", "value": "${var.POSTGRES_PASSWORD}" <=== HERE }, { "name": "POSTGRES_USERNAME", "value": "${var.POSTGRES_USERNAME}" <=== HERE }, { "name": "POSTGRES_PORT", "value": "${var.POSTGRES_PORT}" <=== HERE }, { "name": "POSTGRES_HOST", "value": "${var.POSTGRES_HOST}" <=== HERE }, ] } ]) } The configuration below var.XXX does not seem to work as the task logs return psycopg2.OperationalError: FATAL: password authentication failed for user "root" It probably because its not able to read … -
JavaScript Delete Button Implementation Issues
I am a student studying JavaScript and Django. When I select the current option, I want to create a page where I can check the information (product name, option name, etc.) of the selected option is added. Choosing the option is currently implemented, but I also want to implement the function of deleting the added information after selecting it, so I wrote JavaScript as follows: I have designed the delete button to appear one by one next to the option information, and my goal is to delete only the corresponding information when I press the delete button. However, I am upset that all the information added disappears as soon as I press the delete button. I don't know how to solve it. Can't I just delete the information I want to delete without deleting all the added information? Coding geniuses, please help me. It's a problem that hasn't been solved in a week. If you help me, I will be touched with all my heart. Code : <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>Option</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">Select Option.</option> {% for … -
Django form is not valid when I add image area
I trying create a profile update section in web site. This section have a username, email and change image area. Username and email is working but "Image" does not. Only works when I try email and password but when I add the "Image" field and click the update button there is no change My views: @login_required def update_profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('home') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'accounts/update.html', context) Models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics", null=True, blank=True) def __str__(self): return f"{self.user.username} Profile" def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) TEMPLATE: <div class="container my-5"> {% include 'fixed/_alert.html' %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 h2">Update Profile</legend> {{ u_form | crispy }} {{ p_form | crispy }} </fieldset> <div class="form-group"> <input class="btn btn-outline-info btn-block" type="submit" value="Update"> </div> </form> And my signal.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: … -
Python | Django
I'm a complete noob to programming and currently learning python and django. Recently, I created a python application that requires an input (string) from a user in order to provide desired output. It works perfectly however I would like to make it into a django app where I can provide a gui for inputing the string. python app downloads images to a user machine so I am not worried about the displaying of output. I've been following some tutorials on building and adding applications to django and I kind of understand how it works however I am not sure how to tackle adding an existing application and providing a gui or "input" field for the python application which I already built. Any kind of guidance will be appreciated. thanks -
How to limit the number of records in the Serializer
Hello everyone, how to limit the number of results using a serializer? In short, there is a table of comments, which can contain different types of posts. class CourseComment(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) content = models.TextField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and here related table class CourseMessage(models.Model): course_id = models.ForeignKey(Course, on_delete=models.PROTECT) author_id = models.ForeignKey(User, on_delete=models.PROTECT) text = models.TextField() # RAW Format must exclude specials chars before publish is_pinned = models.BooleanField(default=False) comments = GenericRelation('CourseComment') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I made the serializer according to the documentation https://www.django-rest-framework.org/api-guide/relations/ class CourseMessages(serializers.ModelSerializer): user = Author(source='authorid', read_only=True) files = MessageFiles(source='coursemessageattachedfile_set', many=True) message_comments = MessageComments(source='comments', many=True, read_only=True) class Meta: model = CourseMessage fields = ['text', 'updated_at', 'user', 'files', 'message_comments'] class MessageComments(serializers.RelatedField): def to_representation(self, value): ct = ContentType.objects.get_for_model(value) serializer = Comments(value, read_only=True, source='last_comments') return serializer.data class Comments(serializers.ModelSerializer): author = Author(source='user', read_only=True) class Meta: model = CourseComment fields = ['content', 'author'] Everything works well, but I would like to see first 3 comments. Maybe someone has encountered such a problem, or can advise how to do it better. I get this data for the RetrieveAPIView detail page. The first three comments are required for … -
Erro no models Django + SQL server
Oi, pessoal. Estou fazendo uns testes com django e sql server e sempre obtenho esse erro quando preciso usar nos modelos o ForeignKey. Alguém sabe o motivo? Desde já, obrigada. Imagem do Erro Código -
sending message to csgo game coordinator from django
I am using csgo python module to get the skin float value. It works perfectly in terminal. But I am having issue using it with django. I found out that it uses gevent and I dont know much about it. So I thought changing the approach as it was blocking the django server. Now I'm executing django app and csgo gamecoordinator seperately. Approach 1: Using socket for sending and receiving: csgo_gc.py import json import logging import re import socket from csgo.client import CSGOClient from csgo.enums import ECsgoGCMsg from google.protobuf.json_format import MessageToDict from steam.client import SteamClient logging.basicConfig(format='[%(asctime)s] %(levelname)s %(name)s: %(message)s', level=logging.DEBUG) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) username = '###' password = '###' client = SteamClient() client.set_credential_location('D:\\sentry') cs = CSGOClient(client) def get_params(inspect_link): param_pattern = r'^steam://rungame/730/\d{17}/\+csgo_econ_action_preview%20' \ r'(?:S(?P<param_s>.*)|M(?P<param_m>.*))A(?P<param_a>.*)D(?P<param_d>.*)$' res = re.match(param_pattern, inspect_link) if res: res = res.groupdict(default='0') for k, v in res.items(): res[k] = int(v) return res return None @client.on(client.EVENT_AUTH_CODE_REQUIRED) def auth_code_prompt(is_2fa, code_mismatch): if is_2fa: code = input("Enter 2FA Code: ") client.login(username, password, two_factor_code=code) else: code = input("Enter Email Code: ") client.login(username, password, auth_code=code) @client.on('logged_on') def start_csgo(): cs.launch() @cs.on('ready') def gc_ready(): s.bind(('127.0.0.1', 4500)) s.listen(5) while True: print('waiting for a connection') connection, client_address = s.accept() try: print('client connected:', client_address) while True: data = connection.recv(4096) if … -
Django while running the server ModuleNotFoundError: No module named 'project_name'
Error ModuleNotFoundError: No module named 'book_store' book_store is the project name in manage.py the path for settings is os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'book_store.settings') while runnung python manage.py runserver My folder hierarch book_store static templates settings.py urls.py wsgi.py manage.py -
Can not add highest bid to page in Django
I'm making a Django auction website. The problem is that I have no idea how to add highest bid to index page so that it updates every time user places a bid on another page. views.py: def index(request): index = listing.objects.filter(end_auction=False) number=len(index) return render(request, "auctions/index.html", {"list":index, "number":number}) models.py: class listing(models.Model): Title = models.CharField(max_length=50) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) Description = models.CharField(max_length=300) price = models.DecimalField(max_digits=6, null=True, decimal_places=2) image=models.ImageField( blank = True, null = True, upload_to ='') category = models.ForeignKey(category, on_delete=models.CASCADE, related_name="categories") end_auction=models.BooleanField(default=False) def __str__(self): return f"{self.Title}" class bid(models.Model): listing = models.ForeignKey(listing, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) bid = models.DecimalField(max_digits=6, null=True, decimal_places=2) def __str__(self): return f"{self.bid}, {self.listing}, {self.user}" Keep in mind that I didn't include the whole code which is rather long. If you want me to add something just let me know! Answer would be greatly appreciated! :) -
Django how to secure hidden input fields and prevent forms submitting if value changed?
I am rendering few data in hidden input. User can inspect html page and see those hidden input data. He can also change hidden input data which one kind of security risk for my website. Such as I have an hidden input where user email and name rendering like this <input type="hidden" name="name" class="form-control" placeholder="Your Name" value="Jhone" required=""> User can inspect the html and change the value then my forms submitting with new updated value. is there any way to stop submitting forms if value is changed. here is my code: #html hidden input <input type="hidden" name="name" class="form-control" placeholder="Your Name" value="Jhone" required=""> <input type="hidden" name="email" class="form-control" placeholder="Your Name" value="Jhone@gmail.com" required=""> %for y in user_profile%} <input type="hidden" name='userprofile' value="{{y.id}}"> {%endfor%} <input type="hidden" name="parent" id="parent_id" value="95"> The most import fields for me userprofile and parent. I want to prevent forms submitting if any hidden value change. froms.py class CommentFrom(forms.ModelForm): captcha = CaptchaField() class Meta: model = BlogComment fields = ['name','email','comment','parent','sno','blog','user','userprofile'] views.py if request.method == "POST": if comment_form.is_valid(): isinstance = comment_form.save(commit=False) if request.user.is_authenticated: isinstance.user = request.user elif not request.user.is_authenticated: User = get_user_model() isinstance.user = User.objects.get(username='anonymous_user') isinstance.blog = blog isinstance.save() messages.add_message(request, messages.INFO, 'Your Comment Pending for admin approval') return redirect('blog:blog-detail',slug=blog.slug) else: messages.add_message(request, messages.INFO, "your … -
Data from my Django form is not added to my database cause I cannot view it on the webpage
I am trying to build a project management system and have to add client to my database. For this I have created a form as below forms.py class AddClientForm(forms.Form): email = forms.EmailField(label="Email", max_length=50, widget=forms.EmailInput(attrs={"class":"form-control"})) password = forms.CharField(label="Password", max_length=50, widget=forms.PasswordInput(attrs={"class":"form-control"})) first_name = forms.CharField(label="First Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) last_name = forms.CharField(label="Last Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) username = forms.CharField(label="Username", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) phone = forms.CharField(label="Phone", max_length=15, widget=forms.TextInput(attrs={"class":"form-control"})) #For Displaying Projects try: projects = Projects.objects.all() project_list = [] for project in projects: single_project = (project.id, project.project_name) project_list.append(single_project) except: project_list = [] #For Displaying Contracts try: contracts = Contracts.objects.all() contract_list = [] for contract in contracts: single_contract = (contract.id, contract.contract_name) contract_list.append(single_contract) except: contract_list = [] project_name = forms.ChoiceField(label="Project", choices=project_list, widget=forms.Select(attrs={"class":"form-control"})) contract_id = forms.ChoiceField(label="Contract", choices=contract_list, widget=forms.Select(attrs={"class":"form-control"})) location = forms.ChoiceField(label="Location", choices=States, widget=forms.Select(attrs={"class":"form-control"})) Then i have created the following views.py def add_client(request): form = AddClientForm() context = { "form": form } return render(request, 'admintemplate/add_client_template.html', context) def add_client_save(request): if request.method != "POST": messages.error(request, "Invalid Method") return redirect('add_client') else: form = AddClientForm(request.POST, request.FILES) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] phone = form.cleaned_data['phone'] location = form.cleaned_data['location'] project_id = form.cleaned_data['project_name'] contract_id = form.cleaned_data['contract_id'] try: user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=3) user.clients.location = … -
how to push notifications from Django rest framework to react Js
I am developing a booking management application. There I need to push notifications to a specific user based on an action. For example: if a seller gets an order that he/she will be notified in real time. What's the best way to do it. I have read django-fcm , django-channel , django-push-notification,etc. But I couldn't get a proper idea to do it. -
Querying using related field names
I've got two models that I'd like to perform a reverse search on. I'm wondering how to do this given the fact that one model has to fields with foreign keys to the same model. class Review(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None) class Job(models.Model): cart = models.ForeignKey(Cart, related_name="cart_one", on_delete=models.CASCADE, null=True, blank=True) unscheduled_job = models.ForeignKey(Cart, related_name="cart_two", on_delete=models.CASCADE, null=True, blank=True) employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True, blank=True) My query is as follows: reviews = Review.objects.filter(cart__job__employee=employee) This query is failing due to the fact that the Job model has two foreign keys that point to the cart model. How would I fix this? Thanks! -
django token not being created when user registers
Serializers.py from rest_framework import serializers from rest_framework.authtoken.models import Token # User Related Serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = models.cUser fields = '__all__' def create(self, validated_data): user = models.cUser.objects.create_user(**validated_data) token = Token.objects.create(user=user) return user models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class cUserManager(BaseUserManager): def create_user(self, email, password, **others): email = self.normalize_email(email) user = self.model(email=email, **others) user.set_password(password) user.save() return user def create_superuser(self, email, password, **others): others.setdefault('is_staff', True) others.setdefault('is_superuser', True) return self.create_user(email, password, **others) class cUser(PermissionsMixin, AbstractBaseUser): email = models.EmailField(unique=True) username = models.CharField(max_length=128, unique=True) password = models.CharField(max_length=256, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = cUserManager() I'm creating a custom user (cUser) with the AbstractBaseUser and want to create a token every time a new user gets created (using the rest framework.authToken module) but it is not working, what can I do? -
Changing static files path to s3 buckt path django
Currently I am getting my static files like this: src="{% static 'website/images/home-slider/plantarte-espacio-4.jpg'%}" And my settings.py look like this: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'website/static'), ) Now wat I want is that instead of grabbing the static files from the static foleder inside my app. It goes to my AWS S3 bucket I created and uploaded all the files to Instead of this: src="/static/website/images/home-slider/plantarte-espacio-4.jpg" Do this: src="https://plantarte-assets.s3.us-east-2.amazonaws.com/website/images/home-slider/plantarte-espacio-4.jpg" If someone could please help me I would really apreciate it.