Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Cannot pass the value from kwargs in POST method django rest framework
When I try to pass the value of course_id using perform_create method, It shows this error... ValueError at /course/9f77f4a9-0486-44f3-8bea-4908adb7d3ca/add/ Cannot assign "'9f77f4a9-0486-44f3-8bea-4908adb7d3ca'": "Content.course_id" must be a "Course" instance. Request Method: POST Request URL: http://127.0.0.1:8000/course/9f77f4a9-0486-44f3-8bea-4908adb7d3ca/add/ Django Version: 2.2.5 Exception Type: ValueError Exception Value: Cannot assign "'9f77f4a9-0486-44f3-8bea-4908adb7d3ca'": "Content.course_id" must be a "Course" instance. This is my views.py class ContentAdd(generics.ListAPIView, mixins.CreateModelMixin): queryset = Content.objects.all() serializer_class = ContentSerializer def post(self, request, *args, **kwargs): saveData = self.create(request, *args, **kwargs) response_data = {} response_data["data"] = saveData.data response_data["errors"] = {} return Response(response_data, status=status.HTTP_201_CREATED) def perform_create(self, serializer): id = self.kwargs.get("course_id") serializer.save(course_id=id) This is my serializers.py class ContentSerializer(serializers.ModelSerializer): class Meta: model = Content fields = [ 'title', 'description', 'serial', 'file', 'file_type', ] This is my model.py class Content(models.Model): content_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) course_id = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="content_course_id", to_field='course_id') file = models.FileField(upload_to=gen_pic_path,blank=False, null=False) file_type = models.BooleanField(blank=False, null=False) # content/attachment serial = models.IntegerField() title = models.CharField(max_length=200) description = models.TextField() This is url path path('course/<course_id>/add/', ContentAdd.as_view()), -
django, postgresql countdown and passive if payment is not made
Backend: I used Django and postgresql. Frontend: I used reactjs. I have a user table and a user profile table. I'm giving the user a date. For example, the deadline is 05.05.2019. If the user does not pay by this date, the user will be both passive and unable to login to the system. How can I make such an algorithm? This means that if the user does not pay by the specified date, he will not be able to enter the system. It will also become passive. Can you help me with this? -
Why can't Django server access the Mac Address of the client which is connected to the server
From what I have studied from my computer networks course is that the packet consists of both IP address as well as MAC address during communication. In our OSI reference model, it is the network layer that does logical addressing and data link layer that does physical addressing, the one which actually assigns the MAC addresses of sender and reciever. So if a packet already consists of both IP address and MAC address then why our application server is not able to get the MAC address from the dataload? -
categroy and subcategory not showing properly django drf
I want to show subcategory inside category only: models.py: class Category(MPTTModel): name = models.CharField(max_length = 100) slug = models.SlugField() parent = TreeForeignKey('self',blank=True, null=True, related_name='children', on_delete=models.CASCADE, db_index = True) class MPTTMeta: unique_together = ('slug', 'parent') verbose_name_plural = "categories" order_insertion_by = ['name'] def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class SubCategory(models.Model): Sub_Category = models.ForeignKey(Category, on_delete = models.CASCADE) sub_category_name = models.CharField(max_length=100) serializers.py: class CategorySerializers(serializers.ModelSerializer): children = SubCategroySerializer(many=True, required=False) class Meta: model = Category fields = ('id','name','slug','children') class SubCategroySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name','slug', 'children') views.py: class CategoryView(generics.ListCreateAPIView): authentication_classes = [] permission_classes = [] pagination_class = None queryset = Category.objects.all() serializer_class = CategorySerializers urls.py: path('categories/', views.CategoryView.as_view()), when i making get request: http://localhost:8000/api/categories/ { "id": 8, "name": "Lifestyle", "slug": "lifestyle", "children": [ { "id": 9, "name": "Fashion", "slug": "fashion", "children": [] }, { "id": 18, "name": "Shopping", "slug": "shopping", "children": [] } ] }, { "id": 9, "name": "Fashion", "slug": "fashion", "children": [] }, { "id": 18, "name": "Shopping", "slug": "shopping", "children": [] }, as you can see fashion and shopping subcategory are showing inside lifestyle category and also showing in category. i just want to show … -
Django MySQL Filter records on dates after adding duration to date
My Model (with attribute values): MyModel: start_date = time.now() active_duration = 6 active_unit = 'm' # month Let suppose, I want to filter all the records which are still active in the current month. -
'InMemoryUploadedFile' object has no attribute 'startswith'
I am creating an image url api and getting the error is ```'InMemoryUploadedFile' object has no attribute 'startswith'``` Here is my models.py ``` class ShowImage(models.Model): image_name = models.CharField(max_length=255) image_url = models.ImageField(upload_to="settings.MEDIA") ``` Serializers.py ```class ShowImageSerializer (serializers.ModelSerializer): class Meta: model = ShowImage fields = ('id', 'image_name', 'image_url')``` Views.py ``` class ShowImageList(generics.ListCreateAPIView): queryset = ShowImage.objects.all() serializer_class = ShowImageSerializer # parser_classes = (FormParser, MultiPartParser) class ShowImageDetail(generics.RetrieveUpdateDestroyAPIView): queryset = ShowImage.objects.all() serializer_class = ShowImageSerializer ``` urls.py ```url(r'^show_image/', ShowImageList.as_view(), name= 'ShowImage'), ``` If i am trying to redirect url to ShowImageDetail then i am getting this error ```Expected view ShowImageDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. ``` -
Django REST Framework PUT doesn't create new object?
When sending PUT request to generics.RetrieveUpdateDestroyAPIView with a URL like site.com/demos/:id where id doesn't match any existing object in the database, a 404 response will be returned. But according to RFC 7231: The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload. Doesn't this violate the RFC? -
Combine multiple models(mysql) to template in Django
enter image description hereI have bootstrap design to bind my django crud like operation. which has Modal to insert data and table to show that data on same page. in insert Modal there is 2, 3 dropdown which i want to populate with my mysql db records . thats why i want to combine two modals in single def. views.py def deptlist(request): department = Department.objects.all() return render(request, 'manageemp.html', {'department': department}) def managemp(request): employees = Employee.objects.all() return render(request, "manageemp.html", {'employees': employees}) forms.py class EmpForm(ModelForm): class Meta: model = Employee fields = ["employee_id", "Name", "designation", "department_id", "manager_id", "date_of_joining","date_of_birth", "location_id", "email","contact_number", "password", created_by", "modified_by", "status", "user_type"] class dept(ModelForm): class Meta: model = Department fields = ["department_id", "department_name", "created_by", "modified_by", "status"] -
How could I display the value from two different tables in mySQL?
How could I display the value from two different tables in mySQL in which in (employee) table it contains several information like job_title_id. And on the second table (job_titles) table in contains job_title_id in which it is now a primary key and corresponding job titles like (CE0, Employee,etc). On my form I am pulling all the the information shown from the employee table,but then the job_title_id form employee table is a digit. How could I show its corresponding job_title from table 2? <div class="col-md-4 mb-3"> <div class="form-group bmd-form-group is-focused"> <label class="bmd-label-floating" for="jb_title">Job title</label> <input class="form-control" list="jb_title" name="jb_title" value="{{employee.job_title_id}}"> <datalist id="jb_title"> <option value= "1"> <option value="2" > <option value="3"> <option value="4"> <option value="5"> <option value="6"> <option value="7"> </datalist> </div> </div> </div> </div> Dropdown choices for now. views.py def save_employee_update(request): print(request.POST) emp_id = request.POST['employee_id'] fname = request.POST['first_name'] midname = request.POST['middle_name'] lname = request.POST['last_name'] pr_address = request.POST['present_address'] pm_address = request.POST['permanent_address'] zcode = request.POST['zipcode'] bday = request.POST['birthday'] email = request.POST['email_address'] pagibig = request.POST['pagibig_id'] sss = request.POST['sss_id'] tin = request.POST['tin_id'] sg_pr_id = request.POST['solo_parental_id'] # rg_sched = request.POST['reg_schedule'] usid = request.POST['userid'] defpass = request.POST['default_pass'] ustype = request.POST['user_type'] # j_title = request.POST['JobTitle'] employee = Employee.objects.get(employee_id=emp_id) employee.first_name = fname employee.middle_name = midname employee.last_name = lname employee.present_address = pr_address … -
how to use Q to search fields in list in django DRF without using querysets
def list(self, request): """" """ query = [Q(role_id=USER_ROLE['employer'])] first_name = [Q(request.GET.get('first_name')), Q.AND] last_name = [Q(request.GET.get('last_name')), Q.AND] if first_name: query = query.filter(first_name=first_name) if last_name: query = query.filter(last_name=last_name) user_obj = User.objects.filter(query) serializer_data = self.serializer_class(user_obj, many=True).data return custom_response(status=status.HTTP_200_OK, detail=SUCCESS_CODE['3007'], data=serializer_data) In this i am getting the error AttributeError: 'list' object has no attribute 'filter' -
What is the problem with my ajax Post or with code in my views.py file that the audio is not being retrieved
I am currently working on a project in Django which records audio on the browser and send it to the server for communication. i have already recorded the audio but when i try to POST it using an ajax request, an empty dictionary is received in views.py. here is my script where i have recorded the audio and tried to post an ajax request(record.html) <form method="POST" enctype='multipart/form-data'> {%csrf_token%} <audio scr="" name="audio" id="audio1"></audio><br> <input type="button" value="click me to record" id="recordbtn"> <input type="button" value="click me to stop record" id="stopbtn"> </form> var blob; navigator.mediaDevices.getUserMedia({audio:true}) .then(function success(stream){ var options; try{ options={memiType:'audio/webm;codecs=opus'}; } catch{ console.log('media type not supported') } mediaRecorder=new MediaRecorder(stream,options); mediaRecorder.ondataavailable=DataAvailable; recordbtn.onclick = function() { mediaRecorder.start(); console.log('recoding started'); } var chunks=[]; function DataAvailable(event) { chunks.push(event.data); console.log('dataprocessed'); var audio = document.getElementById('audio1'); audio.controls = true; blob = new Blob(chunks , { 'type' : 'audio/webm; codecs=opus' }); console.log(blob); chunks = []; var audioURL = URL.createObjectURL(blob); audio.src = audioURL; console.log('src assigned'); var token = '{{csrf_token}}'; console.log(token); var fd=new FormData(); fd.append('Blob1',blob); console.log(fd); console.log(fd.getAll('Blob1')); $.ajaxSetup({headers:{ "X-CSRFToken": token}}) $.ajax( { url:"{%url 'record:voice2pg'%}", type:'POST', contentType:'audio/webm; codecs=opus', data:fd, processData:false, success:function(){ alert('post successful') } } ) } stopbtn.onclick = function() { mediaRecorder.stop(); console.log('recording stopeed'); } }) .catch(function failure() { console.log('failure occured'); } ); views.py … -
Django; Problem with Displaying Items Appropriately
I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip. I am facing a problem. I have added two activities for Kuala Lumpur through Django admin. They are "Going to Botanical Garden" and "Going to Aquaria." When I go to http://127.0.0.1:8000/triplist/, I see this page: When I click on Kuala Lumpur, I see this page at http://127.0.0.1:8000/triplist/kuala-lumpur/: The two activities, called "Going to Botanical Garden" and "Going to Aquaria," cannot be separated. They are supposed to be displayed in this way: Activity name: Going to Botanical Garden Date: Dec. 4, 2019 Time: 12:34 p.m. Location: KL Sentral Item Type: Ticket Item Number: E12342 Activity name: Going to Aquaria Date: Dec. 4, 2019 Time: 1:58 p.m. Location: Bukit Bintang Item Type: Ticket Item Number: C45776 That means, there must be a … -
create_user() missing 1 required positional argument: 'password'
I am authenticating using email instead of username and i trying to add google authentication everything working fine but this is the error i'm getting: TypeError at /api/complete/google-oauth2/ create_user() missing 1 required positional argument: 'password' user model: class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('user must have email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length = 100, unique = True) First_Name = models.CharField(max_length = 100, null = True, blank = True) Last_Name = models.CharField(max_length = 100, null = True, blank = True) is_staff = models.BooleanField(default = False) is_superuser = models.BooleanField(default = False) is_active = models.BooleanField(default = True) last_login = models.DateTimeField(null = True, blank = True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = "email" EMAIL_FIELD = "email" REQUIRED_FIELD = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) ....................................................................................