Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I add <a> tags to a Django HTML Email template?
I'm trying to set up a view to reset passwords. The HTML email template works fine, until I add a anchor tag which causes the emails to no longer be sent. I'm not getting any error messages so I'm not sure what the problem is. Is it not possible to send hyperlinks in an email? I want to try and create a button in the email so that a user will be redirected to reset their password when they click on it. in views.py: class CustomPasswordResetView(PasswordResetView): template_name = "accounts/password_reset.html" email_template_name = "accounts/password_reset_email.html" html_email_template_name = "accounts/password_reset_html_email.html" subject_template_name = "accounts/password_reset_subject.txt" success_url = reverse_lazy("accounts:password-reset-done") password_reset_html_email.html <!DOCTYPE html> <html> <head> </head> <body> {% autoescape off %} <div> <p><b>A password reset was requested for</b> {{ user.email }} If you did not request this, then disregard the email. To reset your password click on the link below.</p> <h1>HTML VERSION</h1> <a href="{% url 'accounts:password-reset-confirm' uidb64=uid token=token %}">Verify Email</a> <p> The link will expire in 24 hours. If clicking the link above doesn't work, please copy and paste the URL in a new browser window instead. </p> </div> {% endautoescape %} </body> </html> -
question about forms, how do i get instant user in a form field pyhton django
i have build some user to user message function. i have sender, receiver and text see below. The user now must choose his email and then the email where the message should go. But what i want is that the user dont need tho choose it self i need a form function that query instantly request.user. but i dont know how to implement that on form. And that the user is not shown in the receiver list. Srry for my bad english hope you understand me. views.py def mailEMployee(request): mail = Mailsysthem.objects.filter(ontvanger=request.user) receiver = Mailsysthem.objects.filter(ontvanger=request.user) sender = Mailsysthem.objects.filter(zender=request.user) user = CustomUser.objects.filter(email=request.user) form = Mailsythemform() if request.method == 'POST': form = Mailsythemform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('mail') context={ 'form':form, 'receiver':receiver, 'sender':sender.all, 'mail':mail, 'user':user } return render(request,'emp/mail.html', context) Forms.py class Mailsythemform(forms.ModelForm): class Meta: model= Mailsysthem fields= ['zender','ontvanger','subject','text'] models.py class Mailsysthem(models.Model): zender = models.ForeignKey(to=CustomUser, null=True, on_delete=models.SET_NULL,related_name='Zender') ontvanger = models.ForeignKey(to=CustomUser, null=True, on_delete=models.SET_NULL,related_name='Ontvanger') subject = models.CharField(null=True, max_length=200) text = models.TextField(max_length=300, null=True, blank=True, verbose_name='Bericht') date = models.DateTimeField(auto_now_add=True, blank=True) solftdelete = models.BooleanField(default=False) mail_opened = models.BooleanField(default=False) url.py path('mailemployee/', views.mailEMployee, name='mail'), -
Django email verification link goes to page not found
I am using conventional email code generation to verify email users. During development when I send the verification link to console and paste in browser it works fine but during production it says page not found.. Have tried all possible option no result. Kindly check the code below Validation view def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() messages.success(request, 'Thank you for your email confirmation. Now you can login your account.') return redirect('user-login') URL path('activate/(P<uidb64>[0-9A-Za-z_\-]+)/(P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/', user_views.activate, name='activate'), Email code format Please click on the link to confirm your registration, http://riflogistik.com/activate/(PMTI%5B0-9A-Za-z_%5C-%5D+)/(Pb6ymqe-66b9346a42751b6d94e729b4050698ba%5B0-9A-Za-z%5D%7B1,13%7D-%5B0-9A-Za-z%5D%7B1,20%7D)/ Kindly assist with the issue -
GCP App Engine w/Django: big pandas load in views is causing server error
One of my page views in GCP App Engine (standard) is failing to load. I've determined that the issue occurs when Django temporarily loads a large pandas dataframe from cache (30mb). This is necessary in order for my charts to grab a subset of the data for charts before page rendering (it is not being injected into the html at all). def myView(request): baseTable = cache.get("somecachekey") #issue is here chartDiv = makeChart(baseTable) return render(request, template_name = 'myView.html', context = {'chart' : chartDiv}) Interestingly, there are no server errors. The logs seem fine. Also, this view works successfully when I am locally hosting Django on my laptop. Any advice here? -
Use email created on cpanel to send message in django
i try to make setting for send message to user when they create account or rest password ( i use all auth ) ,, but when try to create acc to ex the page just still loading , it don't do anything how to fix it # email message send EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST= 'mail.filltasks.live' EMAIL_HOST_USER= 'no-reply@filltasks.live' EMAIL_HOST_PASSWORD= 'mypass_namecheap_acc' EMAIL_USE_TLS= True EMAIL_PORT= 465 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
Customized Password Reset URL for Django Rest API Password Reset
I am new to Django and have implemented a password reset endpoint for my rest API using the django-rest-passwordreset library. It works fantastic, but I want to customize the url returned in my email to include "https://" and domain name before the path and token so that the full URL is shown in the email. As of now, the email send me a path like this: /password-reset/?token=random_string_of_characters_are_here I'd like it to email me something like this: https://mywebsite.com/password-reset/?token=random_string_of_characters_are_here -
connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
I´am deploying my new app to heroku and i can´t figure out how can i solve it. I have this error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? I tried many things even redo complete database deploy. On localhost everithing is working but if i want to deploy to heroku this appear. Here is github repo to this project: https://github.com/AdrianHorvath8/Developer-search -
How do I generate SECRET_KEY in django and postgresql database for a .env file?
A bit confusing to me is I am working on a project with a previously generated key - like so: SECRET_KEY='1x8n9Xj4UNw8T2PgIiaircPBcZ5z9u0TTBivRbeTMbbRsiNM1VUjWlkP1mDZy8o11csfee*^5jvpGsH41VYVUAx8jE110ashdjkrkGBIjJRQ1SxU8irV6mcNz-3rQ1RDWiDv1WqmSfVtUX4kYymodEEZkeKNH4mQUlHsqdVX2ZAJ4BQaYmQOzKls' but its longer that the one I generated which is more like so: SECRET_KEY='te1we2*&v_&!9p1jhl7-aa@z$mlrb#v=2%xuyt%h([(ew@3z0^' using this command python manage.py shell -c 'from django.core.management import utils; print(utils.get_random_secret_key())' And in what instances would the KEY not be enclosed with quotes('') in the .env file. I know the procedure involved in securing the secrets, my confusion comes with the structure of the first SECRET_KEY which makes me think am doing something the wrong way. -
Error: unknown tag from YAML in DRF generated openapi schema
I have a data model in Django that gets serialized with Django Rest Framework. To document this API made with Django Rest Framework I want to use DRF's option to automatically create an openapi schema that then generates a redoc documentation. The problem that I have is that the Django decimal field creates a datatype that YAML doesn't seem to understand causing Error: unknown tag !<tag:yaml.org,2002:python/object/apply:decimal.Decimal> The block where the last line that generates the error looks like type: string format: decimal multipleOf: 0.01 maximum: 100000000 minimum: !!python/object/apply:decimal.Decimal I have found some posts touching similar errors here and here but they don't fix my problem and also seem somewhat unrelated to my problem as they focus on solving the same error message but the error originates from another problem. I have tried the approach with adding the unknown tag to the settings.json file but without success. However I am also not completely sure how the content of "yaml.customTags": [...] should exactly look like in this case. -
django - cargar archivo csv en la base de datos
I created a view where I have a form, I have a input type="file" to load a csv file, but my code takes a long time to process the file, to process a file of 1000 records it takes about 10 minutes, I have analyzed the I code and it takes too long in the "for" loop, insert into the database is not delayed because I use "bulk_create", how can I improve it? this is my code: class AsignacionCreateView(CreateView): model=AsignacionContact form_class=AsignacionForm template_name='gestionAsignacion/asignacion_contact.html' success_url = reverse_lazy('gestionAsignacion:asignacion_contact') def form_valid(self, form): isvalid = super().form_valid(form) csv_file = self.request.FILES['file'] data=codecs.iterdecode(csv_file, 'utf-8') data = csv.reader(data, delimiter=",") next(data) asignaciones = [] for row in data: print('inicio de for') asignacion = AsignacionSur( idasignacion=AsignacionContact.objects.get(id=self.object.pk), producto=row[0], contrato=row[1], nombre_suscriptor=row[2], tipo_servicio=row[3], total_deuda=row[4], corriente_no_vencida_actual=row[5], corrente_vencida=row[6], total_deuda_corriente=row[7], cuota_minima_agente=row[8], politica_surtigas=row[9], categoria=row[10], estrato=row[11], ref_anio=row[12], historico_ref=row[12], ciclo=row[14], medidor=row[15], lectura=row[16], plan_acuerdo=row[17], descripcion_barrio=row[18], direccion=row[19], dias_deuda=row[20] ) asignaciones.append(asignacion) if len(asignaciones) > 5000: AsignacionSurtigas.objects.bulk_create(asignaciones) asignaciones = [] if asignaciones: AsignacionSur.objects.bulk_create(asignaciones) return isvalid This part of the code takes too long: for row in data: asignacion = AsignacionSur( idasignacion=AsignacionContact.objects.get(id=self.object.pk), producto=row[0], contrato=row[1], nombre_suscriptor=row[2], tipo_servicio=row[3], total_deuda=row[4], corriente_no_vencida_actual=row[5], corrente_vencida=row[6], total_deuda_corriente=row[7], cuota_minima_agente=row[8], politica_surtigas=row[9], categoria=row[10], estrato=row[11], ref_anio=row[12], historico_ref=row[12], ciclo=row[14], medidor=row[15], lectura=row[16], plan_acuerdo=row[17], descripcion_barrio=row[18], direccion=row[19], dias_deuda=row[20] ) -
I want to customize the error message for a login api to django rest framework simple jwt
I am able to customise error by over riding the validate function of the TokenOBtainPairSerializer. However I can't customize cases in which user sends only password or only username. The error is "password field is required". But I can't figure out where this error is coming from? I don't know the control flow of a request when we use django-drf-simplejwt. Please elaborate. -
Form_valid not redirecting to success page
I have a class base view which renders a form. When the form is correctly filled, I want to redirect to a success url, but couldn't find a way to do that. Every thing I tried just reloads the form page without redirecting. Before that I had a function based view and it was correctly redirecting using : return HttpResponseRedirect(reverse('scripts:results', args=(self.script_id,))) I tried to define a success_url, override get_success_url and form_valid but each time I just have a refreshed form (code below). success_url : success_url = reverse('scripts:data_input', args=(self.script_id,)) get_success_url : def get_success_url(self): return reverse('scripts:data_input', args=(self.script_id,)) form_valid def form_valid(self, form): return HttpResponseRedirect(reverse('scripts:results', args=(self.script_id,))) I've tried changing the view to render, and it seems to work for the views that don't have any arguments, so maybe the problem is coming from there but I couldn't find how to solve it. If needed, here is my urls.py : app_name = 'scripts' urlpatterns = [ path('', views.ScriptsView.as_view(), name='scripts'), path('<int:script_id>/data/', views.DataInputView.as_view(), name='data_input'), path('<int:script_id>/results/', views.results, name='results'), ] And my view : class DataInputView(FormView): form_class = ScriptInputForm initial = {'key': 'value'} template_name = 'scripts/data_entry.html' def setup(self, request, *args, **kwargs): self.script_id = kwargs['script_id'] self.script = Script.objects.get(pk=self.script_id) self.module = Script.get_script(self.script) return super().setup(request, *args, **kwargs) def form_valid(self, form): return HttpResponseRedirect(reverse('scripts:results', … -
Django: serving static files for production
I ran into a problem during serving my static files in Django. The problem only exists in the production configuration where I'm using docker (docker-compose.yml) with nginx (default.conf) files. After run command python manage.py collecstatic static files are placed in the file defined in STATIC_ROOT. But these are not files which I created to modify my templates sites and administration panel. As I saw my custom styling and photos with fonts are not served to the STATIC_ROOT folder specified in settings.py file. Below I put some of the most important code snippets related to my configuration for serving static files. settings.py # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING DEBUG = False INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.conf', 'rest_framework', 'django_filters', 'tinymce', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ] STATIC_URL = '/django_static/' STATIC_ROOT = os.path.join(BASE_DIR, 'django_static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = i18n_patterns( path('panel/', admin.site.urls), path('tinymce/', include('tinymce.urls')), ) urlpatterns += [ re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), re_path(r'^django_static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}), ] django_static directory after command python manage.py collectstatic enter image description here default.conf … -
Does not validate the JWT token from React in header, or does not see the token
There is an application - front on React, back on Django. There is also an application on Microsoft Azure for user authentication. I use this tutorial to validate the token: Validating JSON web tokens (JWTs) from Azure AD, in Python Following it, 2 files are created. demo.py: import jwt from jwksutils import rsa_pem_from_jwk # To run this example, follow the instructions in the project README # obtain jwks as you wish: configuration file, HTTP GET request to the endpoint returning them; jwks = { "keys": [ { "kid": "X5eXk4xyojNFum1kl2Ytv8dlNP4-c57dO6QGTVBwaNk", "nbf": 1493763266, "use": "sig", "kty": "RSA", "e": "AQAB", "n": "tVKUtcx_n9rt5afY_2WFNvU6PlFMggCatsZ3l4RjKxH0jgdLq6CScb0P3ZGXYbPzXvmmLiWZizpb-h0qup5jznOvOr-Dhw9908584BSgC83YacjWNqEK3urxhyE2jWjwRm2N95WGgb5mzE5XmZIvkvyXnn7X8dvgFPF5QwIngGsDG8LyHuJWlaDhr_EPLMW4wHvH0zZCuRMARIJmmqiMy3VD4ftq4nS5s8vJL0pVSrkuNojtokp84AtkADCDU_BUhrc2sIgfnvZ03koCQRoZmWiHu86SuJZYkDFstVTVSR0hiXudFlfQ2rOhPlpObmku68lXw-7V-P7jwrQRFfQVXw" } ] } # configuration, these can be seen in valid JWTs from Azure B2C: valid_audiences = ['d7f48c21-2a19-4bdb-ace8-48928bff0eb5'] # id of the application prepared previously issuer = 'https://ugrose.b2clogin.com/9c2984ff-d596-4e5c-8e74-672be7b592e3/v2.0/' # iss class InvalidAuthorizationToken(Exception): def __init__(self, details): super().__init__('Invalid authorization token: ' + details) def get_kid(token): headers = jwt.get_unverified_header(token) if not headers: raise InvalidAuthorizationToken('missing headers') try: return headers['kid'] except KeyError: raise InvalidAuthorizationToken('missing kid') def get_jwk(kid): for jwk in jwks.get('keys'): if jwk.get('kid') == kid: return jwk raise InvalidAuthorizationToken('kid not recognized') def get_public_key(token): return rsa_pem_from_jwk(get_jwk(get_kid(token))) def validate_jwt(jwt_to_validate): public_key = get_public_key(jwt_to_validate) decoded = jwt.decode(jwt_to_validate, public_key, verify=True, algorithms=['RS256'], audience=valid_audiences, issuer=issuer) # do what you wish with decoded token: … -
Update or create from file CSV in Django
In my view, I created this which allows to add several plants thanks to a CSV file : class UploadFileView(generics.CreateAPIView): serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) file = serializer.validated_data['file'] reader = pd.read_csv(file) for _, row in reader.iterrows(): new_file = Plant( name=row['Name'], plant_description=row["Plant description"], family=Family.objects.get(name=row['Family']), category=PlantCategory.objects.get(name=row['Category']), facility_rate=row["Facility rate"], seedling_depth=row['Seedling depth'], seedling_distance=row["Seedling distance"], row_spacing=row['Row spacing'], sunshine_index=row["Sunshine index"], irrigation_index=row["Irrigation index"], soil_nature=row['Soil nature'], soil_type=row["Soil type"], fertilizer_type=row['Fertilizer type'], acidity_index=row["Acidity index"], days_before_sprouting=row["Days before sprouting"], average_harvest_time=row['Average harvest time'], soil_depth=row["Soil depth"], plant_height=row['Plant height'], suitable_for_indoor_growing=row["Suitable for indoor growing"], suitable_for_outdoor_growing=row["Suitable for outdoor growing"], suitable_for_pot_culture=row['Suitable for pot culture'], hardiness_index=row["Hardiness index"], no_of_plants_per_meter=row['No of plants per meter'], no_of_plants_per_square_meter=row["No of plants per square meter"], min_temperature=row["Min temperature"], max_temperature=row['Max temperature'], time_to_transplant=row["Time to transplant"], ) new_file.save() return Response({"status": "Success : plant(s) created"}, status.HTTP_201_CREATED) The problem being that if the plants are already created there is an error message but I would like to make sure to identify if the plant is not created then we have created it, otherwise we update it with the new ones CSV file data. I saw that there was an update_or_create() method on Django but I couldn't manage to implement it with my code. If anyone can help me that would be great! -
improper configured in django
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Unhandled Rejection (TypeError): Cannot read properties of null (reading 'product')
This error appears to me when I add something to the shopping cart . I've checked the code many times, but I still can't find the solution, I don't know how to make it work. code in cartActions.js import axios from 'axios' import { CART_ADD_ITEM } from '../constants/cartConstants'; export const addToCart = (id, qty) => async (dispatch, getState) => { const { data } = await axios.get(`/api/products/${id}`) dispatch({ type: CART_ADD_ITEM, payload: { product: data._id, name: data.name, image: data.image, price : data.price, countInStock: data.countInStock, qty } }) localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems)) } code in cardReducers.js I think the problem comes from here, but I don't know exactly where to change import { CART_ADD_ITEM } from "../constants/cartConstants" export const cartReducer = (state = { cartItems: [] }, action) => { switch (action.type) { case CART_ADD_ITEM: const item = action.payload const existItem = state.cartItems.find(x => x.product === item.product) if(existItem){ return{ ...state, cartItems: state.cartItems.map(x => x.product === existItem.product ? item:x) } }else{ return{ ...state, cartItems:[...state.cartItems, item] } } default: return state; } } code in CartScreen.js import React, {useEffect} from 'react' import { useParams, useLocation } from 'react-router-dom'; import { useDispatch, useSelector} from 'react-redux'; import { Row, Col, ListGroup, Image, Form, Button, Card } from 'react-bootstrap'; … -
django/wagtail : why my page doesnt pass along pk variable?
I am trying to get the preview work in wagtail with a react frontend and djangorestframework serving it. I have the preview working correctly by changing manually the url passed along and putting the right pk identifier which is initially None. My question is why does the pk in the PostPage class in the get_preview_url function is not correctly set? Here is the code class PostPage(BasePage): serializer_class = "blog.serializers.PostPageSerializer" header_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) body = StreamField(BodyBlock(), blank=True) tags = ClusterTaggableManager(through="blog.PostPageTag", blank=True) content_panels = Page.content_panels + [ ImageChooserPanel("header_image"), InlinePanel("categories", label="category"), FieldPanel("tags"), StreamFieldPanel("body"), ] search_fields = Page.search_fields + [ index.SearchField('title'), index.SearchField('body'), ] api_fields = ( APIField( "header_image_url", serializer=ImageRenditionField("max-1000x800", source="header_image"), ), "body", APIField("owner"), APIField("api_categories", serializer=CategoryField(source="categories")),#check if categories retrieved APIField("api_tags", serializer=TagField(source="tags")), #APIField("pub_date",serializer=DateTimeField(format="%d %B %Y", source="first_published_at")), ) def get_preview_url(self, token): return urllib.parse.urljoin(self.get_client_root_url(), f"post/{self.pk}/" + "?" + urllib.parse.urlencode({"content_type": self.get_content_type_str(), "token": token}), ) def serve(self, request, *args, **kwargs): return HttpResponseRedirect(urllib.parse.urljoin(self.get_client_root_url(), f"/post/{self.pk}") ) And here is the BasePage class which is being inherited in PostPage: class BasePage(HeadlessPreviewMixin, Page): serializer_class = None class Meta: abstract = True def get_component_data(self): if not self.serializer_class: raise Exception(f'serializer_class is not set {self.__class__.__name__}') serializer_class = import_string(self.serializer_class) return { 'page_type': self.__class__.__name__, 'page_content': serializer_class(self).data } def categories_list(self, context): categories = BlogCategory.objects.all() … -
MySQL to PostgreSQL migration converted camelCase columns to simple format. Leading to Column does not exist error in Django ORM
I migrated MySQL database to PostgreSQL using pgloader. I am using Django ORM to execute the queries. The database fields are defined in camel case but after the migration the postgres columns are replaced to normal format. e.g brochureName is changed to brochurename. This is causing "Column does not exist" error in the application. What is the best way to handle this issue? I have lots of columns and queries already defined at many instances. -
Django: AttributeError: 'function' object has no attribute 'as_view' showing in urls.py
i have written alot of class based views, and also configured it's urls but this particluar view is showing this error AttributeError: 'function' object has no attribute 'as_view' i cannot tell what is going on with the view urls.py path('<slug:course_slug>/<slug:quiz_slug>/results/', views.QuizResultsView.as_view(), name="quiz_results"), views.py @method_decorator([login_required, teacher_required], name='dispatch') class QuizResultsView(DetailView): model = Quiz context_object_name = 'quiz' template_name = 'classroom/teachers/quiz_results.html' def get_context_data(self, **kwargs): quiz = self.get_object() course = Course.objects.get(slug=course_slug) quiz = Quiz.objects.get(slug=quiz_slug, course=course) taken_quizzes = quiz.taken_quizzes.select_related('student__user').order_by('-date') total_taken_quizzes = taken_quizzes.count() quiz_score = quiz.taken_quizzes.aggregate(average_score=Avg('score')) extra_context = { 'taken_quizzes': taken_quizzes, 'total_taken_quizzes': total_taken_quizzes, 'quiz_score': quiz_score, 'total_questions':quiz.questions.count() } kwargs.update(extra_context) return super().get_context_data(**kwargs) def get_queryset(self): self.kwargs['course_slug'] self.kwargs['quiz_slug'] return self.request.user.quizzes.all() -
Making an integerfield into selectable dropdown numbers from 0 to the value of the integerfield in django
I have been trying to make the value of an integerfield show up as a dropdown list with numbers ranging from 1 to the valueof the integer field for example 47 , the numbers between 1 and 47 will show up as a dropdown menu. i managed to get this code working: HTML PAGE that's resposible for fetching the integerfield ID since i am displaying it in another model as a foreignkey, this is where i am also trying to make the dropdown list of numbers show up {% for i in rayons %} <option id="empla"value="{{ i.pk }}">{{ i.Nombre_des_Emplacments }}</option> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> var n = {{ i.Nombre_des_Emplacments }}; for (var i = 0; i < n+1; i++) { //creates option tag jQuery('<option/>', { value: i, html: i }).appendTo('#empla'); } </script> {% endfor %}[![enter image description here][1]][1] Result : note that the Num field is what i am talking about and it's dependent on the previous field so when something other than A1 is selected the Num field will change -
Why am I getting an NameError error when I use "if any" on Django [duplicate]
I’m on Django and I try to get subject of mail and check if a certain word are in the subject. For that I do : Firstly I declare a list of word which I will then look for. lst_RAS = [ "ras", "RAS", "réussi ", "terminée", "terminé" ] Then I retrieve the subjects of mail that I receive but it is not important I think since I make sure to retrieve or transform them in string. temp_dict = {} s = mail["Subject"] temp_dict['Subject'] = decode_str(s) Currently I know it's worth a string without worry On the other hand, I am now trying to check if the words on my list are part of my subject. After looking at a lot of advice here it seems the best way to go is this. if any(word in temp_dict['Subject'] for word in lst_RAS): But I get the following error Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Program Files\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\pheni\Documents\Projets Django\mail_manager\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\pheni\Documents\Projets Django\mail_manager\venv\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\pheni\Documents\Projets Django\mail_manager\venv\lib\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( … -
{detail: 'CSRF Failed: CSRF token missing.'} Django and React
even though csrf is provided, it just does not recognize it at all in frontend side (note it works perfect on backend host, but not frontend) views.py: class CheckAuthenticated(views.APIView): def get(self, request): if request.user.is_authenticated: return Response("Authenticated") else: return Response("Not Authenticated",status=401) class PostView(viewsets.ModelViewSet): serializer_class = serializer.PostSerializer def get_queryset(self): queryset = models.Post.objects.all() return queryset @method_decorator(ensure_csrf_cookie,csrf_protect) def create(self,request): authentication_classes = [SessionAuthentication] permissions_classes = [IsAuthenticated] post = serializer.PostSerializer(data=request.data) if post.is_valid(): title = post.data['title'] description = post.data['description'] models.Post.objects.create(title=title,description=description,user=User.objects.first()) return Response("post created successfully.") return Response("post creation failed.") i have also a resource that receive csrf token: class GetCSRFToken(views.APIView): permission_classes = [AllowAny, ] @method_decorator(ensure_csrf_cookie) def get(self, request, format=None): return Response("Success") in urls.py: urlpatterns = [ path('csrf/',views.GetCSRFToken.as_view(),name='csrf'), path('isauthenticated/',views.CheckAuthenticated.as_view(),name='authenticated'), ] now in frontend: let handleSubmit = (e)=>{ e.preventDefault() console.log(Cookies.get('csrftoken')) axios.post('http://127.0.0.1:8000/posts/',post,{withCredentials:true},{headers:{'X-CSRFToken':Cookies.get('csrftoken')}}).then((res)=>{ console.log(res.data) }).catch((e)=>{ console.log(e.response.data) console.log(Cookies.get('csrftoken')) }) } useEffect(()=>{ axios.get('http://127.0.0.1:8000/posts/').then((res)=>{ setPostList(res.data) }) axios.get('http://127.0.0.1:8000/csrf/',{headers:{Authorization:null},withCredentials:true}) },[]) the csrf is being printed in the dev console any idea? -
Terminate an endpoint from within a function Django
Is there a way to end an endpoint from inside a function? I know I can make the function to return True or False, then evaluate that answer and return, but it would be a lot cleaner if I can do something like this: def custom_endpoint(self, request): check_something(request) return Response("ok") check_something(request) should check variables and then end the execution of the endpoint if one of the variables is not correct. Thanks!! -
django-grappelli installed but not showing in lib/site-packages of my venv and not found by django itself
I have activated a virtual environment to a django project. I have installed django-grappelli using pip into that virtual environment. pip install django-grappelli When calling 'pip list', I can see it's installed. Package Version ---------------- ------- asgiref 3.5.2 Django 4.0.5 django-grappelli 3.0.3 pip 22.1.2 psycopg2 2.9.3 setuptools 58.1.0 sqlparse 0.4.2 tzdata 2022.1 In my project setting I added grappelli app above django contrib as instructed by grappelli docs: INSTALLED_APPS = ( 'grappelli', 'django.contrib.admin', ) Then I added the url confs accordingly as instructed by grappelli docs: from django.conf.urls import include urlpatterns = [ path('grappelli/', include('grappelli.urls')), # grappelli URLS path('admin/', admin.site.urls), # admin site ] When checking if it is all good calling py manage.py check I get a ModuleNotFoundError: No module named 'grappelli' error. I looked at lib/site-packages and in fact, django-grappelli isn't showing there (see picture). I tested in a python shell importing for 'grappelli' and 'django-grappelli' but python says no module found for each of these. Essentially pip shows it's installed, but python, hence django, think otherwise. Tested grappelli in another simpler project and did not run into this problem. There is obviously something I am missing here and it is probably right under my nose, but thus …