Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run custom openedx project in localhost
I have the edx-platform, ecommerce, ecommerce-themes, credentials and edx-theme directories. I have installed successfully tutor and devstack but I didn't find the way to replace these custom directories. So, what is the correct way to replace them ? After devstack runned successfully, I tried replacing the default directories with the custom ones but when I runned make dev.provision and then make dev.up but it didn't work, and then the logs said that there were some missing dependencies. -
Django and Nginx are redirecting in response
I have a project with Django and it is running using Nginx, gunicorn. And the URL of the Project is https://myweb/myapp(this I got from our IT). The problem is if I type my URL https://myweb/myapp/ it redirects to https://myweb/login (which doesn't exist and I got a 404 error), but actually, I want to have https://myweb/myapp/login, if I add to the URL /myapp/ it works for the first time, but it redirects again to https://myweb/dashboard/, again I want to have https://myweb/myapp/dashboard/, and so on. How can I properly redirect? or should say how to prevent Django from removing the prefix URL? the Nginx file: server { listen 127.0.0.1:100; server_name hammbwdsc02; client_max_body_size 4G; access_log /home/webapps/culturecrawler/logs/nginx-access.log; error_log /home/webapps/culturecrawler/logs/nginx-error.log; location /static/ { alias /home/webapps/culturecrawler/culture_crawler/static/; } location /media/ { alias /home/webapps/culturecrawler/culture_crawler/media/; } location /{ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; proxy_buffering on; proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_connect_timeout 300s; proxy_read_timeout 300s; if (!-f $request_filename) { proxy_pass http://culture_crawler_app; break; } } # Error pages error_page 500 502 503 504 /500.html; location = /404.html { root /home/webapps/culturecrawler/culture_crawler/templates/; } and the gnicorn file: #!/bin/bash NAME="culture-crawler" # Name of the application DJANGODIR=/home/webapps/culturecrawler/culture_crawler # Django project directory SOCKFILE=/home/webapps/culturecrawler/run/gunicorn.sock # we will communicte using … -
Creating a double log in system for department and user
I'm using django to create an webapp. I have been asked if I can look at creating a sort of double log in system. For example: A nurse on the ward will open up my webapp and will be met with a login page for their ward. So all nurses on that ward will have that generic log in. Once they've logged in they will be met with a second login page where they can enter their normal user credentials that only they know. I'm quite stuck at how to achieve this currently - or if someone could suggest an alternative method I'd be grateful! -
Django loop through json object
How to loop through a JSON object in Django template? JSON: "data": { "node-A": { "test1": "val1A", "test2": "val2A", "progress": { "conf": "conf123A" "loc": "loc123A" }, "test3": "val3A" }, "node-B": { "test1B": "val1B", "test2B": "val2B", "progress": { "conf": "conf123B" "loc": "loc123B" }, "test3": "val3B" } } I am having trouble accessing the nested values "conf" and "lock" inside "progress". How can I access them in Django template if the data is passed as context i.e. return (request, 'monitor.html', {"data_context": json_data['data']})? -
django objects method is not responding in views.py
I am trying to make a django project with sqlite3 db. Currently, I am building a page which I want to get data from db but it is not responding :( this is my mdoels.py from django.db import models class BookBoardModel(models.Model): title = models.CharField(max_length=30, null=False) content = models.TextField() #to be updated after the sign up page pub_date= models.DateTimeField('date published') writer = models.CharField(max_length=20, null=True) this is my views.py from django.shortcuts import render,redirect from .models import BookBoardModel def bookHome(request): books = BookBoardModel.objects return render(request, 'index.html', {'books': books}) this is my index.html {% for data in books %} <h1>{{ data.title }}</h1> {% endfor %} it is not showing at all :(v But in the web page, it only shows this I checked the .objects are not responding. Is there any hints? -
how to filter foreign key
Hello their i have two table one is StudentData and other is Enrollment. Below are the codes for them class StudentData(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) student_name = models.CharField(max_length=30, default=1) department = models.ForeignKey(Department,on_delete=models.CASCADE) program = models.ForeignKey(Program, on_delete=models.CASCADE) is_admitted = models.BooleanField(default=True) is_closed = models.BooleanField(default=False) class Enrollment(models.Model): student = models.ForeignKey(StudentData,on_delete=models.CASCADE) faculty = models.ForeignKey(TeachingSemester,on_delete=models.CASCADE) When student logins , the website shows data according to logged user , below is the code log_user = request.user student_information = StudentData.objects.filter(user=log_user) What can i do so that the Enrollment of only logged in is shown on the page? -
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.