Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I extend my existing Custom User Model created with AbstractBaseUser to have multiple user types like customer, trainer and author?
I have an existing custom user model which I created based on the Django doc to have email-based authentication. I want to extend the model to have multiple user types like Customers, Trainers, and Authors. I am not sure how to go forward and what is the best way to extend this? Also, have I made the right choice going with the AbstractBaseUser or should I have used the AbstractUser Class. -
How to get id from button modal to django views
I want to get the id from the modals button to select the id for the context object get id. the sample script is like this: <button type="button" class="btn btn-primary see-details" data-toggle="modal" data-target="#exampleModalLong" data-id="{{data.id}}">Detail</button> and I call the "data-id" from the button to javascript $(".see-details").on('click', function (){ var id = $(this).data('id'); $(".modal-bodys").html(` <div class="container-fluid"> <div class="row"> <div class="col-md-2"> <h1>{{students.name}}</h1> </div> </div> </div> `) }) I want to retrieve the id of the javascript variable to put into get id in the context in views.py from django.shortcuts import render,get_object_or_404 from profil.models import students def index(request): ID="get data-id from js" context = { 'students' : get_object_or_404(students, id=ID) } return render(request,'index.html',context) -
Trying to get the data from the dropdown list into views.py file in django
I want to get the data from the dropdown in HTML to the views.py file so that I can get the data from my database on the data which I will get from the dropdown. first try error: Request Method: POST Request URL: http://127.0.0.1:8000/admissions/ Django Version: 2.2.6 Exception Type: MultiValueDictKeyError Exception Value: 'state_dropdown' Exception Location: C:\django\lib\site-packages\django\utils\datastructures.py in getitem, line 80 Python Executable: C:\django\Scripts\python.exe Thanks in advance.. forms.py class state_form(Form): state_choices = ( ("Delhi", "Delhi"), ('west bengal', 'West Bengal'), ("Andhra Pradesh", "Andhra Pradesh"), ("Arunachal Pradesh", "Arunachal Pradesh"), ("Assam", "Assam"), ("Bihar", "Bihar"), ("Chhattisgarh", "Chhattisgarh"), ("Goa", "Goa"), ("Gujarat", "Gujarat"), ("Haryana", "Haryana"), ("Himachal Pradesh", "Himachal Pradesh"), ("Jharkhand", "Jharkhand"), ("Karnataka", "Karnataka"), ("Kerala", "Kerala"), ("Madhya Pradesh", "Madhya Pradesh"), ("Maharashtra", "Maharashtra"), ("Manipur", "Manipur"), ("Meghalaya", "Meghalaya"), ("Mizoram", "Mizoram"), ("Nagaland", "Nagaland"), ("Odisha", "Odisha"), ("Punjab", "Punjab"), ("Rajasthan", "Rajasthan"), ("Sikkim", "Sikkim"), ("Tamil Nadu", "Tamil Nadu"), ("Telangana", "Telangana"), ("Tripura", "Tripura"), ("Uttar Pradesh", "Uttar Pradesh"), ('Uttarakhand', 'Uttarakhand'), ) state_name=forms.ChoiceField(choices=state_choices) views.py def admissions(request): if request.method == "POST": a = request.GET['state_dropdown'] print(str(a)) else: context_dict = {} return render( request, 'buddyscholarship_html/admissions.html',{}) HTML code <form class="form-control mb-3" style="margin-top:500px;" method="post"> {% csrf_token %} <select class="col-lg-7 mb-4 mb-lg-0" name="state_dropdown"> <option value="select your state">select your state</option> <option value="Uttarakhand">Uttarakhand</option> <option value="West Bengal">West Bengal</option> <option value="Andhra Pradesh">Andhra Pradesh</option> <option value="Arunachal Pradesh">Arunachal Pradesh</option> … -
HTML page is not shown
when I click on about, it does not go in about.html page and not show any error. here is the link for calling <li><a href="{%url 'about'%}">About</a> </li> url url(r'^about/$',views.AboutView.as_view(),name = 'about') and, view,py class AboutView(TemplateView): template_name = 'about.html' -
django orm: combine result of two queries containing different fields
I have the following Django queries: my_timesheet_Q3_by_wp = my_timesheet_Q3.values('work_packet').annotate(wp_hours=Sum('logged_billable_hours')).order_by() returning [{'work_packet': 1152, 'wp_hours': Decimal('384.00')}] and: wps_details = WorkPacket.objects.values('id', 'number', 'name', 'type', 'purchase_order') returning: [{'purchase_order': 1, 'type': 1, 'id': 803, 'name': u'Consultancy', 'number': u'WP0001/1'}, {'purchase_order': 2, 'type': 1, 'id': 805, 'name': u'Consultancy', 'number': u'WP0002/1'}, {'purchase_order': 3, 'type': 1, 'id': 806, 'name': u'Consultancy', 'number': u'WP0003/1'}, ... the foreigh_key 'work_packet' (first model) is linked to the primary key 'id' (second model). I would like to combine the two queries to add 'number', 'name', 'type', 'purchase_order' to the first query, something like: [{'work_packet': 1152, 'wp_hours': Decimal('384.00'), 'purchase_order': xxx, 'type': xxx, 'id': xxx, 'name': u'someName'}] I know how to achieve this in plain sql but I am new to DJANGO orm -
Issue using i18n_patterns with API
I have an app which includes a website and an API. I have translated the website to a second language. The main language is currently English and the second one Farsi. I have used i18n_patterns in urlpatterns to redirect between the two languages. The issue is when using the API, it seems like Django redirects my request and since the data is sent using POST, it drops all data and gives me an empty result using GET. I tried taking the API url out of the urlpattern and then appending it which solves this issue, but that doesn't work since I need to have Unicode support for Farsi and since there is no i18n_patterns support this way, I get an unintelligible response. This is the Urlpattern: urlpatterns = i18n_patterns( path('admin/', admin.site.urls), path('mainapp/', include('mainapp.urls')), path('', include('mainapp.urls')), prefix_default_language=True ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns.append(path('api/', include('mainapp.api.urls'))) Is there any way I can solve this issue with the least possible change to the app? Any help, suggestion, or guidance would be very much appreciated. -
How can I integrate hbmqtt with Django?
I'd like to integrate a MQTT broker/server based on hbmqtt into a Django project. I'm providing a RESTful API for JS frontend integration as well. What are the general steps required to do so? BTW: I know about django_mqtt but it is GPL-2 licensed and no option for me. -
Django django.contrib.staticfiles.templatetags.static removed in 3.0: How could I replace the functionality?
I have the following code block where a corresponding .css file's path is returned. It is part of a Theme-Class that allows the user to change the website theme (dark and light) from a button in the profile view. def link(self) -> str: """ Returns the link where the CSS file for this theme is located """ return static('app_shared/colors_%s.css' % self.name()) The same problem when it occurs in an HTML-Template can be solved by changing {% load staticfiles %} to {% load static %}. Obviously for source code I will need another alternative. -
How to most effectivly query data from PostgreSQL asynchronously every X seconds?
Before going any further coding wise, I would like to consider and compare different approaches to query data from PostgreSQL DB asynchronously every X seconds. Project environment: Backend = Python based Django project, PostgreSQL DB, zeroMQ Pull socket Frontend = Basic HTML,CSS,JS stuff with some libraries like Vue, jQuery, etc. Background: I build a web based dashboard which will have to update its figures every 2 seconds using the latest data from the PostgreSQL DB which itself gets populated by zeroMQ datastream. Possible setups: 1.) AJAX + JS, client-side pull 2.) Axios + JS, client-side pull 3.) Psycopg2 + Python, server-side push 4.) Any other worth looking into? So which one would best fit in terms of lightweightness and performance? Talking about a possible peak, we assume to have around 5.000 - 10.000 users online -
Django query optimization for 3 related tables
I have 3 models: class Run(models.Model): start_time = models.DateTimeField(db_index=True) end_time = models.DateTimeField() chamber = models.ForeignKey(Chamber, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, default=None, blank=True, null=True, on_delete=models.CASCADE) class RunProperty(models.Model): run = models.ForeignKey(Run, on_delete=models.CASCADE) property_name = models.CharField(max_length=50) property_value = models.CharField(max_length=500) class RunValue(models.Model): run = models.ForeignKey(Run, on_delete=models.CASCADE) run_parameter = models.ForeignKey(RunParameter, on_delete=models.CASCADE) value = models.FloatField(default=0) A Run can have any number of RunProperty (usually user defined properties, can be custom), and a few predefined RunValue (such as Average Voltage, Minimum Voltage, Maximum Voltage) that are numeric values. When I build a front end table to show each Run along with all of its "File" RunProperty (where the Run came from) and all of its "Voltage" RunValue, I first query the DB for all Run objects, then do an additional 3 queries for the Min/Max/Avg, and then another query for the File, then I build a dict on the backend to pass to the front to build the table rows: runs = Run.objects.filter(chamber__in=chambers) min_v_run_values = RunValue.objects.filter(run__in=runs, run_parameter__parameter__parameter_name__icontains="Minimum Voltage") max_v_run_values = RunValue.objects.filter(run__in=runs, run_parameter__parameter__parameter_name__icontains="Maximum Voltage") avg_v_run_values = RunValue.objects.filter(run__in=runs, run_parameter__parameter__parameter_name__icontains="Average Voltage") run_files = RunProperty.objects.filter(run__in=runs, property_name="File") This is not such a big problem for customer with ~10 to 30 Run objects in their database, but we have one heavy usage customer who … -
Django clean() change field requirement
I want to change the requirement of some modelForm fields as shown below. certs is a checkbox. If this checkbox is "True" the ca,cert and key fields shall be required. If not, they shall be left blank (null=True is set in models). class CreateMVPConnectionsForm(forms.ModelForm): class Meta: model = MVPConnections fields = '__all__' exclude = ['created_by_user', 'parent_project_id'] def clean(self): print("clean started") cleaned_data = super().clean() certs = cleaned_data.get('certs') ca = cleaned_data.get('ca') cert = cleaned_data.get('cert') key = cleaned_data.get('key') if certs == True: if ca and cert and key: pass else: raise ValidationError(_('If certs is checked, please fill in "ca", "cert" and "key".')) else: ca = forms.CharField(required=False) cert = forms.CharField(required=False) key = forms.CharField(required=False) Any suggestions on how to solve this? -
Django Lost connection to MySQL server during query
I have a Django Admin application which periodically gives "2013, 'Lost connection to MySQL server during query'" exception at various pages without any obvious reason, e.g. today the problem happens at /login page. My DB tables are relatively small, below 10k records. I noticed no correlation between the problem and database load, e.g. sometimes the problem happens at night when no one is using the database. I read multiple Stack Overflow articles describing similar issue, e.g. Lost connection to MySQL server during query and Lost connection to MySQL server during query?. Also read this: https://dev.mysql.com/doc/refman/5.7/en/error-lost-connection.html. Based on multiple articles I read on the issue, I tried to adjust MySQL DB variables, current values are: max_allowed_packet: 4194304 net_buffer_length: 16384 connect_timeout: 10 net_read_timeout: 30 wait_timeout: 28800 So far nothing helps, the problem just appears randomly and disappears by itself without me doing anything. I also noticed that it more often happens on the server while rarely happens on localhost (both server and localhost connecting to the same database). Any ideas would be very appreciated. Today's traceback from localhost: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/login/?next=/ Django Version: 2.1.7 Python Version: 3.7.4 Installed Applications: ['adminapp.apps.AdminappConfig', 'middleware.apps.MiddlewareConfig', 'adminactions', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
Not showing Validation Errors on Login Page
I am using django.contrib.auth.views.LoginView for Login page. I cannot display the Validation errors when there is incorrect password or username not found. views.py from django.contrib.auth.views import LoginView from django.shortcuts import reverse class MyLoginView(LoginView): template_name = 'login.html' def get_success_url(self): return reverse('home') login.html <form method="POST"> {{ csrf_token }} {{ form.username }} {{ form.password }} <button type="submit">Login</button> </form> -
Python Requests module not working on Ubuntu Server
I have created a website with django and there is a web crawler in it. It is working on my localhost perfectly. But it is not working on the server. The other parts of website is working too. Only this web crawler is not working. When I call the view server is giving "Server Error (500)". It has python requests module in it. The code is working on localhost so it must be a serverside problem. I think something is blocking requests module but I don't know. Here is the code: @login_required def Unutulmaz(request): url = "https://720p-izle.com/tr-altyazili-film-izle/page/" base_url = "https://720p-izle.com/tr-altyazili-film-izle/page/1/" headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0','X-Requested-With': 'XMLHttpRequest',} try: response = requests.get(base_url,headers=headers) print(response.status_code, base_url) except ConnectionError as error: print(error) soup = BeautifulSoup(response.content,"lxml") sonsayfa = soup.find("ul", attrs={"class":"pagination xs-mt-0 xs-mb-0"}).find_all('li')[-3] toplamsayfa = int(sonsayfa.text) for sayfa in range(39,toplamsayfa+1): new_url = url + str(sayfa) try: response = requests.get(new_url,headers=headers) print(response.status_code, new_url) except ConnectionError as error: print(error) soup = BeautifulSoup(response.content,"lxml") filmler = soup.find_all('a', attrs={'class':'sayfa-icerik-baslik'}) for film in filmler: new_url = film['href'] try: response = requests.get(new_url,headers=headers) print(response.status_code, new_url) except ConnectionError as error: print(error) soup = BeautifulSoup(response.content,"lxml") resim = soup.find('div', attrs={'class':'film-kategori-oyuncu-biyografi-resim'}).find('img') thumb = resim['src'] imdb = soup.find('b', attrs={'class':'imdby'}).contents[0] baslik2 = soup.find('div', attrs={'class':'film-kategori-oyuncu-biyografi-baslik oval-ust'}).find('h1').contents[0] baslik … -
how to use mulitselect dropdown in django admin
enter image description here A quick replacement of the HTML select element with multiple selection. Built-in check box support with a Select All option for easy interactions. Built-in support for filtering, hierarchical data binding, grouping, tagging, selection limits, and UI customization with templates. -
Designing Django models with potentially horizontally growing data columns
I have many "features" that would be associated to certain real estate properties. For example, a Single Family Home can have 4 bedrooms, 2 bathrooms, 1 pool. An apartment unit will have air conditioning as well as a laundry room, etc. I am not sure how to correlate these features to each property in Django Models. My first attempt is to have each property be represented with a unique ID, and create one table with all the features listed? For example propertyID | A/C | Bedrooms | Bathrooms | Electric Stoves | Pool | Balcony | Gas Stoves 123 | T | 4 | 2 | F | T | T | T 124 | F | 1 | 2 | T | F | F | F ... As you can see, there are potentially lots of replicated values where if I am dealing with an area with lots of cold weather, Pool will most likely be all F in the way I chose to represent features. I am not sure of another way to model my data. The model will GROW horizontally as I add more and more features such as wifi, fireplace. It would also potentially could … -
Django rest framework: How to reuse an app using different settings?
I have an application that has it's own urls and uses specific settings to access another api. I would like to use this same app again within the same project, but with different urls and using a seperate endpoint. So just setup new urls, and point to the same views from the original app but inject different settings. For example one of my views is: class SummaryVMsList(ListAPIView): ''' VM Summary ''' def list(self, request, *args, **kwargs): ''' Return a list of processed vm's ''' v_token = settings.VTOKEN base_url = settings.VURL v_password = settings.VPASSWORD v_username = settings.VUSERNAME session = Session() session.headers.update({ 'v_token': v_token }) client = VClient( url=base_url, v_username=v_username, v_password=v_password, session=session ) try: repos = client.get_summary_vms() return Response(data=repos, status=status.HTTP_200_OK) except VError as err: return Response( data={'error': str(err)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) # log the error finally: client.logout() How would I be able to change the setting values: settings.VTOKEN, settings.VURL, settings.VPASSWORD and settings.VUSERNAME Based on whick url is used: In urls-site1.py app_name = 'v_site1' urlpatterns = [ path('vm-summary', views.SummaryVMsList.as_view(), name='vms_list'), ] In urls-site2.py: app_name = 'v_site2' urlpatterns = [ path('vm-summary', views.SummaryVMsList.as_view(), name='vms_list'), ] -
How to pass a class name with a string in Django models
I want to get all of objects that are related to an instance of models. Because my code is kinda generic, I pass the related table as an string and use eval() function to convert it to the related table class. But I got an error. Suppose that we have an instance of a table like self.casefile; this is a part of my code: def related_models_migration(self): opts = self.casefile._meta table_name = 'Files' for f in opts.many_to_many: name = ''.join(f.name.split('_')) table_name += name.capitalize() objects = self.casefile.eval(table_name).all() and I got this error: AttributeError Traceback (most recent call last) <ipython-input-6-025484eeba97> in <module> ----> 1 obj.related_models_migration() ~/Documents/kangaroo/etl/data_migration.py in related_models_migration(self) 28 name = ''.join(f.name.split('_')) 29 table_name += name.capitalize() ---> 30 objects = self.casefile.eval(table_name).all() 31 32 for d in dir(etl.models): AttributeError: 'FilesCasefiles' object has no attribute 'eval' How can I pass the class name? -
Python - Django 2 multiple types of users
I'm working to implement multiple type of users in my Django(2.2) applications, I also need to use the email as username, so firstly I setup the django-allauth to use email then I start customizing my models. After a long research, I decided to extend the AbstractUser to build a custom model and use to all user types models. Here's what I did: From models.py: class CustomUser(AbstractUser): title = models.CharField(max_length=255, blank=False) user_type = models.CharField(max_length=255, blank=False) gender = models.CharField(max_length=255, choices=CHOICES, blank=False) contenst = models.TextField(max_length=500, blank=True) class PersonalBelow18(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) dob = models.DateField(blank=False) customer_id = models.BigIntegerField(blank=False) collection_use_personal_data = models.BooleanField(blank=False) class PersonalAbove18(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) dob = models.DateField(blank=False) customer_id = models.BigIntegerField(blank=False) contact_email = models.EmailField(blank=False) contact_no = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the" "format: '+999999999'. Up to 15 digits allowed.") collection_use_personal_data = models.BooleanField(blank=False) class Parent(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) contact_email = models.EmailField(blank=False) contact_no = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the" "format: '+999999999'. Up to 15 digits allowed.") collection_use_personal_data = models.BooleanField(blank=False) class GroupContactPerson(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) contact_email = models.EmailField(blank=False) contact_no = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the" "format: '+999999999'. Up to 15 digits allowed.") department = models.CharField(max_length=255, blank=False) address = models.TextField(max_length=255, blank=False) Then I created their … -
Django/Git: why __pycache__ still metionned?
I try to work using Django and Git. I have experience many conflicts problems and try to understand better Git and Django in order to implement a workflow that should prevent if possible conflicts (even if it is not always possible) I have origin/master branch (=dev branch) on my Gitlab remote repository and the corresponding master in my local repository. I have defined a backlog with differents isues. I decide to work on issue #1 so I pull origin/master to be up-to-date in my local master and create a local branch name feature/1. I work on this feature/1 branch and commit yesterday. I did not finish to work on this issue but when I finish, but to complete workflow, I will push this feature/1 on Gitlab and make a merge request in order to merge with origin/mater. After that, I pull origin/master, suppress my local feature/1 branch and create a new feature/2 branch. This morning, I checkout on my local master to verify I am still up-to-date with origin/master and it is the case except that git mentionned that 3 files have been modified: On branch master Your branch is up to date with 'origin/master'. Changes to be committed: (use … -
How to stream encrypted/protected PDF File in Django?
I am creating a site and I want to essentially stream pdfs. The user must not be able to save these files to their computer. I understand that browsers are always able to download pdfs but as far as I know there is some way to encrypt the pdfs so that they can be displayed on the site but when they are downloaded they are password protected. So, I have the following view which displays completely unprotected pdfs: @login_required def view(request, pk): object = Things.objects.all().filter(pk=pk) object = object[0] # TODO: PDF Encryption with open("."+object.object_pdf.url, 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = 'filename=%s'%object.object_pdf.url return response pdf.closed It is my understanding that, where the comment is, I should be able to decrypt pdfs and then display them. My issue with using the following from PyAesCrypt: # encrypt pyAesCrypt.encryptFile("data.pdf", "data.pdf.aes", password, bufferSize) # decrypt pyAesCrypt.decryptFile("data.pdf.aes", "dataout.pdf", password, bufferSize) is that I would still, at least in my mind, be streaming the unencrypted dataout.pdf file. There are modules other than PyAesCrypt that seem to have the same issue. Is there a way to do this or do I have to take a different approach? I have also seen mention of a technique … -
Fill a form from text file then post to databse Django
So what I am trying to achieve is a form that users fill in that then posts to a database, but I want some of the information filled in before using a barcode scanner, so a text field that a user scans in a barcode say 101 that searches a csv file and returns the relevant information in a form and users can fill in the blanks then submit that data to a database. Here is what I have so far forms.py class MendingForm(forms.ModelForm): date = forms.DateField(widget=forms.DateInput( attrs = { 'class': 'form-control', 'type': 'date' } )) def __init__(self, *args, **kwargs): super(MendingForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) class Meta: model = Mending fields = ['date', 'frame', 'knitter', 'folio_number', 'style', 'colour', 'size', 'fronts_selvedge', 'fronts_rib', 'fronts_narr_wids', 'backs_selvedge', 'backs_ribs', 'backs_narr_wids', 'sleeves_selvedge', 'sleeves_ribs', 'sleeves_narr_wids', 'other', 'mends_id_knitter', 'mends_id_qc', 'total_panels_checked', 'beat_qty', 'plus_minus_panels', 'comments'] views.py def mending_record_new(request): if request.method == "POST": form = MendingForm(request.POST) if form.is_valid(): record = form.save(commit=False) record.examiner = request.user record.total_mends = (int(record.mends_id_knitter) + int(record.mends_id_qc)) record.save() return redirect('mending_list') else: form = MendingForm() return render(request, 'mendingform/record_new.html', {'form': form}) record_new.html {% extends 'mendingform/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="center"> <div class="col-xs-4"> <form class="" action="" method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" … -
Django production static files are not working (deployment)
When deploying my Django project in the Linux server, the static files are not getting uploaded. I have followed instructions on the Docs but it doesn't seem to work. This is what I had done so far: settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') For deploying static files, I typed this command: python manage.py collectstatic All the files are being pushed to a directory called 'staticfiles' in the root folder and the command works as expected. However, when starting the Django server, all the static files i.e JS, CSS and media files are not seen. In fact, the site is broken. What went wrong? Can anyone let me know where I am making a mistake? -
how to change Image using graphene-django?
I want to change image by mutation. user has one image file already. user want to change it to new file. this is Models. class User(AbstractUser): """ User class """ name = models.CharField(_("Name of User"), blank=True, max_length=255) # 이름 gender = models.CharField(choices=GENDER_CHOICES, max_length=5, null=True) # 성별 class Photo(models.Model): image = models.ImageField(upload_to="user_profile/") owner = models.ForeignKey(User, on_delete=models.CASCADE) order = models.CharField(max_length=10, null=True) pub_date = models.DateTimeField(auto_now_add=True) this is mutation class ImageAndSelfMutation(graphene.Mutation): class Arguments: image = Upload() Output = types.EditProfileResponse def mutate(self, info, **kwargs): user = info.context.user ok = True error = None if user.is_authenticated is not None: try: first_image = models.Photo.objects.get(owner=user, order="first") image = kwargs.get('image', first_image) first_image = image user.save() print(user.Photo.image) except IntegrityError as e: print(e) error = "Can't Save" return types.EditProfileResponse(ok=not ok, error=error) return types.EditProfileResponse(ok=ok, error=error) else: error = '로그인이 필요합니다.' return types.EditProfileResponse(ok=not ok, error=error) error is that 'User' object has no attribute 'Photo' could you help me? -
i want to use variable globally in veiws.py
veiws.py def getBusRouteId(strSrch): end_point = "----API url----" parameters = "?ServiceKey=" + "----my servicekey----" parameters += "&strSrch=" + strSrch url = end_point + parameters retData = get_request_url(url) asd = xmltodict.parse(retData) json_type = json.dumps(asd) data = json.loads(json_type) if (data == None): return None else: return data def show_list(request) Nm_list=[] dictData_1 = getBusRouteId("110") for i in range(len(dictData_1['ServiceResult']['msgBody']['itemList'])): Nm_list.append(dictData_1['ServiceResult']['msgBody']['itemList'][i]['busRouteNm']) return render(request, 'list.html', {'Nm_list': Nm_list}) There is a dict data that was given by API In 'def getBusRouteId', some Xml data is saved by dict data In 'def show_list', I call 'def getBusRouteId' so 'dictData_1' get a dict data And I want to refer this dictData_1 in another function Is there any way to use dictData_1 globally?