Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Method POST not allowed [DRF]
This is my User Model class User(AbstractBaseUser, PermissionsMixin, Base): user_id = models.AutoField(primary_key=True) email = models.EmailField(db_index=True, max_length=100, unique=True) is_advisor = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) And this is my UserProfile class UserProfile(Base): profile_id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile') first_name = models.CharField(null=True, blank=True, max_length=100) last_name = models.CharField(null=True, blank=True, max_length=100) This is my UserProfileSerializer class UserProfileSerializer: class Meta: model = UserProfile fields = "__all__" And this is my view class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all() parser_classes = (MultiPartParser, ) serializer_class = UserProfileSerializer lookup_field = 'user' This is my urls.py router = SimpleRouter(trailing_slash=False) router.register(r'user', UserViewSet) router.register(r'user/profile', UserProfileViewSet) urlpatterns = [ path(r'user/activate', ActivateUser.as_view(), name='activate_user'), ] + router.urls When I try to create an User using the url http://localhost:8000/api/user/profile/2 I get detail : Method POST not allowed What am i doing wrong here? Any help appreciated. -
The .mp3 file that generated by AWS Polly does not run at all
I have made a rest API using Django Rest Framework. I gonna convert a sentence to speech using AWS Polly and tried to run it in my local environment. When I run the endpoint, a .mp3 file has generated in the root folder. The result message says "save success!". But the file does not work as well the file contains the size. I am hearing nothing. As actually the result file should work by Media player. I followed the AWS Polly article, [here][1] Class: class TexttoSpeechView(CreateAPIView): serializer_class = TexttoSpeechSerializer permission_classes = (IsAccessedUser,) def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): text = serializer.data.get('text') voice = "Mizuki" response = use_polly(text) if "AudioStream" in response: # Note: Closing the stream is important because the service throttles on the # number of parallel connections. Here we are using contextlib.closing to # ensure the close method of the stream object will be called automatically # at the end of the with statement's scope. with closing(response["AudioStream"]) as stream: output = os.path.join(BASE_DIR, "speech.mp3") data = stream.read() try: # Open a file for writing the output as a binary stream with open(output, "wb") as file: file.write(data) print("save success") except IOError as error: # Could not … -
How to restart a Django project after terminal shut down
I've been learning Django from a Youtube Tutorial. I have a good basis in python, but have never worked with this. we have been starting an app and ran a server with "python3 manage.py runserver" command. Everything was working fine. problem is that terminal shut down, and i have no idea how to just restart the server. I go to the same directory as we did the first time, activate my virtual environment, but when I type the runserver command, i face this error: ModuleNotFoundError: No module named 'main' I have no clue how to solve this. Any advice ? Thanks ! -
Django - 'AssertionError: .accepted_renderer not set on Response' on DRF endpoint with Middleware
So I wanted to create Middleware to add authentication to every endpoint automatically. It seems to be creating issues for Django Rest Framework endpoints using @api_view decorator. Whenever I run my unit tests for the below endpoint I get "AssertionError: .accepted_renderer not set on Response." How do I fix this so that my middlware works on both APIView classes and endpoints with @api_view decorator? View.py @api_view(['GET']) @swagger_auto_schema( operation_description="Get <count> most recent posts by category" ) def get_most_recent_posts_by_category(request, category, count): return Response(status=status.HTTP_200_OK) Middleware from datetime import datetime from rest_framework import status from rest_framework.response import Response from cheers.core.api.jwt_helpers import decode_cognito_jwt class CognitoMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): auth = request.headers.get("Authorization", None) if not auth: return Response(dict(error='Authorization header expected'), status=status.HTTP_401_UNAUTHORIZED) parts = auth.split() if parts[0].lower() != "bearer": return Response(dict(error='Authorization header must start with bearer'), status=status.HTTP_401_UNAUTHORIZED) elif len(parts) == 1: return Response(dict(error='Token not found'), status=status.HTTP_401_UNAUTHORIZED) elif len(parts) > 2: return Response(dict(error='Authorization header must be Bearer token'), status=status.HTTP_401_UNAUTHORIZED) token = parts[1] try: res = decode_cognito_jwt(token) expiration = datetime.utcfromtimestamp(res['exp']) current_utc = datetime.utcnow() if current_utc > expiration: return Response(dict(error=f'current time:{current_utc} is after expiration:{expiration}', user_msg='Please login again'), status=status.HTTP_400_BAD_REQUEST) except Exception: # Fail if invalid return Response(dict(error="Invalid … -
TypeError: %i format: a number is required, not str (python, phonenumbers)
I'm trying to use phonenumbers, but how do I throw an exception so that it gets posted back to the post form? gives an error % i format: a number is required, not str instead of showing it as an error about incorrect filling in the form on the site models.py import phonenumbers def validate_phone_number(value): try: z = phonenumbers.parse(value, None) except phonenumbers.NumberParseException: print('NOT VALID 0') raise ValidationError(_('%(value) is not a valid phone number'), params={'value': value},) if not phonenumbers.is_valid_number(z): print('NOT VALID') raise ValidationError( _('%(value) is not a valid phone number'), params={'value': value}, ) class Storehouses(models.Model): phone = models.CharField(validators=[validate_phone_number], unique=True, max_length=17) views.py class StorehouseSettingsAddView(TemplateView): template_name = 'storehouse/settings/storehouse_settings_add.html' def get(self, request, *args, **kwargs): # get work good ... def post(self, request, *args, **kwargs): formOne = StorehouseAddCategoryForm(self.request.POST, prefix='one_form') if formOne.is_valid(): form_one = formOne.save(commit=False) form_one.save() return HttpResponseRedirect(reverse_lazy('storehouse_settings_add')) else: print('NotValid') context = self.get_context_data() formOne.prefix = 'one_form' context.update({'formOne': formOne}) return self.render_to_response(context) #error here gets to return self.render_to_response (context) but throws an error -
Group by date in Django
I am trying to achieve the result the SQL query SELECT UNIX_TIMESTAMP(DATE((FROM_UNIXTIME(`timestamp`)))) AS `x`, COUNT(`timestamp`) as y FROM somedb.events WHERE user_id=3 AND `timestamp` > 1612117800 AND `timestamp` < 1614450600 AND `kind`='food' GROUP BY `x` ORDER BY `x` desc; using Django ORM. Expected output: [ { "x": 1613759400, "y": 2 }, { "x": 1612463400, "y": 1 } ] Here is what I tried so far: queryset = events.objects.filter( user=request.user, timestamp__range=dates, kind=self.model.FOOD ) result = queryset.annotate( trunc_date_timestamp=Func(Value( TruncDate( Func( F('timestamp'), function='FROM_UNIXTIME', ) )), function='UNIX_TIMESTAMP', output_field=models.IntegerField() ) ).values(x=F('trunc_date_timestamp')).annotate(y=models.Count('x')).order_by('-x') This produces the output: [ { "x": 0, "y": 3 } ] and result = queryset.annotate( trunc_date_timestamp=Func( Func( F('timestamp'), function='FROM_UNIXTIME', output_field=models.DateField() ), function='UNIX_TIMESTAMP' ) ).values(x=F('trunc_date_timestamp')).annotate(y=models.Count('x')).order_by('-x') produces the output: [ { "x": 1613831760, "y": 1 }, { "x": 1613810160, "y": 1 }, { "x": 1612520520, "y": 1 } ] -
How to make API endpoints for stepwise continuous upload use case?
I have a good experience with Android Frontend REST API calls, but I am very new to Backend and learning Django Framework so I need help for designing the below API endpoints. For better understanding I have uploaded a video over here https://youtu.be/z87Hz1uHrYY. This is the solution which I was thinking of doing, ) HTTP-Method: POST EndPoint URL: /recipe/ Request Params: {"name":"Pizza"} "image": pizza.png Response Params: {"id":"123xyz"} // unique id ) HTTP-Method PATCH EndPoint URL: /recipe/123xyz/ Request Params: {"serving":2, "difficulty": "m", "prep_time": 80} Response Params: {"id":"123xyz", "serving":2, "difficulty": "m", "prep_time": 80} ) HTTP-Method: PATCH EndPoint URL: /recipe/123xyz/ingredients/ Request Params: [{"ingredient":”rice”, “amount”: “1/2”, “unit”: “g”},{"ingredient":”water”, “amount”: “1/2”, “unit”: “ml”}] Response Params: {"id":"123xyz", "serving":2, "difficulty": "m", "prep_time": 80, “ingredients”: [{"ingredient":”rice”, “amount”: “1/2”, “unit”: “g”, “index”:1},{"ingredient":”water”, “amount”: “1/2”, “unit”: “ml”, “index”:2}] } ) HTTP-Method: PATCH EndPoint URL: /recipe/123xyz/steps/ Request Params: [{"description":”abc”, “image”: “s3//step1.png”, "index": 1},{"description":”xyz”, “video”: “s3//step2.mp4”, "index": 2}] Response Params: {"id":"123xyz", "serving":2, "difficulty": "m", "prep_time": 80, “ingredients”:[{"ingredient":”rice”, “amount”: “1/2”, “unit”: “g”, “index”:1},{"ingredient":”water”, “amount”: “1/2”, “unit”: “ml”, “index”:2}], "steps":[{"description":”abc”, “image”: “s3//step1.png”, "index": 1},{"description":”xyz”, “video”: “s3//step2.mp4”, "index": 2}]} These are the API breakdowns that I can think of with the questions below. ) How to handle reordering of ingredients and steps? ) When to … -
Django tinymce does not upload image in production
I have trouble uploading images in production mode with django tinymce. It does upload images in development mode but not in production. It Would be great if someone could me help me get this going. settings.py import os from pathlib import Path import json with open('/Users/omidsoroush/Desktop/config/config.json') as config_file: config = json.load(config_file) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config['SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', '49.12.203.203', 'www.example.org'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'blog.apps.BlogConfig', 'pytutorial.apps.PytutorialConfig', 'users.apps.UsersConfig', 'sendemail', 'crispy_forms', 'tinymce', ] 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', ] ROOT_URLCONF = 'pypro.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], '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 = 'pypro.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'pypro_db', 'USER': 'postgres', 'PASSWORD': config['DB_PASS'], 'HOST': 'localhost', 'PORT': '5432', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': … -
Create object if not exists in Django ImportExportModelAdmin
I have these two models: Profile_model.py class Profile(models.Model): firstname = models.CharField(max_length=200, blank=False) lastname = models.CharField(max_length=200, blank=False) email = models.CharField(max_length=200, unique=True, blank=False) ... Investment_model.py class Investment(models.Model): invested = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) ... and I have this admin: Investment_admin.py class InvestmentResource(resources.ModelResource): ... firstname = fields.Field(attribute='profile', widget=ForeignKeyWidget(Profile, field='firstname'), column_name='firstname') lastname = fields.Field(attribute='profile', widget=ForeignKeyWidget(Profile, field='lastname'), column_name='lastname') email = fields.Field(attribute='email', widget=ForeignKeyWidget(Profile, field='email'), column_name='email') class Meta: model = Investment fields = ( 'firstname', 'lastname', 'email', 'invested',) export_order = fields class InvestmentAdmin(ImportExportModelAdmin, admin.ModelAdmin): ... resource_class = InvestmentResource ... I am using django's ImportExportModelAdmin for bulk imports and exports but when I try to import, I get this error: I get that its producing this error because the profile hasn't been created yet. But what do I have to do to implement an update_or_create inside the ImportExportModelAdmin? -
The best way to catch IntegrityError on admin page?
I am trying to catch IntegrityError in admin.py file, but cannot do it properly. Is there a way at all? Note, that I use UniqueConstraint for my recipe model, since I do not want duplicated tags and ingredients. For many to many fields in my Recipe Admin model I've used inliners. IntegrityError is raised when I specially try to create a recipe with two identical tags. from recipes.models import ( Recipe, Ingredient, Tag, RecipeIngredient, RecipeTag ) from django.contrib import admin class RecipeIngredientInline(admin.TabularInline): model = Recipe.ingredients.through class RecipeTagInline(admin.TabularInline): model = Recipe.tags.through class RecipeAdmin(admin.ModelAdmin): search_fields = ('name',) readonly_fields=('total_favorites',) list_filter = ('tags',) inlines = (RecipeIngredientInline, RecipeTagInline) @admin.display(empty_value='---empty---') def total_favorites(self, obj): return obj.userrecipe_set.all().count() def save_model(self, request, obj, form, change): # Here I am trying to catch the exception, but without joy. breakpoint() super().save_model(request, obj, form, change) class IngredientAdmin(admin.ModelAdmin): search_fields = ('name',) list_filter = ('measurement_unit',) class TagAdmin(admin.ModelAdmin): search_fields = ('name',) list_filter = ('slug',) class RecipeIngredientAdmin(admin.ModelAdmin): search_fields = ('recipe__name',) class RecipeTagAdmin(admin.ModelAdmin): search_fields = ('recipe__name',) admin.site.register(Recipe, RecipeAdmin) admin.site.register(Ingredient, IngredientAdmin) admin.site.register(Tag, TagAdmin) admin.site.register(RecipeIngredient, RecipeIngredientAdmin) admin.site.register(RecipeTag, RecipeTagAdmin) -
Change image size with a input range value in Django
I'm trying to make a range field that whenever the user changes its value, it is inserted as the size of an image. {% extends "base.html" %} {% load i18n %} {% load static %} {% load crispy_forms_tags %} {% block conteudo %} <script> function updateTextInput() { var value = document.getElementById("range").value; var img = document.getElementById('imageRange'); img.style.height = value updateTextInput() } function SetSize(porte){ var tamanho; switch (porte){ case 'pequeno': tamanho = 40 break; case 'medio': tamanho = 80 break; case 'grande': tamanho = 120 break; } document.getElementById("range").value = tamanho; updateTextInput(); } </script> <! -- page content ... -- > <form enctype="multipart/form-data" action="submit", method="POST">{% csrf_token %} <input type="number" class="form-control" name="pet-id" value="{{ pet.id }}" hidden> <div class="container"> <div class="form-group"> <label><b>{% trans "Porte" %}</b>:</label><br> <button class="btn btn-primary" style="color:black; font-size:70%" onclick="SetSize('pequeno')" type="submit" value="Submit">Pequeno porte</button> <button class="btn btn-primary" style="color:black; font-size:70%" onclick="SetSize('medio')" type="submit" value="Submit">Médio porte</button> <button class="btn btn-primary" style="color:black; font-size:70%" onclick="SetSize('grande')" type="submit" value="Submit">Grande porte</button><br><br> <table class="fixed"> <tr> <td><img src="https://cdn.pixabay.com/photo/2018/03/30/13/04/silhouette-3275316_960_720.png" height="150" /></td> <td style="vertical-align:bottom"><img id="imageRange" src="https://image.flaticon.com/icons/png/512/91/91544.png" height="80" /></td> </tr> </table> <input class="form-range" style="width:30%" id="range" type="range" min="40" step="0" max="120" oninput="updateTextInput();" > </div> The code in an isolated file is working perfectly. However, when including it in a Django template, it doesn't work. I tested and the functions are being … -
Instantiating new form object doesn't give me a new form (Django)
This problem suddenly happened and I have no idea what I'm doing wrong. I have a function-based view. It checks if a form is posted, creates a new model object, and is supposed to return an empty form. Problem is when I do form = EventForm() and print the form, it prints a form with previous values when last submitted! from django.shortcuts import render from .forms import EventForm from .models import Event def home(request): if (request.method =='POST'): form = EventForm(request.POST) if form.is_valid(): form.save() event_list = [] events = Event.objects.all() for event in events: event_list.append({ 'title': event.title, 'start': event.date.strftime("%Y-%m-%d") }) form = EventForm() print(form) # previously filled form!! context = { 'form': form, 'events': event_list } return render(request, 'cal/calendar.html', context) This is what is being printed: <tr><th><label for="title_id">Title:</label></th><td><input type="text" name="title" class="form-control" placeholder="Enter event title" id="title_id" maxlength="200" required></td></tr> <tr><th><label for="date_id">Date:</label></th><td><input type="date" name="date" class="form-control" id="date_id" required></td></tr> <tr><th><label for="title_id">Title:</label></th><td><input type="text" name="title" class="form-control" placeholder="Enter event title" id="title_id" maxlength="200" required></td></tr> <tr><th><label for="date_id">Date:</label></th><td><input type="date" name="date" class="form-control" id="date_id" required></td></tr> -
Deploying django + graphql to AWS EC2 with Nginx
Hi I have an issue with Graphql url after deployment to EC2 using Nginx and gunicorn So locally everything is working I can access: http://127.0.0.1:8000/graphql When I deploy that to EC2 I'm getting an error 404 not found (ec2-.........compute.amazonaws.com/graphql) Django urls.py urlpatterns = [ path('admin/', admin.site.urls), path('graphql' , jwt_cookie(csrf_exempt(GraphQLView.as_view(schema=schema, graphiql=True)))), path('', index), re_path(r'^.*', index) ] Nginx/site-enable/django server { listen 80; server_name ec2-.........compute.amazonaws.com; location = /favicon.ico { access_log off; log_not_found off; } # main django application location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/project/run.sock; } location /static/ { autoindex on; alias /home/ubuntu/project/static/; } } Thanks in advance! -
How to exclude deleted records in a model save?
I am using django.contrib.postgres.field.DateRangeField in a model with an exclusion constraint to make sure 2 dateranges don't overlap: class MyModel(models.Model): date_range = DateRangeField() class Meta: constraints = [ ExclusionConstraint( name='exclude_overlapping_periods', expressions=[ ('date_range', RangeOperators.OVERLAPS), ], ), ] This works, but fails ugly with an integrityError (as it should). I want to validate the model with a clean method to make a user friendly response: def clean(self): error_dict = {} if MyModel.objects.exclude(id=self.id).filter( date_range__overlap=self.date_range): error_dict['date_range'] = ValidationError( 'Range can not overlap with an existing period.', code='overlap_period') if error_dict: raise ValidationError(error_dict) This works, but not in the instance when I use a formset and one instance is deleted at the same time another is updated. How can I accomodate this? -
allow page access only for admin user Django
So I need to allow page access only for admin user in Django, I'm trying this piece of code to use in app views.py, but its not working well.. from django.shortcuts import redirect def index(request): if not request.user.is_superuser: return redirect('https://xx.com') return render(request, 'scan_debug/index.html') -
Javascript - how to process argument within innerHTML iframe?
I have the following snipped at my Django HTML template: <script> function PlayTrack() { document.getElementById("iframeMusicPlayer").innerHTML = "<iframe src=\"{% url 'stream_audio' pk=track.file.pk|safe|cypher_link_stream %}\" height=\"250\" width=\"325\" ></iframe>"; } </script> <button type="button" class="btn" onclick="PlayTrack()"><i class="fal fa-play"></i></button> As you can see I have src="{% url 'stream_audio' pk=track.file.pk|safe|cypher_link_stream %}" set as src. But actually I want to have this as a argument like so (pseudo code): <script> function PlayTrack(track) { document.getElementById("iframeMusicPlayer").innerHTML = "<iframe src=\"$track\" height=\"250\" width=\"325\" ></iframe>"; } </script> <button type="button" class="btn" onclick="PlayTrack(track={% url 'stream_audio' pk=track.file.pk|safe|cypher_link_stream %})"><i class="fal fa-play"></i></button> How can I format my JS code so that I can simply pass the url as argument into the innerHTML iframe call? -
hello i need to create a auto increment invoice number
I need to create an auto increasing invoice number starting from 000001 and going up ex.000001, 000002, 000003 and so on right now i have this code that i took from another stack overflow question but i dont want the MAG part def increment_invoice_number(self): last_invoice = Transaction.objects.all().order_by('id').last() if not last_invoice: return 'MAG0001' invoice_no = last_invoice.invoice_no invoice_int = int(invoice_no.split('MAG')[-1]) new_invoice_int = invoice_int + 1 new_invoice_no = 'MAG' + str(new_invoice_int) return new_invoice_no invoice_no = models.CharField(max_length=500, default=increment_invoice_number, null=True, blank=True) i want my invoice num to start with 000001 -
How can I query a Postgres DateRange with a single date?
I am using django.contrib.postgres.field.DateRangeField as described [here][1]. class MyModel(models.Model): date_range = DateRangeField() How to I query this model to return all date_range with a lower bound greater than today? I tried: today = datetime.date.today() MyModel.objects.filter(date_range__gt=today) But this results in operator does not exist: daterange > date. -
djoser override reset password email with template
I am using the Django rest framework and Djoser for Authentication and User Registration. I completed the part of activation by template. But now the issue is I want to use html template on rest password. I created html form page to submit form of reset password. when I click on submit it not taking new password and reset password on post method. giving me error on that. Code is running on postmen but getting error when I submit it through html template Here is my djoser settings.py DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_USERNAME_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'EMAIL': { 'activation': 'user_profile.email.ActivationEmail', 'confirmation':'user_profile.email.ConfirmationEmail', 'password_reset':'user_profile.email.PasswordResetEmail', 'password_changed_confirmation':'user_profile.email.PasswordChangedConfirmationEmail' }, 'SERIALIZERS': { 'user_create': 'user_profile.serializer.UserSerializer', 'user': 'user_profile.serializer.UserSerializer', } } views.py class ResetPasswordView(View): def get (self, request, uid, token): return render(request, 'reset_password.html') def post (self, request,uid,token): new_password=requests.post.get("new_password") re_new_password=requests.post.get("re_new_password") payload = json.dump({'uid': uid, 'token': token, 'new_password': new_password, 're_new_password': re_new_password}) protocol = 'https://' if request.is_secure() else 'http://' web_url = protocol + request.get_host() + '/' password_reset_url = "users/reset_password_confirm/" # url used for activate user password_post_url = web_url + AUTHENTICATION_BASE_ROUTE + password_reset_url response = requests.post(password_post_url,data=payload) return HttpResponse(response.text) urls.py re_path(r'^password/reset/confirm/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', ResetPasswordView.as_view()), reset_password.html <form action="" method="post"> {% … -
How to fix this error module 'django.http.request' has no attribute 'META'?
I'm trying to get the visitor's IP address in my django project, here's the code I followed. from django.contrib.gis.geoip2 import GeoIP2 def add(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip g = GeoIP2() ip = add (request) location = g.city(ip) longitude = location["longitude"] latitude = location["latitude"] user_location = Point(longitude, latitude, srid=4326) When I run the server I get the following error and I don't know why module 'django.http.request' has no attribute 'META' -
Django UserCreationForm not responding when button clicked with input in fields
I'm having trouble getting my register application in Django to work. I am using the built-in UserCreationForm form. I can go to the URL and the form shows up but when I put info into the fields and click the submit button nothing happens. It should pop up an error screen saying "missing the csrf_field" (I know this because I'm following TechWithTim's tutorial and that's what happens to him). But when I click the "Register" button nothing happens. views.py: from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm # Create your views here. def register(response): form = UserCreationForm() return render(response, "register/register.html", {"form":form}) register.html: {% extends "main/base.html" %} {% block title %}Create an Account{% endblock %} {% block content %} <form method="POST" class="form-group"> {{form}} <button type="submit" class="btn btn-success">Register</button> </form> {% endblock %} urls.py: from django.contrib import admin from django.urls import path, include from register import views as v urlpatterns = [ path('', include("main.urls")), path("register/", v.register, name="register"), path('admin/', admin.site.urls), ] I added the application to my settings.py file as well. This is my first question on here and I tried to format it properly so sorry if I didn't -
Django - Sending Email and Base64 images, URL's are broken on Gmail
I am trying to send Emails using Django EmailMultiAlternatives() msg = EmailMultiAlternatives(subject, '', from_email, [to]) # Email details msg.attach_alternative(html_content, "text/html") # Email Content + Type msg.send() # SEND! On the receiving end i.e Gmail, image URLs are broken and I have tried using Base64 in my src as well, they still appear broken. I have used this for reference : Base64 images to gmail But there seems to be to no conclusive answer on how this should be implemented apart from attaching them in the email. -
cors policy error : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin
I have installed django-cors-headers and this is settings.py : ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS","").split() MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] and also : CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True but i got this error in chrome consloe: Access to XMLHttpRequest at 'https://event-alpha.mizbans.com/api/meetings/?memory=0' from origin 'https://alpha.mizbans.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. -
nslookup hostname in csv file and write ip address in another csv file in django
I want to perform ns-lookup on multiple hostnames given in .csv file and save IP address in another csv file in django using python. i am having a problem creating upload.py index.html <form enctype = "multipart/form-data" action = "upload.py" method = "post"> {% csrf_token %} <p><input type = "file" name = "myFile" /></p> <p><input type = "submit" value = "Upload" /></p> </form> views.py from django.shortcuts import render import dns import dns.resolver def index(request): if request.method == 'POST': search = request.POST.get('search') ip_address = dns.resolver.Resolver() IPv4 = ip_address.resolve(search, 'A').rrset[0].to_text() IPv6 = ip_address.resolve(search, 'AAAA').rrset[0].to_text() return render(request, 'index.html', {"ipv4": IPv4, "ipv6": IPv6, "hostname": search}) else: return render(request, 'index.html') -
Django: UniqueConstraint validator does work neither for model nor for intermediate model
My project is basically a platform, where one can post one's recipes with tags (for example, breakfast or dinner) and ingredients (carrot, milk, etc.). I would want to implement unique constraint for recipe, so that user could not create one with, say, two identical tags or ingredients. So, I have decided to use django UniqueConstraint validator for that, but even migrations did not apply, django says: "No changed were detected". from django.db import models from django.contrib.auth import get_user_model from django.core.validators import MinValueValidator, MaxValueValidator User = get_user_model() class Recipe(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='recipes', verbose_name='автор', ) name = models.CharField( max_length=200, verbose_name='имя', ) image = models.ImageField( max_length=4096, upload_to='images/%Y-%m-%d', verbose_name='фото', ) text = models.TextField(verbose_name='описание') ingredients = models.ManyToManyField( 'Ingredient', through='RecipeIngredient', verbose_name='ингредиет', ) tags = models.ManyToManyField( 'Tag', through='RecipeTag', verbose_name='тэг', ) cooking_time = models.IntegerField( default=60, validators=( MinValueValidator(1), MaxValueValidator(44640) ), verbose_name='время приготовления (в минутах)', ) creation_date = models.DateTimeField( auto_now=True, verbose_name='дата создания рецепта', ) class Meta: verbose_name = 'рецепт' verbose_name_plural = 'рецепты' def __str__(self): return f'Рецепт - id: {self.id}, имя: {self.name}.' class Tag(models.Model): name = models.CharField( max_length=256, verbose_name='имя', ) color = models.CharField( max_length=64, verbose_name='цвет', ) slug = models.SlugField( max_length=64, verbose_name='слаг', ) class Meta: verbose_name = 'тэг' verbose_name_plural = 'тэги' def __str__(self): return f'Тэг - id: {self.id}, имя: …