Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Contact Form With Google Recaptcha v3
I want to implement Google Recaptcha v3 into a working Django contact form. I tried following these tutorials: https://simpleisbetterthancomplex.com/tutorial/2017/02/21/how-to-add-recaptcha-to-django-site.html https://foxrow.com/using-recaptcha-v3-with-django https://medium.com/@mihfazhillah/how-to-implement-google-recaptcha-v3-on-your-django-app-3e4cc5b65013 But have had no luck trying to figure it out. Can someone please help me out? Settings.py: GOOGLE_RECAPTCHA_SECRET_KEY = '<KEY>' Html: <script> grecaptcha.ready(function() { grecaptcha.execute('<SITE_KEY>', {action: 'contact'}) .then(function(token) { document.getElementById("form").appendChild(document.CreateElement(`<input type="hidden" name="g-recaptcha-response" value=${token}`); }); }); </script> <form role="form" action="" method="post"> {% csrf_token %} {{ form.as_p }} <script src='https://www.google.com/recaptcha/api.js?render=<SITE_KEY>'></script> <div class="g-recaptcha" data-sitekey="<SITE_KEY>"></div> <button type="submit">Submit</button> </form> Views.py: def contact(request): form_class = ContactForm # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get( 'contact_name' , '') contact_email = request.POST.get( 'contact_email' , '') form_content = request.POST.get('content', '') # Email the profile with the # contact information template = get_template('contact_template.txt') context = { 'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content, } content = template.render(context) email = EmailMessage( "New contact form submission", content, "Your website" +'', ['GMAIL_ADDRESS'], headers = {'Reply-To': contact_email } ) email.send() messages.info(request, "Success") return render(request, 'contact.html', { 'form': form_class, }) Forms.py: from django import forms class ContactForm(forms.Form): contact_name = forms.CharField(required=True) contact_email = forms.EmailField(required=True) content = forms.CharField( required=True, widget=forms.Textarea ) # the new bit we're adding def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['contact_name'].label = "Name:" self.fields['contact_email'].label = "Email:" … -
Django cannt import any function from views
I am trying to import functions which is in file say aaa.py there I am importing views.py as aaa.py from .views import * and in views.py I am importing aaa.py as views.py from .aaa import * But in aaa.py I get an import error saying, cannot import name 'function_name' from 'folder_name.views' -
How the updating of m2m fields are working? Django Rest Framework
I have code where Product model has M2M field Comment model. I made methods in views.py for getting Product by id and all objects of Product, but there's problem with updating it. I can't fully understand how to update Product comments field. I already tried a lot of different answers and ideas, but nothing helps me. I'm using PUT method for update. My main questions: Where and how target Product id in order to update comments field in it? After I find Product by it's id how I can update M2M field comments in it? I tried: Completely Lost: Many To Many with Serializers and Update in Django Rest Framework Doesn't work at all, screams for 'collections.OrderedDict' object has no attribute 'id' Django Rest update many to many by id It's making PrimaryKeyRelatedField which is not correct for me. How to update many to many Django REST? Not enough information in answer, got stuck on it. I read https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers, but found no usefull information on my problem products/models.py from django.db import models from comments.models import Comment # Create your models here. class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=150, blank=True) description = models.TextField(default="No description") category = models.CharField(max_length=255, blank=True) … -
Python(Django) - Convert URL from post to a embed YouTube IFrame
Basically what I trying to achive is to find the URL in the post, for example if I post this: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. https://www.youtube.com/watch?v=example It will be looking like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. YouTube Player {% extends "Feed/wrapper.html" %} {% block content %} <div class="card"> <h2 class="text-info">{{newsfeed_articles.title}}</h2> <h6 class="text-info">{{newsfeed_articles.date|date:"d-m-Y в H:i:s"}}</h6> <p>{{newsfeed_articles.post|safe|linebreaks}}<p> <div class="fakeimg" style="height:200px;">Image</div> </div> {% endblock %} -
django.db.utils.IntegrityError "error makemigrations"
django.db.utils.IntegrityError: The row in table 'biblioteka_book' with primary key '1' has an invalid foreign key: biblioteka_book.info_id contains a value '1' that does not ha ve a corresponding value in biblioteka_extrainfo.id. from django.db import models # Create your models here. class ExtraInfo(models.Model): OCENY = { (0, 'Nieznany'), (1, 'Słaba'), (2, 'Średnia'), (3, 'Dobra'), (4, 'Bardzo dobra'), (5, 'Arcydzieło') } ilosc_stron = models.IntegerField(default=0) ocena = models.IntegerField(default=0, choices=OCENY) class Book(models.Model): nazwa = models.CharField(max_length=60) opis = models.TextField() gatunek = models.CharField(max_length=30) cena = models.DecimalField(max_digits=400, decimal_places=2) wydanie = models.IntegerField(null=True, blank=True) autor = models.CharField(max_length=30) zdjecie = models.ImageField(null=True, blank=False, upload_to='Pictures') przecena = models.BooleanField() info = models.OneToOneField(ExtraInfo, on_delete=models.CASCADE, primary_key=True,) def __str__(self): return self.nazwa_with_wydanie() def nazwa_with_wydanie(self): return str(self.nazwa) + " (" + str(self.wydanie) + ")" -
Why does django admin change_form has a sorting by Primary Key query? Isn't it fetching just one object to edit it?
I have a payments_event model that has millions of data, when I click on one of them to edit it, the page takes tooo much time to load, and when I look at the queries, it has this query: SELECT ••• FROM "payments_event" ORDER BY "payments_event"."id" DESC And it's duplicated two times.. -
Rendering arcGIS pro customized map in the front end
I am new to arcGIS Pro. I created my own map in the arcGIS Pro. I want to render this map dynamically in the front end like a GoogleAPI. I connected arcGIS Pro into Pycharm. But I don't know how to render in the frontend. Could anyone tell a way to render the map??? -
I am not sure how to request Django rest-framework Social Oauth2
I am trying to add Google & Facebook social auth to my DRF api. I followed steps from readme, I read the docs but I don't know how to request my api from my react app - docs shows this example for facebook login: curl -X POST -d "grant_type=convert_token&client_id=<client_id>&client_secret=<client_scret>&backend=facebook&token=<facebook_token>" http://localhost:8000/auth/convert-token` And here my problem comes - I don't understand what is "client_secret" in curl request? Should it be the same as SOCIAL_AUTH_FACEBOOK_SECRET in settings (that is copied from facebook developers site)? -
Store encrypted file in django database using IPFS storage
I am developing a project where I need to upload file from template, then it is retrieved at the backend, encrypted using cryptography module and then stored in database using IPFS File storage system. However I am able to encrypt the file but not able to store it in database. Here is the code: encryption.py from cryptography.fernet import Fernet import os.path def encrypt_file(paper): key = Fernet.generate_key() input_file = paper filepath = 'static/encrypted_files' output_file = os.path.join(filepath,str(paper)+'.encrypted') data = input_file.read() fernet = Fernet(key) encrypted = fernet.encrypt(data) with open(output_file, 'wb') as f: f.write(encrypted) data_1 = open(output_file,'r') return [key,data_1] views.py paper = request.FILES.get('paper',None) content = encrypt_file(paper) queryset, created = Request.objects.update_or_create(tusername=request.user.username,defaults = {'paper':content[1],'status':'Uploaded','key':content[0]}) models.py paper = models.FileField(storage=InterPlanetaryFileSystemStorage()) -
What Should I learn after completion of django?
I have learnt django and django rest api. After completion of django should I go for React or numpy,pandas? -
Django-mail-queue does not attach file on Centos 7
I have been trying to attached and PDF file to Django-mail-queue. But seem it does not working on centos 7. On local (MacOS) is working well. I've tried to chmod the folder and file to 777 permissions, but that fails, too. This is what I tried: class TestSendMail(View): def get(self, request): send_mail_queue( settings.SERVICE_INVOICE_MAIL_TILE, '<p>Hello</>', 'it48thwru@gmail.com', [os.path.join(settings.BASE_DIR, 'test.pdf')] ) return render(request, 'frontend/pages/test_send_mail.html') def send_mail_queue(subject, html_content, to_address, files=None): from mailqueue.models import MailerMessage try: new_message = MailerMessage() new_message.subject = subject new_message.to_address = to_address new_message.from_address = settings.DEFAULT_FROM_EMAIL new_message.html_content = html_content if files: # add attach file for file in files: attach_file = File(open(file, "rb")) new_message.add_attachment(attach_file) new_message.save() except Exception as ex: import logging logger = logging.getLogger(__name__) logger.error(ex) pass How can I fix that? Thanks! -
Shared volume between Jobs ~ Gitlab Shared Runners
I am running a Gitlab pipeline on a Django + Postgres project and I am trying to build and then run my tests inside my gitlab pipeline. I am using a custom docker image in order to use docker-compose in my pipeline. I have 2 seperate jobs : build and test but the problem is by default jobs environments are not shared, so after my first build job I can't simple run my test with docker-compose exec -it app python manage.py run test How can I achieve this without having to relauch a build in my second job for my tests ? -
Marked library is not working on django template
i'm trying to render html code in my django project using 'marked' but it does not work <p class=" content-markdown" >{{object.content }}</p> <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.7.0/marked.min.js"></script> <script type="txt/javascript"> $(document).ready(function(){ $(".content-markdown").each(function(){ var content = $(this).text() console.log(content) var marked = marked(content) console.log(marked) $(this).html(marked) }) }) </script> -
how to access radio button selected value in Django
I am trying to access radio button selected value in my django view but it returns on instead of selected value. Template form <form class="col-md-8 mx-auto" action="upload" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group" id="div_id_sample" > <label for="id_sample" class="col-form-label requiredField">Select File</label><br> <div class="btn btn-primary"> <input type="file" name="sample" class="clearablefileinput" required id="id_sample" accept=".exe"> </div> </div> <div class="form-group"> <label for="radiogroup">Enforce Timeout</label><br> <div class="btn-group" data-toggle="buttons" id="radiogroup"> <label class="btn btn-secondary"> <input type="radio" name="timeoptions" id="option60" autocomplete="off" value="60"> 60 seconds </label> <label class="btn btn-secondary"> <input type="radio" name="timeoptions" id="option120" autocomplete="off" value="120"> 120 seconds </label> <label class="btn btn-secondary active"> <input type="radio" name="timeoptions" id="option180" autocomplete="off" checked value="180"> 180 seconds </label> </div> </div> <div class="form-group"> <label for="radiogroup2">Select Machine:</label><br> <div class="btn-group" data-toggle="buttons" id="radiogroup2"> <label class="btn btn-secondary"> <input type="radio" name="machineoptions" id="machine1" autocomplete="off" value="0"> Windows XP </label> <label class="btn btn-secondary active"> <input type="radio" name="machineoptions" id="machine2" autocomplete="off" value="1" checked> Windows 7 </label> </div> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> views.py in my views i am using ModelForm but not in my HTML and the reason behind that is i copied and pasted the htmlcode generated by the ModelForm. Reason is because i need to collect two more items that are not in my data MODEL so that why. def upload(request): if request.user.is_authenticated: if request.method == … -
Data not being saved to database with django forms
I am working on a django application, which contains a form. I defined the model and made the migrations. But the data is not being saved into the database. And the URL for the application gets messed up when I use submit the form. This is my code so far models.py class modelPost(models.Model): name = models.CharField(max_length=200) email = models.EmailField(max_length=70) phone = models.CharField(max_length=12) def publish(self): self.save() def __str__(self): return self.name forms.py from .models import modelPost class testForm(forms.ModelForm): class Meta: model = modelPost fields = ('name', 'email', 'phone') views.py from .forms import testForm # Create your views here. def index(request): if request.method == "POST": testForm = testForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('home') else: testForm = testForm() return render(request, 'index.html', {'testForm': testForm}) index.html <form> {% csrf_token %} {{ testForm.name|as_crispy_field }} {{ testForm.email|as_crispy_field }} {{ testForm.phone|as_crispy_field }} <input type="submit" value="check" class="save btn submit_button"> </form> when I try to submit the form, this happens to the url http://127.0.0.1:8000/?csrfmiddlewaretoken=BG2i7fSbwG1d1cOlLWcEzy5ZQgsNYzMrhDJRarXkR3JyhetpWvqNV48ExY7xM9EW&name=randomPerson&email=test%40test.com&phone=12345678 These are some links that I checked, but the answers dont work link1 link2 -
How to force pip to install last version of django?
There are have many versions of python on my ubuntu. I have set the default version for python command to 3.7 using alias. I have created a virtual env using virtualenvwrapper and want to install django on this virtual. After activating this virtual if I type python command, version 3.7 runs. But if I type 'pip install Django' the old version 1.13 which is related to python 2.7 is installed. I have tried to use 'pip install Django==2.2.6' but no success. It says: DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support How can I force pip to install version related to python 3.7? -
How can I create a python console in VS Code that includes django app settings?
I got a little bit used to how PyCharm Professional works but I like Visual Studio Code way more, I like the Python console of PyCharm, which automatically includes things like DJANGO_SETTINGS_MODULE. Is there a way to achieve something similar in Visual Studio Code? -
Bootstrap_form inherit the types from the model
I’m new to Django and bootstrap, so apologies if this is a very basic issue. I’ve defined my model, created my (CreateView) view and am using {% bootstrap_form form %}. It displays nicely, but the field are all the same length on screen and don’t size to the definition in the model (I.e, a date field is much longer than defined in the model). How can I get my form to inherit the size/ width defined in the model? -
Django temporary fields only upon creation
Consider two models: Contract class Contract(models.Model): employee = models.OneToOneField(Employee, on_delete=models.CASCADE) contract_type = models.ForeignKey(ContractType, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() and Employee class Employee(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) contract = models.OneToOneField(Contract, on_delete=models.CASCADE, null=True, blank=True) I was wondering if there's a way to add temporary fields in a model form that are only shown upon creation in the Employee model so I can add all those fields while I create a new Employee then when saving, I first create an Employee object, then automatically generate a Contract object and edit the original Employee object and link the now generated Contract object. I really hope this makes sense, and if it does, can someone guide me in the right direction? Thank you, for your time reading this. -
Creating professional user registration with Django rest framework
I am trying to create a good professional user registration and authentication for a personal project I am building, that sends emails to authenticate users’ email. Because it’s a REST API I am building, I searched for solutions and I found out about Django-rest-auth which depends on Django-all auth. For some reason, it still hasn’t been able to work out for me. -
Creating unique identifiers for urls
I'm currently trying to develop an application. I am using Django framework for my backend. Now in my app I will show stuff like posts or pictures. Initially I just used the primary key to display inside the urls. I was told that this wasn't so good because it reveals too much information to a potential attacker. Instead I should use uuid. I read into uuid and now realised that they are very handy. Also I read in some posts also here on SO that uuid may not have enough randomness and could be guessable. A solid alternative would be to use the secrets module from python. Since I'm not experienced enough to make a good assessement I'm reaching out to more experienced developers. Would you just stick with uuid and maybe shorten it or go with the secrets module of python. Please note that as of now I won't be using the id for anything else than uniquely identifying an object. Is it okay to use uuids of 32 characters length? The url will get kind of long. -
changing from address on send_mail
I've hooked in Gsuite as my SMTP server. It sends out emails and it works very well. However, when using the send_mail function in django, I want to indicate a from address other than the email address that I have hooked into Gsuite, which is admin@mywebsite.com. subject = 'Order Confirmation' from_email = "jim@gmail.com" to_email = ("james@gmail.com",) txt_message = "some text" html_message = "some other text" send_mail(subject, txt_message, from_email, to_email, html_message=html_message, fail_silently=False, auth_user="admin@mywebsite.com", auth_password="PASSWORD" ) When an email is sent out with this code, when I look at the resulting email email in the email client of james@gmail.com, the "from" address is admin@mywebsite.com rather than jim@gmail.com. Is there a way that I can change this so that the 'from' is jim@gmail.com or at least the 'reply-to' is jim@gmail.com? Thanks for your help! -
How can I create object of the extended model of User on Django
I'm writing the API for my project. There I have model of user extended by the Profile model. I don't know how to make registration. I should get email, login, password and judge_id by json and create user and profile using this data. I wrote Profile model and serialisers for User and Profile(I'm not really sure how should transfer User to the user field). But how should I write registration in my views (as I understand there I should use serialisers)? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) judge_id = models.CharField(max_length=30) completed_tasks = models.ManyToManyField(Task, related_name="compl+") wa_tasks = models.ManyToManyField(Task, related_name="wa+") todo_tasks = models.ManyToManyField(Task, related_name="todo+") notes = models.ManyToManyField(Note) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User( email=validated_data['email'], username=validated_data['username']) user.set_password(validated_data['password']) user.save() return user class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' def create(self, validated_data): profile = User( judge_id=validated_data['judge_id'], user=validated_data['user']) profile.set_password(validated_data['password']) profile.save() return profile -
Cannot resolve keyword 'name' into field. Choices are: ab_price, amazon_price, desc, fk_price, id, is_avl, launch_date,
I am getting this error but, I don't have name in my ORM class, i was expecting it to be fine. before this, I had changed the name field to p_model and now name is nowhere in the code models.py class Product(models.Model): p_model = models.CharField(max_length=200, verbose_name='Model') desc = models.CharField(max_length=200, verbose_name='Description') launch_date = models.DateField(verbose_name='Launch Date') amazon_price = models.FloatField(verbose_name='Amazon Price') fk_price = models.FloatField(verbose_name='Flipkart Price') sd_price = models.FloatField(verbose_name='SnapDeal Price') ab_price = models.FloatField(verbose_name='Alibaba Price') is_avl = models.BooleanField(default=False, verbose_name='In Stock') views.py def addproduct(request): if request.method == 'POST': form = Addproduct(request.POST) if form.is_valid(): form.save() usrn = request.user.username wall = wallet.objects.get(username=usrn) bal = wall.Balance wallet.objects.update(username=usrn, Balance=bal + 5) newbal = get_bal(request) messages.success(request, f'Product has been added successfully, Your current wallet Balance is {newbal} try ' f'adding more') return redirect('addproduct') else: return HttpResponse("Invalid Data") else: form = Addproduct() bal = get_bal(request) usrn = request.user.username return render(request, 'register/addproduct.html', {'form': form, 'bal': bal, 'usr': usrn}) forms.py class Addproduct(forms.ModelForm): class Meta: model = Product fields = ('__all__') ''' -
Django: How to use views&forms of an app in main templates?
I'm using edge repo for quick starting a django project. The repo has an app called "accounts" which handles signin up, logging in, etc with crispy forms. However i'd like to allow users to sign up from the home.html which isn't located in accounts/templates. I have tried adding the following code to home.html: {% if not user.is_authenticated %} {% include "signup.html" %} {% include "auth_base.html" %} {% block form %} {% crispy form %} <div class="form-message"> <p> Already signed up? <a href="{% url 'accounts:login' %}">Log in</a>. </p> </div> {% endblock form %} {% endif %} However since the main views.py can't locate views/forms in account app i'm faced with the following error: django.template.base.VariableDoesNotExist: Failed lookup for key [form] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'view': <my_env.views.HomePage object at 0x7f0ed11cec88>}] My project files are the same as here with only "project_name" being different. I expected to be able to use the signup form in home.html. Can anyone point me the right way?