Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django test without vpn
I want to test my function, where I add a new object to a database and then (still in this function) the object is being sent to a server. The problem is that to send the object to a server I need to run VPN. I'm wondering is there a way to run this function in my test, but skip the line responsible for sending the object to the server, or somehow simulate this behavior? Currently, I'm not able to run my test because I'm getting Failed to establish a new connection: [Errno 110] Connection timed out My test looks like this: def test_create_ticket_POST_adds_new_ticket(self): response = self.client.post(self.create_ticket_url, { 'title': 'test title', 'description': 'test description', 'grant_id': 'test grant id', }) result_title = Ticket.objects.filter(owner=self.user).order_by('-last_update').first().title result_count = Ticket.objects.filter(owner=self.user).count() self.assertEquals(response.status_code, 302) self.assertEquals(result_title, 'test title') self.assertEquals(result_count, 1) And the post request is calling this function: @login_required @transaction.atomic def create_ticket(request): if request.method == 'POST': ticket_form = TicketForm(request.POST) tags_form = TagsForm(request.POST) attachments = AttachmentForm(request.POST, request.FILES) if ticket_form.is_valid() and attachments.is_valid() and tags_form.is_valid(): jira = JIRA(server=JIRA_URL, basic_auth=(jira_user, jira_password)) new_issue = add_issue(request, jira, ticket_form) add_attachments(request, jira, new_issue) set_tags(request, new_issue, tags_form) messages.info(request, _(f"Ticket {new_issue} has been created.")) return redirect(f'/tickets/{new_issue}/') else: ticket_form = TicketForm() tags_form = TagsForm() attachments = AttachmentForm(request.POST, request.FILES) return … -
i want to add custom field in django-allauth SignupForm
i wanted to add custom field with django-allauth SingupForm and adding new field like phone number. i already managed to add this field in Postgresql on my own(without migrations,but by my hands). this is my postgresql screen In my signup page i have these fields already but i can't managed to add "phone" to my database, i really want to make it! please someone help me. forms.py from allauth.account.forms import SignupForm from django import forms class CustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='Voornaam') last_name = forms.CharField(max_length=30, label='Achternaam') phone = forms.CharField(max_length=30, label='phone') def __init__(self, *args, **kwargs): super(CustomSignupForm, self).__init__(*args, **kwargs) self.fields['first_name'] = forms.CharField(required=True) self.fields['last_name'] = forms.CharField(required=True) self.fields['phone'] = forms.CharField(required=True) def save(self, request): user = super(CustomSignupForm, self).save(request) user.phone = self.cleaned_data.get('phone') user.save() return user def signup(self,request,user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() return user settings.py ACCOUNT_FORMS = {'signup': 'registration.forms.CustomSignupForm'} -
SMTPAuthenticationError at /
Iam trying to send an email with my django app to my email. and its firing the above error. my Login credentials in my settings are correct and i have turned on less secure apps and DisplayUnlockCaptcha but it still persists. nvironment: Request Method: POST Request URL: http://localhost:8000/ Django Version: 3.0.9 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shield_sec'] Installed 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'] Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/apple/projects/Django/ingabo_sec/shield_sec/views.py", line 17, in contact send_mail ( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 69, in open self.connection.login(self.username, self.password) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 734, in login raise last_exception File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 723, in login (code, resp) = self.auth( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 646, in auth raise SMTPAuthenticationError(code, resp) Exception Type: SMTPAuthenticationError at / Exception Value: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials 138sm1136246lfl.241 - gs settings.py STATIC_URL = '/static/' … -
how to filter spetember in datefield django?
Hope You Are Good I Have This Model: class Task(models.Model): .... timestamp = models.DateField(auto_now_add=True) now I want to get only September tasks not matter what date is, I want to filter or grep September 2020 tasks how can I achieve this? -
Django - import constants's variable from variable
I've a Django application and I'd like to import from myapp.constants the MYCONSTANT variable in a way that myapp and MYCONSTANT is stored in a variable: VAR1='myapp' VAR2='MYCONSTANT' and I'd like to import it using the variables. from VAR1.constants import VAR2 , but of course it does not work. How can I achieve this? Is there any similar way to using apps.get_model() ? -
Django in Google Cloud Run cant find /cloudsql socket
I have a dockerized django application which I've built, uploaded to GCR and then deployed as a google cloud run service. However, when starting up I get the following error (from the cloud run logs): psycopg2.OperationalError: could not connect to server: Connection refused Is the server running locally and accepting connections on Unix domain socket "/cloudsql/kingdoms-289503:us-west1:kingdomsdb/.s.PGSQL.5432"? My database settings for django look something like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': "/cloudsql/kingdoms-289503:us-west1:kingdomsdb", 'USER': "postgres", 'PASSWORD': "password", 'NAME': "postgres", } } And I've made sure to create the connection to the database From what I understand, cloud run is supposed to magically mount a at /cloudsql that django can use to connect to postgres, but the error implies that it's not being mounted. Is there an extra piece of configuration I would need to check to make sure that socket is there? Are there alternatives to connecting to cloudsql that don't involve this socket? -
How to Upload Djnago Project in Digitalocean?
i am Uploading Djnago project in Digitalocean server.i have uploaded all my files in Digitalocean.and i am Using MongoDb database.but when i run my project it showing below error raise ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5f6c644e91288a299c34f17e, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]> This error is Related Mongodb database or Something else? i don't Know How to Upload Mongodb database in Digitalocean.can any one Explain step by step how to upload Django project in Digitalocean with Mongodb.i will be Thankful. -
Django adding field to ElasticSearch
I'm trying to add a field to a well established ElasticSearch (I would rather not do a rebuild) and I wonder if there is a way of simply adding the field. So if I have something as simple as @search_index.document class OrganisationDocument(Document): name = fields.TextField() class Django: model = Organisation queryset_pagination = 100 When I add a new field, for example: facilities_resident_transport = fields.NestedField(properties={ 'name':fields.KeywordField() }) I now get an error RequestError(400, 'search_phase_execution_exception', 'failed to create query: { I have tried saving an Organisation with the field used but when I look in Kibana the field isn't there. Can I populate without a complete rebuild? -
How to do a variation in Views.py for add to cart function
Views.py I just need to make the add to cart have variation like for example S,M,L This is not Django Rest Framework and this is model.py -
Element of type <myclass> is not json serializable
class priceManage(object): def __init__(self,uid): self.uid = uid def getRealPrice(self): tot_price = 0 plist = e_cart.objects.filter(e_uid_id = self.uid, e_ordnum__isnull = True).select_related() for x in plist: tot_price += x.e_prodid.getRealPrice()*x.e_qta return float(tot_price) all done, but when i instance object and try to serialize with json i get Object of kind priceManage is not json serializable why f i return a float? So many thanks in advance -
How do I create a Django endpoint that receives JSON files?
I'm designing a Django endpoint that is supposed to receive a JSON file message from an API that sends texts. On the API, I'm supposed to include the endpoint (drlEndpoint) so that after a text is sent, the app endpoint can also receive a report in form of a JSON file. How do I design an endpoint that can receive the report? Here is the API... api_key = "" api_secret = "" # Get Bearer token = api_key + api_secret message_bytes = token.encode('ascii') base64_bytes = base64.b64encode(message_bytes) bearer = base64_bytes.decode('ascii') # Handle data and send to API enpoint post_dict = { 'unique_ref': '', 'clientId': '', 'dlrEndpoint': '', 'productId': '', 'msisdn': '', 'message': '', } data = json.dumps(post_dict) # converts data to json url = '' # set url headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + bearer} # set headers r = requests.get(url=url, data=data, headers=headers) # make the request to the API endpoint my_data = r.json() # converts the request into json format print(my_data) # makes the request and prints to terminal -
Attribute Error in Django model Foreign Key
In My Django Project, there are two apps: Login and Company The error that am receiving in this is AttributeError: module 'login.models' has no attribute 'Country' Company App > models.py from django.db import models from login import models as LM class CompanyProfile(models.Model): full_name = models.CharField(max_length=255, unique = True) country = models.ForeignKey(LM.Country, on_delete=models.SET_NULL, null=True, blank=False) state = models.ForeignKey(LM.State, on_delete=models.SET_NULL, null=True, blank=False) def __str__(self): return self.full_name Login App > models.py class Country(models.Model): """List of Country""" name = models.CharField(max_length=50, unique= True, default='None') code = models.CharField(max_length=2, unique= True, primary_key=True, default ='NA') def __str__(self): return str(self.code) class State(models.Model): """List fo State""" region = models.CharField(max_length = 255, unique = True, primary_key=True, default='None') country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=False, default ='NA') def __str__(self): return self.region Here is test to check that weather is login is getting imported or not def test_import(): try: # import pdb; pdb.set_trace() importlib.find_loader('LM.Country') found = True except ImportError: found = False print(found) Answer is received stands to be True python3 manage.py shell >>> test_import() True Now on other stackoverflow blogs i checked i thought it could be of Circlular Import But i have already fixed that still am getting this error? Thanks in Advance Regards -
Cron for sending emails after 3 days in django
I dont have any knowledge about the cron. In my project once the task is assigned to employee email is sent to his mailid. If the employee does not complete the task within deadline I want to send the mail after every 3 days to complete the task. Can anyone give me I idea what I should do. The project is on my local environment, does it support or I should take server. -
How to extract data from django model
There is a django model with this field task_args. This field contains record like this ('test_user', 1, ['test'], 'id_001'). This field is a text field. How do I filter data from this model using this field I tried the following but this does not seem to work user = request.user.username num = 1 parsed_data = eval("['test']") id = "id_001" print(type(parsed_data)) args = f"{(user,num,parsed_data,id)}" print(args) task_id = list(TaskResult.objects.filter(task_args=args).values('task_id')) This results in an empty list. -
Convert nested query MySQL django
Im trying to convert this query from MySQL to Django, but I don't know how to do nested select in python, please, could you help me? SELECT zet.zone, SUM(CASE WHEN zet.`status` = 'available' THEN zet.total ELSE 0 END) AS `ge_available`, SUM(CASE WHEN zet.`status` = 'assigned' THEN zet.total ELSE 0 END) AS `ge_assigned`, SUM(CASE WHEN zet.`status` = 'on_going' THEN zet.total ELSE 0 END) AS `ge_on_going`, SUM(CASE WHEN zet.`status` = 'stopped' THEN zet.total ELSE 0 END) AS `ge_stopped` FROM (SELECT vhgz.zone zone, vhgz.status status, COUNT(*) total FROM view_historic_group_zone vhgz, (SELECT group_id gid, MAX(date_change) fe FROM historical_group WHERE date_change <= '2020-09-21 15:12:56' GROUP BY group_id) hg WHERE vhgz.date = hg.Fe AND vhgz.gid = hg.gid GROUP BY vhgz.zone, vhgz.status) zet GROUP BY zet.zone Model.py class viewhistoricgroupzone (models.Model): zone = models.CharField(max_length=50) date = models.DateTimeField() status = models.CharField(max_length=23, blank=True, null=True) gid = models.PositiveIntegerField() The result should be: {"zone":"Spain","available":0,"assigned":1,"on_going":15,"stopped":2} {"zone":"England","available":12,"assigned":4,"on_going":5,"stopped":1} {"zone":"Italy","available":2,"assigned":4,"on_going":12,"stopped":4} {"zone":"Germany","available":5,"assigned":8,"on_going":7,"stopped":3} -
Run django url in background inside windows 10
I'm new to django and trying to develop a system which requires to run a certain script in the background. if i'm using linux i can register this automatically to crontab. but what will be the process if i'm using windows 10? is there any way to automate the registration of tasks in task scheduler? Here are the example of link i'm accessing http://localhost/get/1 http://localhost/get/2 http://localhost/get/3 i want to run the following link asynchronous to each other. Thank you for suggestions and help -
Which plugin for Django autocompletion
I'd like to use autocompletion in my Django project but I don't know which plugin to choose. I have ModelMultipleChoiceField in my form like: tags = forms.ModelMultipleChoiceField( label=_("Etiquettes"), queryset=Tag.objects.all(), to_field_name="name", required=False, widget=forms.SelectMultiple(attrs={'class': "form-control form-custom"}) ) I'd like to change it into autocompletion. I know there is Typeahead and Django-autocomplete-light plugins but I don't know which one is better for my case. I want to create tag if it doesn't exist after typing it. I want a field like tags in StackOverflow question form but creating tags too. Thank you if anybody can help me. Best regards. -
Django Cloudinary - how do I supply the cloud name (except in the settings)?
I am building a django 3.1.1 app with a simple cloudinary setup for storing images. I get a weird error Must supply cloud_name in tag or in configuration although I did everything as stated in the package documentation: CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'your_cloud_name', 'API_KEY': 'your_api_key', 'API_SECRET': 'your_api_secret' } The uploads work fine, the images are present in Cloudinary and I even got them to display on the page. Now this error just pops from time to time and I can't seem to find the reason why. -
Only Django Admin pages visible while rest of Site blank in production
Im trying to host my site on heroku on my localhost my project is fine with no issues , on deploying it all I get are blank pages (I inspected it and elements are shown but nothing is visible on webpage)apart from admin pages I installed all the necessary packages as I was deploying that is to say gunicorn and whitenoise as well as setting STATIC_ROOT and STATICFILES_STORAGE . I at first set DISABLE_COLLECTSTATIC = 1 and later set it to 0 when deploying, I have failed to see any error that might be causing the issue some of my files for context settings STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_dev')] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' urls from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.conf.urls import handler404 urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('user.urls')), path('users/', include('django.contrib.auth.urls')), path('accounts/', include('allauth.urls')), path('', include('pages.urls')), path('store/', include('store.urls')), #path("djangorave/", include("djangorave.urls", namespace="djangorave")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #error handlers handler404 = 'store.views.error_404' #handler500 = 'store.views.my_custom_error_view' -
How can I connect a user model to a custom model in Django?
I have a student model with a one-to-one relationship to the built-in Django User model. My aim is to combine both forms in a single template for registration such that whenever I create a new student, the student object is automatically assigned a user by using Django post_save signals. Below are the code snippets: models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Student(models.Model): CURRENT_CLASS = ( ('1', 'Form 1'), ('2', 'Form 2'), ('3', 'Form 3'), ('4', 'Form 4'), ) user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) adm_num = models.IntegerField(null=True) form = models.CharField(max_length=1, choices=CURRENT_CLASS, null=True) def __str__(self): return '%s %s' % (self.first_name, self.last_name) forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import Student class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] class StudentForm(ModelForm): class Meta: model = Student fields = '__all__' exclude = ['user'] views.py def signupPage(request): form = CreateUserForm() student_form = StudentForm() if request.method == 'POST': form = CreateUserForm(request.POST) student_form =StudentForm(request.POST) if form.is_valid() and student_form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + username) return redirect('student:login') … -
Django Session: TypeError at /order/ Object of type Decimal is not JSON serializable
While trying to delete a session variable it throws a type error. Well I to tried print out the each variable and its type that I am storing in the session. But I didn't find any variable of type decimal. What is the issue here, why ain't it deleting the session variable? def checkout_address(request): form = AddressChoiceForm(request.user, request.POST or None) next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): address_type = request.POST.get('address_type', 'shipping') address = Address.objects.get(id=request.POST.get('address')) print(address.id) request.session[address_type+'_address_id'] = address.id if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect('orders:order') return redirect('orders:order') def order(request): cart = Cart(request) order = None address_form = AddressChoiceForm(request.user) shipping_id = request.session.get('shipping_address_id', None) billing_id = request.session.get('billing_address_id', None) order, created = Order.objects.get_or_create(user=request.user, ordered=False) if shipping_id: shipping_address = Address.objects.get(id=shipping_id) order.shipping_address=shipping_address del request.session['shipping_address_id'] if billing_id: billing_address = Address.objects.get(id=billing_id) order.billing_address=billing_address del request.session['billing_address_id'] if billing_id or shipping_id: order.save() return TemplateResponse( request, "orders/order.html", { 'address_form':address_form, 'order':order, 'cart':cart } ) Traceback Internal Server Error: /order/ Traceback (most recent call last): File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/utils/deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/contrib/sessions/middleware.py", line 63, in process_response request.session.save() File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 83, in save obj = self.create_model_instance(data) File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 70, … -
ValueError: not enough values to unpack (expected 2, got 1) in Django Framework
I am beginner in django, I just starts learning how to load static files and all about static file. After setting whole code when I run the server I encounter with this error: `C:\Users\Lenovo\Documents\Django project\project3\fees\views.py changed, reloading. Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Lenovo\anaconda3\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Lenovo\anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\contrib\staticfiles\checks.py", line 7, in check_finders for finder in get_finders(): File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\contrib\staticfiles\finders.py", line 282, in get_finders yield get_finder(finder_path) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\contrib\staticfiles\finders.py", line 295, in get_finder return Finder() File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\contrib\staticfiles\finders.py", line 59, in __init__ prefix, root = root ValueError: not enough values to unpack (expected 2, got 1)` please tell me why I am getting this error and how can i solve it. Here is setting.py files """ Django settings for project3 project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see … -
Convert ReturnDict/Serializer.data to normal dictionary in django
In my django application I want to work on serializer.data thus there is a need to convert ReturnDict or OrderDict to normal dictionary. How can I do that ? For e.g. Here's the example data {'id': 75, 'kits': [OrderedDict([('id', 109), ('items', [OrderedDict([('id', 505), ('quantity', 6), ('product', 3)]), OrderedDict([('id', 504), ('quantity', 4), ('product', 1)]), OrderedDict([(' id', 503), ('quantity', 2), ('product', 6)]), OrderedDict([('id', 502), ('quantity', 2), ('product', 5)]), OrderedDict([('id', 501), ('quantity', 2), ('product', 4)])]), ('quantity', 2), ('kit', 10)]), OrderedD ict([('id', 110), ('items', [OrderedDict([('id', 510), ('quantity', 12), ('product', 3)]), OrderedDict([('id', 509), ('quantity', 8), ('product', 1)]), OrderedDict([('id', 508), ('quantity', 4), ('product', 6)] ), OrderedDict([('id', 507), ('quantity', 4), ('product', 5)]), OrderedDict([('id', 506), ('quantity', 4), ('product', 4)])]), ('quantity', 4), ('kit', 1)])], 'transaction_type': 'Return', 'transaction_date': ' 2020-09-24T06:16:02.615000Z', 'transaction_no': 1195, 'is_delivered': False, 'driver_name': '__________', 'driver_number': '__________', 'lr_number': 0, 'vehicle_number': '__________', 'freight_charges': 0, 've hicle_type': 'Part Load', 'remarks': 'to be deleted', 'flow': 1, 'warehouse': 1, 'receiver_client': 3, 'transport_by': 4, 'owner': 2} -
TypeError: Cannot read property'map' of undefined, I want to implement select option using map, but there is a problem
error code : TypeError: Cannot read property 'map' of undefined PatientInfoModal D:/test/pages/patient/PatientInfoModal.js:164 161 | </Form.Item> 162 | 163 | <Form.Item name={['patient', 'hospital']} label="Hospital" rules={[{ required: true }]}> > 164 | <Select placeholder="Select a Hospital" style={{ width:'150px' }}> | ^ 165 | {testplz.map(a => <Option>{a.name}</Option>)} 166 | </Select> 167 | </Form.Item> mycode.js : const doctorplz = { doctor } const [ whats, whatsdata ] = useState("doctor") const testplz = doctorplz[whats] <Select placeholder="Select a Hospital" style={{ width:'150px' }}> {testplz.map(a => <Option>{a.name}</Option>)} </Select> console.log(doctorplz) : {doctor: Array(4)} doctor: Array(4) 0: {d_code: 1, name: "test1", position: "RB", code_id: 1} 1: {d_code: 2, name: "test2", position: "LB", code_id: 2} 2: {d_code: 3, name: "test3", position: "ST", code_id: 2} 3: {d_code: 4, name: "test4", position: "RW", code_id: 1} length: 4 __proto__: Array(0) __proto__: Object I got the error despite entering the code correctly. I don't know what the hell is wrong. Also, the code below works fine. mycode2.js (Code that works) const namelist = { "01": [ { d_code: '1', name: 'test1' }, { d_code: '2', name: 'test2' }, { d_code: '3', name: 'test3' } ] } const [ data, setData ] = useState("01"); const Options = namelist[data]; <Select placeholder="Select a Doctor" style={{ width:'150px' }} > … -
Django REST Framework: HyperlinkedModelSerializer: ImproperlyConfigured error
I am trying to serialize my Django models using the HyperlinkedModelSerializer class from Django REST Framework. My application is a dictionary application. I defined the serializer class for a Definition model, DefinitionSerializer, as follows: class DefinitionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Definition fields = ["id", "definition", "expression"] The Definition model is defined as follows: class Definition(models.Model): definition = models.CharField(max_length=256) I am trying to return the serialized data in my IndexView as follows: class IndexView(APIView): definitions = Definition.objects.all() serializer = DefinitionSerializer(definitions, context={"request": request}, many=True) return Response(serializer.data) Accessing that view, however, returns the following ImproperlyConfigured error: Could not resolve URL for hyperlinked relationship using view name "expression-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. Does this error have to do with the fact that I am including slugs instead of primary keys in my URLs? For example, the URL associated with the "expression" field in the DefinitionSerializer is: app_name = "dictionary" path("define/<slug:slug>", views.ExpressionView.as_view(), name="expression") How can I make this work?