Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting and setting data in sqlite in django
So, I'm trying to update some information in sqlite db in django. What I wanna do is the following: 1. I get existing data from the db 2. Based on the data, I do some calculations on the given data to make new data. 3. After getting the new data, I put them in the sqlite db. I wanna do the process above manually or automatically. I'm currently using django framework to make some web application. In my website, there's a bunch of stores having customer reviews, and I wanna make popularity points of each store based on calculations of the reviews. How can I update data of a column based on data of another column? -
How can I launch a new terminal to track my shell script triggered from Django?
I'm working on a Django 2.0.2 project built in python 3.6.3 which necessitates forking off a shell script as a background child process. This is currently how I'm currently triggering it: import subprocess subprocess.Popen(./master.sh) Unfortunately, this doesn't echo to the same terminal as the Dango server like other processes on the site. The pipeline outputs to a log.txt file after completing, but as some jobs will take hours to complete, I'd like a way to follow the job as it happens by spawning a new terminal. I have tried using gnome-terminal commands, but so far I've had no successful readout. -
How to create Multi User Account
Please am really need you guys help on how to use Django to create Multi-user Account. e.g Student, Lecturers, and Department login page(Admin).. in this system the department will be the Admin to register the lecturers inorder to have access and why the Student register on their own... Am design a project titled Online Assignment Submission System (it is my final year Project)... I really need you guyz help... on how to go about it using Django. -
How do I filter access to certain views based on time?
I am trying to create a system whereby users can only access a certain page at a time which they have booked. Users who have not booked access to this time will not be able to access the page. Essentially the page will only be available to users once they have booked! I am trying everything I can to do it see my files below. models.py class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) daterequired = models.DateTimeField(default=timezone.now) students = models.CharField(max_length=200) length = models.CharField(max_length=40, blank=True) def __str__(self): return str(self.user) forms.py class BookingForm(forms.ModelForm): class Meta: model = Booking exclude = ['user', ] widgets = { 'students': forms.TextInput(attrs={'placeholder': 'Number of Students'}), 'length': forms.TextInput( attrs={'placeholder': 'Time needed in hours'}), } views.py @login_required def choose(request): pod = Pod.objects.all() booking = Booking.objects.filter(user=request.user) bookingtime = booking.daterequired.strftime("%Y-%m-%d %H:%M:%S") currenttime = datetime.now().strftime("%Y-%m-%d %H:%M:%S") timedifference = currenttime - bookingtime if timedifference <= booking.length: return render(request, 'choose.html', {'pod': pod, 'booking': booking}) else: return HttpResponse("<p>NO ACCESS</p>") I am not sure how far off I am at the moment but would appreciate any help in the right direction. Thanks guys! -
Django not passing data to views on POST request
I've created a dropdown menu that is supposed to pass data to a view that'll help filter a queryset. However, it doesn't seem like the data is actually being passed to the view. Below is the relevant code I've written. template.html <!-- Query based content for dropdown menu --> <form method="POST" action="{% url 'property-selected' %}" id="property-select"> {% csrf_token %} <select class="dropdown-content" onchange="this.form.submit()" name="property-select"> {% if current_user_meters %} <option disabled selected> -- select an option -- </option> {% for meter in current_user_meters %} <option class="dropdown-menu-option" value="{{meter.id}}">{{meter.name}}</option> {% endfor %} {% else %} <option>You don't have any meters</option> {% endif %} </select> </form> views.py def property_selected(request): if request.method == 'POST': selection = request.POST.get('property-select') current_user_groups = Group.objects.filter(id__in=request.user.groups.all()) current_user_properties = Property.objects.filter(groups__in=current_user_groups) current_user_meters = Meter.objects.filter(meter_id__in=current_user_properties) selected_meters = Meter.objects.filter(name=selection) selected_meter_data = MeterData.objects.filter(name=selection).order_by('date') return render(request, 'properties/property-selected.html', { 'current_user_meters': current_user_meters, 'selection': selection, 'selectected_meters': selected_meters, 'selected_meter_data': selected_meter_data, }) for the querysets in the views file, the "selection" variable doesn't seem to be getting anything, which is where I want the data from the POST request to go. I want the data from the POST request to go there so my "selected_meters" and "selected_meter_data" queries will work as intended. Thanks! -
EditForm won't save the image from my ImageField
So basically I am just trying to change the data of my user. Everything works in the edit form, except that the image won't get saved. It gets passed in the form, my form has enctype enabled and also added request.FILES in the view, but nothing seems to work. When debugging, I only get that my form has no such 'photo' attribute. class StudentEditForm(forms.ModelForm): email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'placeholder': "E-mail Address", 'class': 'email'})) name = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': "Name", 'class': 'name'})) surname = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': "Surname", 'class': 'surname'})) photo = forms.ImageField(required=True, error_messages={'required': 'A profile picture is required.'}, widget=forms.FileInput(attrs={'class': 'profile_pic'})) phone = forms.CharField(max_length=15, required=True, validators=[RegexValidator(regex='^[0-9+]+$', message='Not a valid phone number.')], widget=forms.TextInput(attrs={'placeholder': "Phone Number", 'class': 'phone'})) class Meta: model = Student fields = ('email', 'name', 'surname', 'phone', 'photo') if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, request.FILES, instance=student) if form.is_valid(): user.email = form.cleaned_data['email'] user.first_name = form.cleaned_data['name'] user.last_name = form.cleaned_data['surname'] user.save() form.save() return redirect('index') {% if user.is_student %} <div id="profile-edit"> <a id="close" href="{% url "index" %}"><i class="fas fa-times"></i></a> <form class="main-form" method="post" enctype="multipart/form-data"> {% csrf_token %} <h3 id="sign-title">Edit Profile</h3> <p class="field"> {{ form.email }}</p><br> <p class="field"> {{ form.name }}</p><br> <p class="field"> {{ form.surname }}</p><br> <p class="field"> {{ form.phone }}</p><br> <label id="file1" … -
Django POST shows in form, but doesn't come through to the next view
I have a simple form such as: <form action = "{% url 'endresult' %}" form method = "POST"> {% csrf_token %} <div class="well"> <h4 style="margin-top: 0"><strong> Student Details </strong></h4> <div class="row"> <div class="form-group col-md-4"> <label/> Student ID <input class="form-control" type="text" name = "studentpost" placeholder= "{{student.studentid}}" readonly> </div> </form> </div> The student ID does show up in my form, but when I try to get the results from endresult it shows up as a blank, if i try to call the studentid i get none. Why is this? def endresult(request): postedstudent = request.POST.get('studentpost') print(f"postedstudent : {postedstudent }") studentid = request.POST.get('student.studentid') print(f"studentid : {studentid }") return render(request, 'submitted.html') Here is my output: posteduser: ntname: None -
Error in accessing file in S3-Bucket using Django
I am using Django-mailbox, AWS-EC2 instance and AWS-S3 , So I am trying to send an attachment with mail and receive it on S3 bucket and I am successful to achieve this. Next while accessing that attachment file from saved path, it showing me following error, however file is saved successfully in given path, you can see in folder dir. My folder structure is as follows Let me know if any further details needed. -
How to pass values into python script from django views
When a user logins in, they provide a username, password, serverid. I want to pass that into a script that would connect them to a server. How do I do so and also get the output of the script to see if it was executed properly? -
Django use queryset in template
I want to check a field(=is_seller) of the table(=UserProfileInfo) and if it has some value(=0) , make some part of template disabled and these are my codes : models.py : class UserProfileInfo(models.Model): user=models.OneToOneField(User,related_name='profile') companyname=models.CharField(blank=True,null=True,max_length=128,verbose_name=_('companyname')) phone_regex = RegexValidator(regex=r'^\d{11,11}$', message=_(u"Phone number must be 11 digit.")) cellphone = models.CharField(validators=[phone_regex], max_length=17,verbose_name=_('cellphone')) tel = models.CharField(blank=True,null=True, max_length=17,verbose_name=_('tel')) state=models.CharField(,max_length=128,verbose_name=_('state')) city=models.CharField(,max_length=128,verbose_name=_('city')) address=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('address')) is_seller=models.CharField(blank=True,null=True, max_length=2,verbose_name=_('seller')) def __str__ (self): return self.user.username class Meta: verbose_name=_('UserProfileInfo') verbose_name_plural=_('UserProfileInfos') view.py: def stock(request): st_form=StocksForm(None) is_seller=UserProfileInfo.objects.filter(user=request.user).values("is_seller") if request.method == "POST": st_form =StocksForm(data=request.POST) print("<<<<<<<<<<<"+str(is_seller)) if st_form.is_valid(): instance=st_form.save() id_name=(st_form.cleaned_data.get("name")) instance.name=StocksName.objects.filter(id=id_name).values("name")[0]['name'] #becouse of autocomplete it was saving the value by its id and i converted to name instance.user=request.user instance.save() messages.success(request,"SUCCESSFUL" ,extra_tags="savestock") else: messages.error(request, "ERROR!") else: st_form=StocksForm() return render(request,'BallbearingSite/stock.html',{'stocks_form':st_form,'seller':is_seller}) template.html : it doesnt work and i dont know how to correct it : {% for item in seller %} {% if item.is_seller=="0" %} <p>show some message</p> {% endif %} {% endfor %} -
Pass from login a variable to know is the first time the user login
First time the use logins, I wan to show him a multi step setup. How can I pass from login a variable to know is the first time the user login ? -
What is better for an embedded device - Node.js or Django?
Background: I'm currently developing a project on Raspberry Pi - for now I want to gather data from a sensor and display it on a web page with some neat graphs and stuff like that but I plan to expand it sooner or later. I'm facing a dilemma right now: which framework should I use? I learned about Node.js from this book and I really like the concept - also the authors are giving quite a few reasons why it's good for embedded devices. On the other hand, I learned about the existence of Django and since I'm working with python on a daily basis I thought using it would be a better idea. I'm torn apart now - I'd like to use technology that would be most suitable in embedded world (and which would educate me the most) and yet I'm kinda afraid to jump into deep waters of a language I don't really know (JavaScript). If somebody with more experience with web technology and embedded devices could help me out, that would be most helpful! In short: What would be the best option for an embedded device (and for me): Node.js or Django? -
How do I handle files stored as blob from react-dropzone
When I add files to the file field using react-dropzone and pass it to a remote Django backend, it passes the values: {u'preview': u'blob:http://127.0.0.1:8080/17c3c181-e361-44f1-8ee8 -6476847aeffb'} . How do I handle that as a file for uploading to S3 using a Django Rest API backend? -
Can't Access the file from path Aws + Django
I am using Django-mailbox, an AWS-EC2 instance and AWS-S3 , I am trying to send an attachment with mail and receive it on S3 bucket and I am successful to achieve this. Now while accessing that attachment file from path, it is shows me following error, how file is saved successfully in given path My folder structure is as follows Let me know if any further details needed. -
Django Redirect Solution
In django I am having problems redirecting. Here is my urls.py for the app: urlpatterns = [ path('bkb/', views.index, name = 'index'), path('bkb/<int:department_code>/', views.lcdcl, name ='lcdcl'), path('bkb/<int:department_code>/<int:cl_id>/', views.lcdcl2, name ='lcdcl2'), path('bkb/addcl2/' , views.addcl2, name='addcl2'), path('bkb/<int:department_code>/<int:cl_id>/<int:edit_id>/edit/', views.editdata, name ='editdata'), path('bkb/<int:dept_code>/<int: id>/revers/', views.revers, name ='revers'), here is my view.py for edit data: def editdata(request, department_code, cl_id, edit_id): editdata = CL2.objects.get(pk=edit_id) cl2_info = LCD.objects.get(pk=cl_id) a = department_code b = cl_id if request.method == "POST": forms = CL2Form(request.POST, instance=editdata) if forms.is_valid(): editdata = forms.save(commit=False) editdata.save() return redirect('/bkb/lcdcl2/') else: forms = CL2Form(instance=editdata) context = {'forms' : forms} return render(request, 'bkb/lcdcl2form.html', context) My question is: I want to go to path('bkb/<int:department_code>/<int:cl_id>/', views.lcdcl2, name ='lcdcl2'), from return redirect('/bkb/lcdcl2/') in views. -
getting image source using beautiful soup
here is my code but in this i get source of first product scrap = requests.get('https://www.walmart.com/search/?query=s5&cat_id=0') content = BeautifulSoup(scrap.text, "html.parser") categories = content.findAll("div", {"class": "search-result-gridview-item-wrapper"}) for category in categories: name = category.find("div", {"class": "search-result-product-title gridview"}) title = name.find('a').text price = category.find("div", {"class": "search-result-productprice gridview enable-2price-2"}) p = price.text k=category.find("div",{"class":"search-result-gridview-item clearfix"}) image=k.find("div",{"class":"display-inline-block pull-left prod-ProductCard--Image"}) img = image.a.find("img", {"class": "Tile-img"})['src'] print (img) href=image.find('a')['href'] product_href.append(href) image_source.append(img) product_name.append(title) product_price.append(p) output of print(img) //i5.walmartimages.com/asr/76f06b1a-b180-43dd-91a7-566de4c1be6c_1.4d16dafe13a43abb89aaeab9927d4152.jpeg?odnWidth=180&odnHeight=180&odnBg=ffffff //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif -
Django Dynamic Form Filter
I'm creating a web based ERP-like system in Django 2.0. In a page, I have a form with all the Work Orders or so entries (stored in DB). I would like to have in the first line of the form (below the headers) a input field for each column where I type and it dynamically/instantly filter the form rows. Example: COD | DESCRIPTION | DATE | ETC. search field | search field | search field | search field So when I type any character in any column, instantly the form is updated showing the filter results. Which technique I should use for this? Is Ajax the tool for this job? -
Creating an REST API Django
First thing that I would like to say is that I have no previous experience with python and any framework python related. However, I have programming experience. So, I want to create an REST API using pythona with frameworks djnago and djangorestframework. I have managed to create the database (using postgresql) and also managed to to create the initial migration. However, I believe that that was the easiest part and I have some questions about the thing that I'm about to implement: First I want to create an authentication system. I saw that djangorestframework it's able to manage authentication by itself but I was not able to make it run. Can you please guid me to some good tutorials/provide code samples and briefly explain? After initial migration I saw that django created some tables for authentication and session management by itself (auth_user, auth_user_groups, etc). Is there any way to use my own model for user? Also, i do believe that I wont need all the features that django offerrs (e.g auth_user_groups). Its there any way to remove those unwanted functionalities? I was able to create an API endpoint (by following a tutorial) that returns some data (based on a model, … -
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> django project
gunicorn status gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor Active: failed (Result: exit-code) since Mon 2018-03-12 18:30:15 UTC; Process: 3535 ExecStart=/home/mike/movingcollage/movingcollageenv/bin/ Main PID: 3535 (code=exited, status=1/FAILURE) Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: File "/home/mike/mo Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: time.sleep(0.1) Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: File "/home/mike/mo Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: self.reap_workers Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: File "/home/mike/mo Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: raise HaltServer( Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: gunicorn.errors.HaltS Mar 12 18:30:15 ubuntu-2gb-nyc3-01 systemd[1]: gunicorn.service: Main pr Mar 12 18:30:15 ubuntu-2gb-nyc3-01 systemd[1]: gunicorn.service: Unit en Mar 12 18:30:15 ubuntu-2gb-nyc3-01 systemd[1]: gunicorn.service: Failed 29 ubuntu-2gb-nyc3-01 systemd[1]: gunicorn.service: Failed nginx error log: 2018/03/12 04:59:08 [error] 1562#1562: *1787 connect() to unix:/home/mik e/movingcollage/movingcollage.sock failed (111: Connection refused) whil e connecting to upstream, client: 107.205.110.154, server: movingcollage .com, request: "GET / HTTP/1.1", upstream: "http://unix:/home/mike/movin gcollage/movingcollage.sock:/", host: "movingcollage.com" My config is ok, this used to work; I pulled some new application code and am now getting a 502 bad gateway error (before I pulled the application code the site worked fine). I already did service gunicorn restart and systemctl restart gunicorn and am still getting the 502 bad gateway error. Can anyone help? This is a django project, for what it's … -
Wagtail 2.0 installation error
When I install a fresh copy of wagtail 2.0, the requirements file still wants to call for wagtail 1.14. I change that to 2.0 and django to 2.0, rerun the import and I get this error: Traceback (most recent call last): File "./manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/Users/johnbriggs/.virtualenvs/wagtail/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/johnbriggs/.virtualenvs/wagtail/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Users/johnbriggs/.virtualenvs/wagtail/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/johnbriggs/.virtualenvs/wagtail/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Users/johnbriggs/.virtualenvs/wagtail/lib/python3.6/site-packages/django/apps/config.py", line 123, in create import_module(entry) File "/Users/johnbriggs/.virtualenvs/wagtail/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'wagtail.wagtailforms' Here is my updated requirements.txt file: Django>=2.03 wagtail>=2.0 I can run these fine, but everything bugs at at the migrate process. -
Channels Websocket immedialty disconnecting with ssl
I tried to make run the tutorial from the channels docs on my production server, using ssl. After a few hours i managed to get a connection but it instantly disconnects : None - - [12/Mar/2018:17:42:22] "WSCONNECTING /ws/chat/bibou/" - - None - - [12/Mar/2018:17:42:22] "WSCONNECT /ws/chat/bibou/" - - None - - [12/Mar/2018:17:42:23] "WSDISCONNECT /ws/chat/bibou/" - - my stack is ubuntu 16.04 nginx 1.10.3 channels==2.0.2 daphne==2.1.0 channels-redis==2.1.0 Twisted==17.9.0 I have the exact copy paste of the code from the tutorial, except for this part in room.html var chatSocket = new WebSocket( 'wss://' + window.location.host + ':8443/ws/chat/' + roomName + '/'); and here is my nginx conf server { #http listen 80; server_name groover.co; root /usr/share/nginx/html; include /etc/nginx/default.d/*.conf; location / { return 301 https://$server_name$request_uri; } } server { #https listen 443 ssl; listen 8443 ssl; server_name groover.co; root /usr/share/nginx/html; ssl_certificate "/etc/letsencrypt/live/groover.co/fullchain.pem"; ssl_certificate_key "/etc/letsencrypt/live/groover.co/privkey.pem"; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; add_header Strict-Transport-Security "max-age=31536000"; include /etc/nginx/default.d/*.conf; location /static/ { root /home/ubuntu; } location /media/ { root /home/ubuntu; } location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://unix:/home/ubuntu/tlebrize/Groover.sock; } location /ws/ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header … -
How to display python dictionary in a Django template in bullet list format?
How do I alter the following Django template code: <ul> {% for key, value in real_prices.items %} #real_prices is a dictionary <li>Price: {{ key }}, link: {{value}}</li> {% endfor %} </ul> To display the dictionary items on a page like this: Price: key, link: value Price: key, link: value Price: key, link: value and so on... The current code only displays the dictionary as a whole. For reference, here's the view: def test(request): prices = [] real_prices = [] links = [] url = 'https://www.airbnb.pl/s/Girona--Hiszpania/homes?refinement_paths%5B%5D=%2Fhomes&query=Girona%2C%20Hiszpania&place_id=ChIJRRrTHsPNuhIRQMqjIeD6AAM&checkin=2018-04-04&checkout=2018-04-22&children=0&infants=0&adults=2&guests=2&allow_override%5B%5D=&price_max=252&room_types%5B%5D=Entire%20home%2Fapt&min_beds=0&s_tag=Ph6ohhjw' response = requests.get(url) soup = bs4.BeautifulSoup(response.text) #prices page_selectors = soup.select('._1bdke5s') print(len(page_selectors)) last_page_selector = page_selectors[len(page_selectors) - 4]##############-15 last_page_selector = last_page_selector.getText() for x in range(0, int(last_page_selector)): response = requests.get(url + '&section_offset=' + str(x)) response_text = response.text soup = bs4.BeautifulSoup(response_text) spans = soup.select('._hylizj6 span') for i in range(0, len(spans)): prices.append(spans[i].getText()) for price in prices: if 'zł' in price: real_prices.append(price) #links a_tags = soup.find_all('a') for tag in a_tags: if '_15ns6vh' in str(tag.get('class')): link = 'https://www.airbnb.pl' + str(tag.get('href')) links.append(link) dictionary = dict(zip(real_prices, links)) -
How to implement phonetic typing for Indian languages in django-ckeditor
I have integrated CKeditor in my application with the help of django-ckeditor package. I want to add support for phonetic typing in English and transliterating the words in Indian Language (such as Hindi), very similar to what quillpad does. Any hint/help to achieve the desired result will be highly appreciated. -
Create a session in Django Rest Framework
I have a Django Rest Framework API that authenticates through Firebase. On the frontend after the user has logged in with Firebase, a token is sent to the backend that is verified, Firebase returns a user_id after verification and this is used to return the current user. I have written a simple custom authentication class that handles the token verification. The token is set as tokenid header. Here's the code: from rest_framework.authentication import BaseAuthentication from rest_framework import exceptions import firebase_admin from firebase_admin import credentials, auth from .models import User CREDS_PATH = 'PATH_TO_CREDS.json' cred = credentials.Certificate(CREDS_PATH) default_app = firebase_admin.initialize_app(cred) class FirebaseAuthentication(BaseAuthentication): """Authenticate the user and get its info from Firebase. The token is sent in the request as idToken and veryfied with the Firebase admin. """ def authenticate(self, request): """Actual authentication happens here.""" token = request.META.get('HTTP_TOKENID') if token: try: firebase_user = auth.verify_id_token(token) except ValueError: return None if not firebase_user: return None user_id = firebase_user.get('user_id') try: user = User.objects.get(id=user_id) print(user) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) else: # no token provided return None Then I create a View that is connected to /login route and that uses FirebaseAuthentication and SessionAuthentication. The idea is for this endpoint to verify the … -
django username "disappears" when going in another view
Before I start, I'd like to point out that I have already surfed half of the internet in search of a possible solution, but nothing really solved my problem. That said, I'm quite the beginner in Django and Python so this could be a simple problem and maybe I'm just too dumb to figure it out. So, here's the thing. I'm working on a project for college and I have to make a website that emphasises primarily backend. I chose Django as a framework and so far I've been able to have new users register and also log in and out. The problem is maybe not dramatic, but annoying for me at least. To be more clear, After a user logs in, I want to show his name in the top bar alongside the logout button. So, the log in panel is as such: This part is fine, I just hit Log In and it works. Then I get here: As you can see, at first, the username is displayed in the top bar alongside the logout. But if I click on "Whatever" or the username itself, it goes away. This may have something to do with the fact that …