Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django | Error 403 39 on reCAPTCHA validation
I'm trying to use Google's reCAPTCHA v2 to protect my form. Working with React.js as frontend framework and Django as backend framework, I had no problems at the development stage. When I deploy this site the following error is reported on the servers' log: - admin [03/Sep/2020:21:13:06 +0000] "POST /send_email/ HTTP/1.1" 403 39 "https://www.example.com/contact/" "Mozilla/5.0 (X11; Ubuntu:..." I can't see where it is failing, this is the only message that I got from the server log. Here is the function that validates the reCAPTCHA: @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def sendForm(request): data = JSONParser().parse(request) #Here are the form's data and the reCAPTCHA's token #Check reCaptcha SECRET_KEY = os.getenv("GOOGLE_KEY") recaptcha_response = data['token'] url = 'https://www.google.com/recaptcha/api/siteverify' payload = { 'secret': SECRET_KEY, 'response': recaptcha_response } dataGoogle = urllib.parse.urlencode(payload).encode() req = urllib.request.Request(url, data=dataGoogle, method='POST') # verify the token submitted with the form is valid response = urllib.request.urlopen(req) result = json.loads(response.read().decode()) if result['success']: ... Since it worked at the production stage, I'm quite lost. Note. I've verified the public and private keys. The last time I noticed that there were not any request in the Google Console Admin. Thank you in advance for your answers and time! -
Django live telecasting the actions being performed
I am developing Django application which will run a very big task at background. I would like to telecast the status of execution (live logs) on UI. I understand, django-background-tasks help to run background tasks. But when it is being executed, whatever the logs that system generates need to be live telecasted on UI (Like a similar way how Jenkins do when build is on progress). Help on how to achieve it. -
How do websites create the form fields for addresses? is there an API?
How are a the form inputs in websites created for addresses.. how are all the states and cities showing? my major question is, is there an API that can help provide the locations for an address form or do they usually hard code the locations on their website server? -
how to design the web page in Django html template
From the picture I am trying to explain what I want in web page. And for convenience I have gave the number to the block in picture and I have created block 3 ,4 5,6,7 in one .html file. Actually I want navber1 and navbar2 will display in every page of my project that's why I have to create one separate .html file for navbar1 and navbar2 but the problem is I'm not able to apply two navbar in one html file. I also tried with sidebar (for navbar2) but I have faced some issue Dropdown button not worked on the sidebar and When I reload the page the menu of the side bar will display fist then sidebar overwrite the menu and then visualised properly. please suggest me how to design the page for navbar1 and navbar2 in one html file -
What is a good tech stack for a small business non related with software industry
I'm about to start a business in which we are going to be sending emails to potential clients. We have a database already and we need to have our day-to-day work and accountability in sync. I have imagined having Heroku app(Django as I know) using Sendgrid and Mailchimp and store the finances in google sheets. The problem is that this doesn't feel like flowing. Could you help me get a good tech stack for the business to flow? -
Why Django Doesn't Accept A Rich Text Formatted By Tiny Powered Text area?
I am Working On A Blog Website And I Had A Simple Textarea With No Formatting Options provided to Users, So I Switched To A WYSIWYG Text Area With Text Formatting Functions And The Problem Is That The Form Is Not Accepting The Text Which I Pass To That Textarea So Here Is What My Model Look Like class Article(models.Model): title = models.CharField(max_length=300) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) article_thumbnail_image_url = models.ImageField(default='default.png',blank=True) finalImage = article_thumbnail_image_url.get_attname() author = models.ForeignKey(User, default=None, blank=True, null=True, on_delete=models.CASCADE) Here Is What My View Function Look Like: @login_required(login_url='/accounts/login') def write_article(request): if request.method =='POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): instance= form.save(commit = False) instance.author = request.user instance.save() return redirect('/') else: form = forms.CreateArticle() return render(request, 'articles/write.html', {'form': form}) And Finally, This Is How My Html File Look Like <!DOCTYPE html> <html> <head> <title>Create An Article</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script> <script>tinymce.init({ selector:'textarea' });</script> </head> <body> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <div class="box"> <form class="site-form" action="" name = "article" method="post" enctype="multipart/form-data"> <div> {{form}} {% csrf_token %} </div> </form> </div> <script> const titleInput = document.querySelector('input[name= … -
How can I send a post request to another API from my own application
urls.py urlpatterns = [ path('create_item/', CreateItem.as_view()), ] serializers.py class ParentReferans(serializers.Serializer): name = serializers.CharField() value = serializers.IntegerField() class ItemSerializer(serializers.Serializer): SubItem = serializers.BooleanField() Type = serializers.CharField() Name = serializers.CharField() ParentRef = ParentReferans(many=True, read_only=True) views.py class CreateItem(views.APIView): def post(self, request): response = requests.post('https://sandbox-quickbooks.api.intuit.com/v3/company/4620816365135062310/item?minorversion=4', data=request.data) serializer = ItemSerializer(data=request.data) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I want to send post request to (https://sandbox-quickbooks.api.intuit.com/v3/company/4620816365135062310/item?minorversion=4) address. But I could not come to a conclusion about what I could do. How should I go about this problem? -
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
i am trying to execute the following code on terminal with django.core.mail send_mail send_mail('some title','some text','myemail@gmail.com',['otheremail@gmail.com']) but after execution the console is showing this error Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/adjtlikp/virtualenv/globalit-web/3.7/lib/python3.7/site-packages/django/core/mail/__init__.py", line 61, in send_mail return mail.send() File "/home/adjtlikp/virtualenv/globalit-web/3.7/lib/python3.7/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/adjtlikp/virtualenv/globalit-web/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/adjtlikp/virtualenv/globalit-web/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 338, in connect (code, msg) = self.getreply() File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 394, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed my settings.py EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = 'mypass' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_PORT = 465 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER i tryed to change the EMAIL_PORT and the EMAIL_HOST but nothing changed the intersting is that in localhost the code work perfect but when i am using the host the errors came to me -
Django how to change value on table and keep old records same, apply changes to futures records only
In this Invoicing app, when i change the price on product table, all the previous invoices change too, any solution to keep old invoices same and make changes only on futures ones. class Product(models.Model): code = models.CharField(max_length=64, unique=True) name = models.CharField(max_length=64) price = models.DecimalField(max_digits=20, decimal_places=2) class Invoice(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey(Client,on_delete=models.CASCADE) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) -
Create and access url parameters django routers and class view
How do I create passed in url parameters. I have a class view... class ExampleView(viewsets.ModelViewSet): serializer_class = ExampleSerializer queryset = ExampleModel.objects.all() and my serializer looks like... class ExampleSerializer(serializers.ModelSerializer): class Meta: model = ExampleModel fields = '__all__' and my urls.py file... router = routers.DefaultRouter() router.register(r'example', views.ExampleView, 'example') urlspatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), re_path(r'^', views.FrontendAppView.as_view()), ] but what I really want is a way to pass in parameters, for instance, in my class view instead of doing ExampleModel.objects.all() I want to do something like ExampleModel.objects.get(field_name=param_value) in my urls.py do something like... router.register(r'<int:example_id>/example', views.ExampleView, 'example') being that I "pass in a parameter to my url" example_id I would like to somehow retrieve that in my class view but does not work -
Finding all names in a list that contains a substring without changing the characters
I'm doing a key-search in a list for a search system and having a little bit of trouble in the exhibition. I found that if I lowercase both, the list with all my pages titles and the key I could do a simple search. It worked. But in the end, to exhibit the searched titles as related results, I'm displaying the names lowercased, as I did it for comparing. I was wondering if there is any way that I could display the names as they were before comparing or a better way to do this search, looking for maintaining the original title. This is my search function def search(request): q = request.GET['q'] if util.get_entry(q): #redirect to the existing page calling entry() return redirect("entry", title=q) #searching for matching entries titles #getting all the entries titles in a list all_entries = util.list_entries() #lowering case of the list and the key to avoid comparision problems all_entries = [item.lower() for item in all_entries] key = q.lower() #making a new list with the matching results match_entries = [i for i in all_entries if key in i] #renders the results page passing the list of matching titles return render(request, "encyclopedia/search.html",{ 'title' : q, 'entries' : match_entries … -
How can I write a Jquery function which 'creates' or 'modifies' existing html modal
I'm trying to create a confirm delete window for users who are trying to delete the existing model from my cloud panel. So I created HTML design, but now I'm stuck with the coding part, I'm really green on Jquery and JS, so I pretty much know the logic, but I can't achieve it in code. How should it work? When the user presses on the delete button, I somehow need to pass in the information of the model the user is trying to delete and then modify the delete window content with the model information. What have I done for now? I have only designed the design (HTML code), which I'm putting down here. This is the delete window: <!-- Confirm delete --> <div class="modal fade" id="reply_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true" data-keyboard="false" data-backdrop="static"> <form method="post" action="{{request.build_absolute_uri}}"> {% csrf_token %} <div class="modal-dialog rounded" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> <div class="text-danger"> <i class="fas fa-exclamation-triangle"></i> Please confirm your action! </div> </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <span class="text-center text-dark p-3 border-bottom shadow-sm" style="background-color: #ffe88a;font-size: 14px;">Warning: This action cannot be undone</b>.</span> <div class="modal-body" style="background-color: #fafafa;font-family: 'Mukta', sans-serif;"> {% if messages %} {% for message in messages %} … -
FilterSet field with ModelMultipleChoiceFilter for an intermediate model
I have following models: class ItemAddon(models.Model): name = models.CharField(max_length=127) price = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=2) class ItemAddonAreaRelation(models.Model): itemaddon = models.ForeignKey( 'ItemAddon', on_delete=models.CASCADE, help_text='Item Addon to relate', related_name='relations' ) area_id = models.ForeignKey( 'Area', on_delete=models.CASCADE ) class Area(models.Model): name = models.CharField(max_length=127) class ItemAddonsViewSet(viewsets.ModelViewSet): serializer_class = ItemAddonsSerializer search_fields = ('id', 'name') ordering_fields = ('id', 'name') filterset_class = ItemAddonFilter class ItemAddonFilter(FilterSet): area_ids = ModelMultipleChoiceFilter( method="filter_by_area_ids", widget=CSVWidget() ) I want to filter out ItemAddons based on area id. For example: GET /api/itemaddons?area_id=1,2,3 How can i put the queryset to get the above working? -
Django REST - rest_auth custom fields not being serialized
I'm using Django REST with the rest_auth package, and I'm having an issue with serializing custom fields when registering a new user. The field "is_employer" is always set to false even when you set it to true. Also in the API if you set the is_employer checkbox to true, it doesn't change anything. I added it in models, serializers and adapter, what am I missing? MODELS: class MyUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): username = None first_name = None last_name = None email = models.EmailField(verbose_name='email address', max_length=255, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_employer = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = MyUserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(selfself, app_label): return True; SERIALIZERS: from django.contrib.auth.hashers import make_password from rest_framework import serializers from rest_auth.registration.serializers import RegisterSerializer from users.models import CustomUser class CustomRegisterSerializer(RegisterSerializer): def get_cleaned_data(self): … -
django multiple models with same foreign key
I have django app that is tracking contracts, locations, and products for various clients. Contracts, Locations each reference the client with a ForeignKey. class Location(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) ... class Contract(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) ... I also have a product that will be deployed in a location, on a contract, for a client. I need to include client in product because the reference is used to secure the record to that client. class Product(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) contract = models.ForeignKey(Contract, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) .... What is the best way to make sure a product is never created that contains a different client reference across all 3 models? I was thinking I could use a pre_save signal but I would rather use a database constraint but I don't see a database constraint to force this. -
Can't login as a user or admin in Django project even though password is right
In the admin panel when my password is right and I click on login it just reloads me to the same page and when my password is wrong it shows an error and in my project when I log in it takes me to the home page but not logged in. My settings file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECRET_KEY = '4uo!kh!^)!lc^xb0!&4aym-=%2(guhdfr^!2ly+rb0_!=@qnhx' SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', '4uo!kh!^)!lc^xb0!&4aym-=%2(guhdfr^!2ly+rb0_!=@qnhx') # SECURITY WARNING: don't run with debug turned on in production! #DEBUG = True DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = ['.herokuapp.com','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'catalog' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'locallibrary.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'locallibrary.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators … -
TypeError in view: Field expected a number but got ' '
it's my first time posting a question in stack overflow so bear with me :D I'm trying to create a staff model from a form but an error keep persisting This is my models file : class CustomUser(AbstractUser): user_type_data = ((1, "HOD"), (2, "Consultant")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class Consultant(models.Model): CHOICES = ( ('P', 'au paiement'), ('J15', 'J+15'), ('J30', 'J+30'), ) id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) client_id=models.ForeignKey(Client,on_delete=models.CASCADE,default=1) tarif_facturation = models.IntegerField(blank=True, null=True) tarif_Consultant = models.IntegerField(blank=True, null=True) cnss = models.IntegerField(blank=True, null=True) rib = models.IntegerField(blank=True, null=True) paiement = models.CharField(max_length=300, choices=CHOICES) profile_pic = models.FileField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() @receiver(post_save,sender=CustomUser) def create_user_profile(sender,instance,created,**kwargs): if created: if instance.user_type == 1: AdminHOD.objects.create(admin=instance) if instance.user_type == 2: Consultant.objects.create(admin=instance, client_id=Client.objects.get(id=1), tarif_Consultant="", tarif_facturation="", cnss="", rib="", paiement="") @receiver(post_save,sender=CustomUser) def save_user_profile(sender,instance,**kwargs): if instance.user_type==1: instance.adminhod.save() if instance.user_type==2: instance.consultant.save() My views: def add_staff_save(request): if request.method!="POST": return HttpResponse("Method Not Allowed") else: email=request.POST.get("email") password=request.POST.get("password") first_name=request.POST.get("first_name") last_name=request.POST.get("last_name") username=request.POST.get("username") client_id=request.POST.get("client") tarif_facturation=request.POST.get("tarif_facturation") tarif_Consultant=request.POST.get("tarif_Consultant") cnss = request.POST.get("cnss") rib = request.POST.get("rib") paiement = request.POST.get("paiement") #try: user=CustomUser.objects.create_user(username=username,password=password,email=email,last_name=last_name,first_name=first_name,user_type=2) client_obj=Client.objects.get(id=client_id) user.consultants.client_id=client_obj user.consultant.tarif_facturation=tarif_facturation user.consultant.tarif_Consultant=tarif_Consultant user.consultant.cnss=cnss user.consultant.rib=rib user.consultant.paiement=paiement user.save() Here is the Traceback : ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'gestion'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'gestion.LoginCheckMiddleWare.LoginCheckMiddleWare'] Traceback (most recent call last): File "C:\Users\WD\Miniconda3\lib\site-packages\django\db\models\fields\__init__.py", … -
How to use saved card to pay with stripe?
I'm trying to build a checkout flow where the user can pay using a new card or a card that is saved to the customer object. I'm struggling on how to actually use the saved card details to create a charge. This is what I'm working with at the moment. I want for the user to be able to select one of the payment methods from radio and use that to create the payment, and if they choose new card, be able to use that form to add details view.py customer_id = user.userdetails.customer_id stripe.Customer.create_source( customer_id, source=token, ) charge = stripe.Charge.create( amount=standard_price, currency='usd', description=desc, receipt_email=request.user.email, customer=customer_id ) var stripe = Stripe('key'); // Create an instance of Elements. var elements = stripe.elements(); // Custom styling can be passed to options when creating an Element. // (Note that this demo uses a wider set of styles than the guide below.) // Create an instance of the card Element. var card = elements.create('card', { style: style }); // Add an instance of the card Element into the `card-element` <div>. card.mount('#card-element'); // Handle real-time validation errors from the card Element. card.on('change', function (event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } … -
Update profile with nested user in django rest framework
I need to update the Administrator object with the user in one request using a nested serializer. My views.py: class AdministratorDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Administrator.objects.all() serializer_class = AdministratorSerializer permission_classes = ( permissions.IsAuthenticated, custom_permissions.IsAdministrator | custom_permissions.IsHR | permissions.IsAdminUser, ) def put(self, request, *args, **kwargs): serializer = AdministratorSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) And serializers.py: class AdministratorSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = Administrator fields = '__all__' def create(self, validated_data): user_data = validated_data.pop('user') password = User.objects.make_random_password() user = User.objects.create_user( password=password, is_administrator=True, **user_data ) admin_obj = Administrator.objects.create(user=user, **validated_data) send_password.delay(user.email, password) return admin_obj def update(self, instance, validated_data): user_data = validated_data.pop('user') print(user_data) user = instance.user for k, v in user_data.items(): setattr(user, k, v) user.save() for k, v in validated_data.items(): setattr(instance, k, v) instance.save() return instance But I got 400 Bad Request: { "user": { "email": [ "user with this email address already exists." ] } } Where had I gone wrong? Why does it want to create a new user on put request? -
Importing contents of text file into postgresql database using Django
I am currently working on a project where I need to import contents of text file(with no-header & fixed width fields) into a database table (postgresql) using Django Framework. What is the best way to make the imports or any other utility that would suffice the requirements? -
How to implement some feature? [closed]
I want to create the social network that should work as Reddit, but idk how to implement one thing. I did Communities model(subreddits) and also did Posts model. And it works fine, but i want to add the feature that will let you to create posts not only for one of the communities, but also for your profile, I mean that check this image class Community(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, null=True, blank=True) description = models.TextField(max_length=500) cover = models.ImageField(upload_to='c_covers/', blank=True, null=True) admins = models.ManyToManyField(User, related_name='inspected_c') subscribers = models.ManyToManyField(User, related_name='subscribed_c') banned_users = models.ManyToManyField(User, related_name='forbidden_c') created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) class Post(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, null=True, blank=True) body = models.TextField(max_length=5000, blank=True, null=True) photo = models.ImageField(upload_to='post_photos/', verbose_name=u"Add image (optional)", blank=True, null=True) author = models.ForeignKey(User, related_name='posted_p', on_delete=models.CASCADE) community = models.ForeignKey(Community, related_name='submitted_p', on_delete=models.CASCADE) points = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='liked_p', blank=True) mentioned = models.ManyToManyField(User, related_name='m_in_posts', blank=True) rank_score = models.FloatField(default=0.0) active = models.BooleanField(default=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) -
OperationalError at /admin/login/ no such table Django
I am getting the following error whenever I try to sign in into Django's admin dashboard, I type in my username & password to login, I get the following error: OperationalError at /admin/login/ no such table: myapp_myuser Request Method: POST Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 3.1 Exception Type: OperationalError Exception Value: no such table: myapp_myuser settings.py AUTH_USER_MODEL = 'myapp.MyUser' models.py class MyUser(AbstractUser): id = models.UUIDField(primary_key= True, default= uuid.uuid4, editable= False) first_name = models.TextField(max_length= 25) last_name = models.TextField(max_length= 25) email = models.EmailField(unique= True) class MyModel(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete= models.CASCADE, null= True) user_folder = models.FileField(upload_to= create_user_folder, null= True) Thanks in advance. -
Heroku duplicate key value violates unique constraint (django)
Today I deployed my django app on Heroku for the first time (following this tutorial). The problem is that when I want to modify or add something to the database, I get an Integrity Error which says: duplicate key value violates unique constraint "app_professore_pkey" Where Professore is the name of the Model I tried to modify. I’ve searched a bit online and I’ve seen that probably is because I developed the app on my PC using SQLite and now, on Heroku, it uses PostgreSQL, and those 2 databases works differently. Actually, I don’t have a lot of experience with databases (almost no experience) so I don’t know how to fix this... Maybe modifying something on the Professore model? Or typing something in the Heroku console? This is the error screen I get, if you need it to help me :) Thanks in advance and tell me if I wasn’t clear on something (I’m new to StackOverflow too) -
How can I submit html5 user location to django view using ajax or form?
I am trying to submit a user location to Django class based view using either ajax or form. But my understanding of Javascript and ajax is limited. How can i submit html5 user location to django cbv? views.py: class UserProfileView(CreateView): model = UserProfile fields = ['user_location'] template_name = 'rent_app/user_profile.html' html: {% block content %} <body> {% leaflet_map "map" callback="ourfunction" %} <div id="sidebar" class="sidebar collapsed"> <form method="POST" action="{% url 'rent_app:add-location' %}"> {{ csrf_token }} {% form.as_p %} </form> </div> <script type="text/javascript"> var collection = {{ object_list|geojsonfeature:"popupContent"|safe }}; console.log(collection); function onEachFeature(feature, layer) { if (feature.properties && feature.properties.popupContent) { layer.bindPopup(feature.properties.popupContent); } } function ourfunction(map, options) { map.locate({setView: true, maxZoom: 16}); map.on('locationfound', onLocationFound); function onLocationFound(e) { var radius = e.accuracy; var position= e.latlng; L.marker(e.latlng).addTo(map) .bindPopup("You are within " + radius + " meters from this point").openPopup(); L.circle(e.latlng, radius).addTo(map); } function onLocationError(e) { alert(e.message); } map.on('locationerror', onLocationError); L.geoJson(collection, {onEachFeature: onEachFeature}).addTo(map); } </script> forms.py: class UserProfileModelForm(forms.ModelForm): class Meta: model = UserProfile fields = ('id', 'user_location') widgets = {'geom': LeafletWidget(),'e':forms.HiddenInput()} -
Troubling accessing media on AWS S3, ERROR 403, on Django app
I am having trouble accessing media files uploaded on AWS S3 for my Django app. I was attempting to use Boto3 and Django-Storages libraries and followed these tutorials: https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html https://www.youtube.com/watch?v=kt3ZtW9MXhw Both the Django Admin website and my front-end website are not able to load any of the static and media content. The Django admin is rendered without any CSS, and similarly my front-end has no images. AWS Configurations were added to the settings.py file: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_S3_REGION_NAME = "me-south-1" AWS_STORAGE_BUCKET_NAME = 'jooler-mea' AWS_S3_CUSTOM_DOMAIN = '%s.s3.me-south-1.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_STATIC_LOCATION = 'static' STATICFILES_STORAGE = 'joole.storage_backends.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION) DEFAULT_FILE_STORAGE_LOCATION = 'media' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'joole.storage_backends.MediaStorage' The relevant storages in storage_backends.py file: from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = settings.AWS_STATIC_LOCATION class MediaStorage(S3Boto3Storage): location = settings.DEFAULT_FILE_STORAGE_LOCATION file_overwrite = False I added S3FullAccess: The files are successfully uploading to the AWS website, I can download the files from there to my computer. I tried playing around with CORS and custom policies but have not been successful. I've hit a dead end or not sure where to go from here. Any help would …