Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authentication Required error when sending email with Django
I'm trying to send a password-reset email using gmail server but I'am getting an error. 'SMTPSenderRefused Authentication Required' The google account have - 1. 2-Step Verification on 2. Third-party access through app password 3. Access allowed for less secure app : On ''' setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') #my gmail acc EMAIL_PASSWORD = os.environ.get('EMAIL_PASSWORD') #app password from gmail acc EMAIL_PORT = 587 ''' ''' urls.py path('password-reset/', PasswordResetView.as_view( template_name='users/password-reset.html'), name='password_reset'), path('password-reset-done/', PasswordResetDoneView.as_view( template_name='users/password-reset-done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), ''' I expect an email with a reset-password-link send to the user or whomever POSTed their email when prompted but what i get is this error - ''' SMTPSenderRefused at /password-reset/ (530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError p17sm3671371wrq.95 - gsmtp', 'webmaster@localhost') ''' -
How to enforce web browser to track user location through django?
I want to deny access users to my web application when they are not in the company area ,so I can to enforce web browser to track the user location through django? -
How can I filter foreignkeys in models?
I have created two models, Porumbei and Perechi. Porumbei means pigeon and it can be male or female, they live in pairs(Perechi). My models below(part of it) class Porumbei(models.Model): .... serie_inel = models.CharField(....) sex = models.ForeignKey(Gender, on_delete=models.CASCADE) .... class Perechi(models.Model): .... mascul = models.ForeignKey(Porumbei, on_delete=models.CASCADE) femela = models.ForeignKey(Porumbei, on_delete=models.CASCADE) When I create a new Perechi(pair), the field mascul I want to be sorted with all male in Porumbei(pigeons) and once it has been added to pairs, the next time when adding pairs that male to be excluded from list because it already have pair. The same with female. How can I implement this? -
django registration redux, remove email activation
I simply don't want this feature. I don't want the users to login to their email just to sign in. However I see this feature is default: ACCOUNT_ACTIVATION_DAYS I'm not sure how to remove this feature. I googled around and I can create backends.py and modify. but I'm not sure. Has anyone experienced this? -
Django passing an argument from method to method
The problem is that I have a basket, which is saved in the session and after the successfully created order this session / basket is completely cleared. And the basket has a method that returns the amount of goods and after clearing the basket of goods it returns 0, which is logical, but I need to save the amount to a variable and pass this variable to the second method, which accepts the customer’s order ID, without changing the url, that is, I want so that in url there was only an identifier, but not an identifier + amount. I need to pass an argument from one method to another. Now I will show what I mean. views.py def order_create(request): cart = Cart(request) # session sum = cart.get_total_price() # the value of the sum is saved to the variable if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): # data storage cart.clear_session() # clear the session after a successful order return redirect(reverse('order:order_success', kwargs={'pk':order.id})) # how to pass here also the `sum` variable else: return HttpResponse('y') Pass order ID to order_success method def order_success(request, pk, sum): print(sum) # data processing and data page return urls.py url(r'^order/(?P<pk>[0-9A-Fa-f-]+)$', views.order_success, name='order_success'), How can you … -
Heroku + S3 AWS + Django != No Images
I tried to put my app online, but it seems that image files don't show up. Maybe you can help? I have required images in my bucket in S3 AWS, but still nothing appears. Although when I try to open the image on the webside I am sent to the amazon website. And tehn I get this message: InvalidRequest The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256. 8CF0C70490DEFEE2 dtBKlPBbw5L6pM6mGyd4YaqC4amay/c2tccfhhStjujVGG2qdrvQwD6vGloJZWQle9A5Cwr3Rws= Here is my settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_TMP = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' os.makedirs(STATIC_TMP, exist_ok=True) STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' AWS_ACCESS_KEY_ID = "####" AWS_SECRET_ACCESS_KEY="####" AWS_STORAGE_BUCKET_NAME="####" AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' django_heroku.settings(locals()) -
Django 2.2 user = models.ForeignKey(User, null=True, blank=True) TypeError: __init__() missing 1 required positional argument: 'on_delete'
I am trying to create a user object in my Cart class in my models.py file. And I am receiving the following error: user = models.ForeignKey(User, null=True, blank=True) TypeError: __init__() missing 1 required positional argument: 'on_delete' Can you help me add the required positional argument: on_delete in a proper way in oder to use the user object later while creating a cart session? Thanks in advance. In my models.py I have the following code: from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save, m2m_changed from products.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['card_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated: user_obj = user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) products = models.ManyToManyField(Product, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): if action … -
How do I get a value from this dictionary in my HTML template?
views http://puu.sh/DwJ4H/73165ab8fb.png template http://puu.sh/DwJgs/647951d8fd.png so in my playerData function I get a players last 20 matches and set it to r. last20matches is a list of 20 dictionaries. Now to the template. I'm going through every dictionary ( each dictionary is a match ) and I want to create a link to a page (https://www.dotabuff.com/matches/match_id). However, the match_id is in the dictionary with key match_id. How do I get this into my link in the html file? TemplateSyntaxError at /players/86725175/ Invalid block tag on line 20: 'int({{entry}})', expected 'empty' or 'endfor'. Did you forget to register or load this tag? -
Laravel/Valet and running WagTail or Django App
I am a php developer, primarily working with WordPress, and when working locally, I use Valet by Laravel. I recently started looking into working with Python and it's web framework Django. Starting a web project with one of it's CMS's, Wagtail, I can obviously run the command python manage.py runserver to start the webapp, but seeing as I also use Valet, I was wondering if there was a way to get Valet to recognize the appropriate files that python uses to run it's server. I've tried looking around a bit, but was unable to really find anything to fully answered what I am seeking. Reason why I wanna use Valet is because I am able to type in https://dir_name.app and have the browser serve it instead of http://127.0.0.1:8000 -
Django membership (choices 30, 90, 180 days) and it`s logic
There are 3 choices of memberships,1 3 and 6 months. I`ve written for 1 month, but problem to write logic which depends on the choices. It works well with 1 month, but: membership_choices =( ('1', '1 month'), ('3', '3 months'), ('6', 'half an year'), ) class Membership(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) types = models.CharField(max_length=1, choices=membership_choices) end = models.DateTimeField(default=datetime.today()+timedelta(days=30)) The problem is to write in this model something like this: if types == 3: datetime.today() + timedelta(days=90) elif types == 6: datetime.today() + timedelta(days=180) -
Best way to build a form aggregate data
I'm learning Django and I would like to know what is the best way ( if possible) to represent the formset where each row/form is an aggregation of data from different models ( A, B, C, D ), example: A --> B C --> B & D I would like to do have a form like : row1 = info_A, info_A1, info_B, info_D row2 = info_A, info_A1, info_B, info_D etc... Given a A primary_key, I get back a B Id which I can link to a D object via C. What is the best way to achieve that result ? -
Django manager with datetime.timedelta object inside F query combined with annotate and filter
I am trying to create manager method inside my app, to filter emails object, that have been created 5/10/15 minutes or what so ever, counting exactly from now. I though I'am gonna use annotate to create new parameter, which will be bool and his state depends on simple subtraction with division and checking if the result is bigger than 0. from django.db.models import F from django.utils import timezone delta = 60 * 1 * 5 current_date = timezone.now() qs = self.annotate(passed=((current_date - F('created_at')).seconds // delta > 0)).filter(passed=True) Atm my error says: AttributeError: 'CombinedExpression' object has no attribute 'seconds' It is clearly caused, that ((current_date - F('created_at')) does not evaluate to datetime.timedelta object but to the CombinedExpression object. I see more problems out there, i.e. how to compare the expression to 0? Anyway, would appreciate any tips if I am somewhere close to achieve my goal or is my entire logic behind this query incorrect -
How can I create database in the project folder in Django?
I have a very simple website in Django for which I do not want to create an app separately for the purpose. So the models and admin.py file does not come while creating the django project. When we create an app, those files are automatically created which we have to register in Setting.py. But my project is very short and I do not want to create an extra app for the purpose. Is there any way to create those database model in the project folder itself? What I tried : 1. created a models.py file : wrote my database model in it 2. also created an admin.py file and registered the database model 3. In the setting.py file added the project folder itself But that does not seem to work because when I am trying to create migration its displaying me no changes detected. -
NameError: name 'CityForm' is not defined
i m trying to get temperature of cities entered by user from django.shortcuts import render import requests from .models import City def index(request): cities = City.objects.all() #return all the cities in the database url = 'http://api.openweathermap.org/data/2.5/weather?q= {}&units=imperial&appid=ec2052730c7fdc28b89a0fbfe8560346' if request.method == 'POST': # only true if form is submitted form = CityForm(request.POST) # add actual request data to form for processing form.save() # will validate and save if validate form = CityForm() weather_data = [] for city in cities: city_weather = requests.get(url.format(city)).json() #request the API data and convert the JSON to Python data types weather = { 'city' : city, 'temperature' : city_weather['main']['temp'], 'description' : city_weather['weather'][0]['description'], 'icon' : city_weather['weather'][0]['icon'] } weather_data.append(weather) #add the data for the current city into our list context = {'weather_data' : weather_data, 'form' : form} return render(request, 'weathers/index.html', context) Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Admin\Desktop\the_weather\weathers\views.py", line 14, in index form = CityForm() NameError: name 'CityForm' is not defined [24/May/2019 10:35:31] "GET / HTTP/1.1" 500 64667 -
Why can not I submit a double form to the database
I created a form view and when I want to save a form with two modules I see "IntegrityError". Please help, Thank you in advance class Place(models.Model): LocalName = models.CharField('Nazwa Lokalu', max_length=200) slug = models.SlugField('Link', max_length=100, default="") LocalImg = models.ImageField('Zdjęcie Lokalu', upload_to='Place/static/locals/img', blank=True, max_length=20000) LocalAdress = models.CharField('Adres', max_length=500) LocalNumberPhone = models.CharField('Numer telefonu', max_length=9) LocalHours = models.TextField(verbose_name='Godziny otwarcia', max_length=20000) def get_aboslute_url(self): return reverse("place:place_create", kwargs={'id': self.id}) class Meta: verbose_name = "Lokal" verbose_name_plural = "Lokale" def __str__(self): return self.LocalName class Menu(models.Model): place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name="place", default="") Dinner = models.CharField("Nazwa potrawy",blank=True, default="", max_length=200) DinnerComponents = models.CharField("Składniki",blank=True, default="", max_length=20009) PizzaPrice = models.CharField("Rozmiar i cena Pizzy", help_text="np.Mała-10zł", default="", blank=True, max_length=300) Price = models.DecimalField("Cena",default="00", max_digits=5, decimal_places=2) class Meta: verbose_name = "Menu" verbose_name_plural = "Menu" Forms.py def create_place(request): form = PlaceForm() sub_form = MenuForm() if request.POST: form = PlaceForm(request.POST) sub_form = MenuForm(request.POST) if form.is_valid() and sub_form.is_valid(): place = form.save(commit=False) place.location = sub_form.save() place.save() context = { 'form': form, 'sub_form': sub_form } return render(request, 'posts/layout.html', context) Forms.py class PlaceForm(forms.ModelForm): class Meta: model = Place fields = ('LocalName', 'LocalAdress', 'LocalNumberPhone','LocalHours',) class MenuForm(forms.ModelForm): class Meta: model = Menu fields = ('Dinner','DinnerComponents','DinerCategory', 'Price',) After filling in the form and clicking submit, an error will appear "NOT NULL constraint failed: posts_menu.place_id" -
Error while inserting values in ti databse
When I try to put values in to databse, I am getting this error. raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.name, kwarg)) TypeError: Employee() got an unexpected keyword argument 'EmployeeID' The code is as below: class Employee (models.Model): EmployeeID = models.IntegerField EmployeeFirstName = models.CharField(max_length=100) EmployeeLastName = models.CharField(max_length=100) EmployeeEmail = models.CharField(max_length=100) EmployeeMobileNumber = models.IntegerField EmployeeHireDate = models.DateField EmployeeType = models.CharField(max_length=50) -
Multiple databases with Django
I have about 6 target databases with their own Django admin data and application data. Right now, I am running 6 instances of the same Django application on different hosts. What I would like to do is run one instance of the app, but up front have the user select which database he wishes to connect. Where should I inject this new code so that it hits BEFORE it tries to read the Django.core admin code? -
How to access media file's URL from within template?
This question regards development server. I have an audio file audio1.wav sitting in my MEDIA_ROOT/audio folder. How can I attach such element to an <audio> tag in the template? <audio src="?"></audio> Do I need to construct an absolute URL for the file like http://127.0.0.1:8000/media/audio/audio1.wav (given MEDIA_URL is set to /media/)? If so, how? Or perhaps there is a better way that will also cover for variable audio file name? -
BrowserSync: Proxy Subdomains
I have a Django app which serves multiple sites on separate subdomains. In development, I access the sites on: www.myapp.local:8000 data.myapp.local:8000 publish.myapp.local:8000 admin.myapp.local:8000 Note this works using the django_hosts library and through modifying /etc/hosts file, e.g: 127.0.0.1 www.myapp.local 127.0.0.1 data.myapp.local 127.0.0.1 publish.myapp.local 127.0.0.1 admin.myapp.local However, I am unable to figure out how to configure BrowserSync, in my Gulp-based workflow, in order to proxy all subdomains, providing a seamless experience as I navigate around the sites, and reload the browser as I develop. Configuring BrowserSync to proxy the main site, e.g. browserSync.init( [paths.css + "/*.css", paths.js + "*.js", paths.templates + '/**/*.html'], { proxy: 'www.myapp.local:8000' }) only 'captures' the main site, if you click a link to one of the subdomains, you navigate out of the BrowserSync session and will be served directly by Django on port 8000. -
How do I reverse match url using TimestampSigner in Django?
To register users in my Django web application I've created functionality which sends out a cryptographically signed link to already verified email addresses, which lets them access the user registration page. The next step is now to make sure the link expires after a set amount of time, but this turns out to be harder than expected. Through this, I've been using the built-in Django Signer function, and now the idea is to convert this to the TimestampSigner function instead. To do this, I've read and followed the: https://docs.djangoproject.com/en/2.2/topics/signing/#verifying-timestamped-values Here is my code: in models.py: class GenerateUserRegistration(models.Model): signer = TimestampSigner(sep='/', salt='users.GenerateUserRegistration') def get_registration_url(self, pk): signed_pk = self.signer.sign(pk) domain = Site.objects.get_current().domain path = str(reverse('register', kwargs={'signed_pk': signed_pk})) registration_url = 'http://{domain}{path}'.format(domain=domain, path=path) return registration_url in views.py: def register(request, signed_pk): try: pk = GenerateUserRegistration.signer.unsign(signed_pk, max_age=30) confirmed = Program.objects.get(id=pk) except (BadSignature, GenerateUserRegistration.DoesNotExist): raise Http404(signed_pk) def generate_user_registration_email(request): ... UserGenerator = GenerateUserRegistration() user_registration_url = UserGenerator.get_registration_url(pk) send_mail('app specific data') ... in urls.py: urlpatterns = [ ... re_path(r'register/(?P<signed_pk>[0-9]+/[A-Za-z0-9_=-]+)/$', user_views.register,name='register'), ... When running the program with the TimestampSigner instead of the Signer (where it works just like expected), it throws me the following error: "NoReverseMatch at /admin/generate-user-registration Reverse for 'register' with keyword arguments '{'signed_pk': '1/1hUBvf/3EiPZDorfNCqovGyDjoO--9oyTQ'}' not found. 1 pattern(s) tried: … -
Convert and sort nested dict to list
How to convert and sort below nested dict data = { 'Item2': {'weight': 200, 'parent': 'root'}, 'Item1': {'weight': 100, 'parent': 'root'}, 'SubItem1': {'weight': 100, 'parent': 'Item1'}, 'SubItem1.3': {'weight': 300, 'parent': 'SubItem1'}, 'SubItem1.2': {'weight': 200, 'parent': 'SubItem1'}, 'SubItem1.1': {'weight': 100, 'parent': 'SubItem1'} } to list <ul> <li>Item1 <ul> <li>SubItem1 <ul> <li>SubItem1.1</li> <li>SubItem1.2</li> <li>SubItem1.3</li> </ul> </li> </ul> </li> <li>Item2</li> </ul> I suppose I should use recursion but to do it I did not get. -
Updating div with a unique id in a for loop using jquery in Django
I am creating a website that allows users to search for a list of papers. Once a list of papers is returned, the user can click "like" or "dislike" to one or more papers. The like count should dynamically update as the user click the like button. I am using jquery to handle the dynamic update of the like count. However, I am not sure how to tell the success function in the ajax WHICH id to update. The reason is that the id is generated on the fly, and it is determined by which papers are returned as search results to the user. So far, I have the following in the template: {% for result in results %} <li > {{ result.title}}, <a href="#" class="like_button" data-pid="{{ result.pk }}"> <span class="like_span fa fa-thumbs-up"></span> </a> <strong id="like_count_{{ result.pk }}">{{result.likes}} </strong> </li> {% endfor %} As you can see, i specify the id of the part where I want the dynamic update to happen as "like_count_{{ result.pk }}". I am not sure if this is the best way to go about it. The jquery part looks like this: <script> $(document).ready(function(){ $(".like_button").click(function(){ $.ajax({ type: "GET", data: {'pk': $(this).data('pid'), 'liked': $("span").hasClass('fa fa-thumbs-up') }, url: … -
Django-tinymce static files are not loading, but all other static files are on Amazon S3
I've been using this guide https://www.codingforentrepreneurs.com/blog/s3-static-media-files-for-django/ to get to use S3 for my site's static files. I had TinyMCE working locally, but once I started using S3 to for my files it's the only part that won't load and the widgets that use it simply don't appear. In the Chrome Dev Tools console, I am getting the following error: GET https://conucos-bucket.s3.amazonaws.com/static/assets/js/tiny_mce/plugins/ autosave/editor_plugin.js? AWSAccessKeyId=[ACCESKEY]&Signature=CfhFC2OzRlAnr929E8avUr3UiwM%3D& Expires=1558712746 net::ERR_ABORTED 403 (Forbidden) Failed to load: https://conucos-bucket.s3.amazonaws.com/static/assets/js/tiny_mce/plugins/wordcount/editor_plugin.js And the error appears tons of times for each component that isn't loading On S3 I've made all files public in the Bucket Public and get Access Denied for 2 files in TinyMCE static/assets/js/tiny_mce/plugins/media/langs/dv_dlg.js /conucos-bucket/ static/assets/js/tiny_mce/plugins/searchreplace/langs/mk_dlg.js /conucos-bucket/ And the rest are successful. What should I do so that the widget appears? Since it loads locally when not using S3 I imagine it's an S3 error, but don't know where to begin since it's my first time using it. -
django 2.1.7 template does not exist
Image of Project Can someone help me with add template from app. Just tell me where i must put path to template and what is path to template in the app. -
How to get Primary Key and data from Django SessionWizardView
I have a SessionWizardView that generate 3 forms, depending of of a previous choice. After the selection of the form, the user fill the form and submit it to a specific ListView to each case, using POST. The problem are to get these values, mainly the Primary Key. The SessionWizardView, I followed the documentation (https://django-formtools.readthedocs.io/en/stable/wizard.html#wizard-template-for-each-form) and it's working as I expected. The 3 forms has the last field pre filled, depending from the first field. In the ListView, I've tried to use request.session.pop() to get the fields from the SessionWizardView. Here I had my first doubt: I used either the variable name in the forms.py (e.g.:request.session.pop('formField1', {})), and the field id in the POST (request.session.pop('opcao1-formField1', {})). In both cases the browser return the 'int' object has no attribute 'pk' error. I've tested the 3 forms that the Wizard can show me and all of them show the same error, so I will put the code for the first one, so text stay short. urls.py: logger = logging.getLogger(__name__) urlpatterns = [ # path('', views.IndexView.as_view(), name="index"), path('', views.IndexView.as_view(views.FORMS), name="index"), path('detail/', views.DetailView.as_view(), name="detail"), views.py: class IndexView(SessionWizardView): condition_dict = {"opcao1" : graficoEscolhido1, "opcao2" : graficoEscolhido2, "opcao3" : graficoEscolhido3, } template_name = 'solid/index.html' success_url = …