Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query api: complex subquery
I wasted lots of time trying to compose such query. Here my models: class User(Dealer): pass class Post(models.Model): text = models.CharField(max_length=500, default='') date = models.DateTimeField(default=timezone.now) interactions = models.ManyToManyField(User, through='UserPostInteraction', related_name='post_interaction') class UserPostInteraction(models.Model): post = models.ForeignKey(Post, related_name='pppost') user = models.ForeignKey(User, related_name='uuuuser') status = models.SmallIntegerField() DISCARD = -1 VIEWED = 0 LIKED = 1 DISLIKED = 2 And what i need: Subquery is: (UserPostInteractions where status = LIKED) - (UserPostInteractions where status = DISLIKED) of Post(OuterRef('pk')) Query is : Select all posts order by value of subquery. I'm stuck at error Subquery returned multiple rows Elp!!)) -
show custom django form error in template
I am writing a view to send a password reset email to users. I am checking if the email entered by the user is registered by using the clean method in the forms.py, this is working correctly although I can not get the custom error message to display in the django template. views.py def send_forgotten_password_email(request): heading = 'Reset Password' if request.method == 'POST': form = ForgottenPasswordForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] form = ForgottenPasswordForm() return render(request,'authentication/forms/forgotten_password.html',{ 'form':form, 'heading':heading, }) forms.py class ForgottenPasswordForm(forms.Form): email = forms.CharField( label='Email:', widget= forms.EmailInput(attrs={'class':'form-control','placeholder':'Enter email'}) ) def clean_email(self): email = self.cleaned_data['email'] email = get_object_or_none(User,email=email) if not email: raise forms.ValidationError("Email not found.") return email template {% extends "base.html" %} {% load static %} {% block title %} Forgotten Password {% endblock title %} {% block content %} <div class="row"> <div class="col col-sm-12 col-md-5 col-lg-5"> <div class="card"> <div class="card-body"> <h4 class="card-title">{{heading}}</h4> <div class="alert alert-danger" role="alert"> {{form.non_field_errors}} {{form.errors}} {{forms.errors}} {{form.email.errors}} </div> <form method="POST"> {% csrf_token %} <div class="form-group"> <label>{{form.email.label}}</label> {{form.email}} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> </div> {% endblock content %} -
Django allauth connection error
i having an issue when i trying to signup a new user, django return this message: ConnectionRefusedError at /account/signup/ [Errno 61] Connection refused i'm using django 1.11.5 with allauth 0.33 Could someone help me to solve it please? Thank you. forms.py: class SignupForm(forms.Form): first_name = forms.CharField(max_length=30, label='Nome') last_name = forms.CharField(max_length=30, label='Cognome') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() settings: ACCOUNT_SIGNUP_FORM_CLASS = "custom_profile.forms.SignupForm" ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_AUTHENTICATION_METHOD = 'email' LOGIN_REDIRECT_URL = '/' ACCOUNT_ADAPTER = 'custom_profile.adapters.HandyAdapter' -
Django file download?
I have two views "ans_page" and "downloads", where "ans_page" generates a file (library.csv) into a directory "output", further "ans_page" render an html page called "ans.html" it shows a table with data and a button just beneath the table to download a file from a directory "output" which is a part of an app called FragBuild, button is provided with a hyperlink which is associated with "Downloads" views URL, my expectation is that if some one click on the download button it should start a download but it showing an error instead like given bellow: View def Downloads(request): file_path = os.path.join(os.path.split(os.path.abspath(__file__))[0],'output','library.csv') file_wrapper = FileWrapper(file(file_path,'rb')) file_mimetype = mimetypes.guess_type(file_path) response = HttpResponse(file_wrapper, content_type=file_mimetype ) response['X-Sendfile'] = file_path response['Content-Length'] = os.stat(file_path).st_size response['Content-Disposition'] = 'attachment; filename=%s' % smart_str('library.csv') and URL like this: url(r'^ans_page/Downloads$', views.Downloads, name='Downloads'), a button in html to initiate download like this: <div class=""> <button class="btn btn-primary" style="width:40; margin-bottom: 30px; margin-left: 300px "><a href="{% url 'Downloads' %}"> Download Peptide as CSV file </a> </button> </div> But when i clicked on a button to initiate download it shows an error: ValueError at /ans_page/Downloads The view FragBuild.views.Downloads didn't return an HttpResponse object. It returned None instead. How can I solve this problem i have struggle … -
Django OneToOneField post_save cant call int object
I want to extend my 'User' model with the 'Profile' model. To facilitate this I've created the following model. I wanted to have the linked 'Profile' model be automatically created with each new 'User' model. Based on some comments on stackoverflow / research on the internet (simpleisbetterthancomplex) I came with the following solution: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') #Pushup related stats total_pushups = models.IntegerField(default=0) best_consecutive = models.IntegerField(default=0) week_streak = models.IntegerField(default=0) save = models.IntegerField(default=000) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() However, every time I run this (whether through unit tests or 'create superuser' - I have no vies yet, I'm practicing TDD) I get the following error: TypeError: 'int' object is not callable Does anyone here know what I am doing wrong? -
Django migration with python3.6 ERROR:root:code for hash sha3_224 was not found
Hello I read Django tutorials and I have an error related to specific sha3_224 hash function during the migration process. How to solve this problem? Thank you. (venv) linuxoid@linuxoid-ThinkPad-L540:~/myprojects/myproject$ python manage.py makemigrations ERROR:root:code for hash sha3_224 was not found. Traceback (most recent call last): File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 121, in __get_openssl_constructor f = getattr(hashlib, 'openssl' + name) AttributeError: module '_hashlib' has no attribute 'openssl_sha3_224' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 243, in globals()[__func_name] = __get_hash(__func_name) File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 128, in __get_openssl_constructor return __get_builtin_constructor(name) File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 113, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha3_224 ERROR:root:code for hash sha3_256 was not found. Traceback (most recent call last): File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 121, in __get_openssl_constructor f = getattr(hashlib, 'openssl' + name) AttributeError: module '_hashlib' has no attribute 'openssl_sha3_256' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 243, in globals()[__func_name] = __get_hash(__func_name) File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 128, in __get_openssl_constructor return __get_builtin_constructor(name) File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 113, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha3_256 ERROR:root:code for hash sha3_384 was not found. Traceback (most recent … -
why using "fieldsets" causing duplicate tab for the main model in the inlines tabs
I have in my admin change page two inlines and they displayed fine without using "fieldsets", but after using "fieldsets" I have extra tab for the main model in the inlines. here some images for the tabs and for the "fieldset" code. fieldsets = ( ("barber", { "fields": <some fields> }), ("Balance", { "classes": ("collapse",), "fields": <some fields> }), ("Schedule", { "classes": ("collapse",), "fields": <some fields> }), ) before using "fieldset" after using "fieldset" -
How to include a calendar management module easily within a Django project
I am developing a Python Django platform, using Django, html, and a bit a javascript. This platform aims to manage bookings. I am stuck on a calendar module which I could insert within my html pages. The calendar module would read schedule availabilties and redirect to a booking page when clicked on it. Ideally, I would like something similar to this website : https://www.doctolib.fr/medecin-generaliste/paris (class 'dl-search-result-calendar'). I know it might be coded in AngularJS and Ajax, although my knowledge of this 2 technos is very limited. My question is, what would be the easiest solution to insert such a calendar module, with booking redirect module ? Any help is welcome Thank you -
SEARCH BOX NOT DISPLAYING RESULTS DJANGO
Hello Guys am trying to implement a simple search box on my blog project to be able to display searched posted on my site. Please do have a view at my code and tell me whats wrong MODEL.PY class EntryPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) tags = models.ManyToManyField(Tag) body = models.TextField() slug = models.SlugField(max_length=200) publish = models.BooleanField(default=True) created= models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) VIEWS.PY def search(request): post= EntryPost.objects.all() search_text = request.GET.get('q', '').distinct() results = post.filter(body__icontains=search_text) return render(request, 'search.html', {'results': results}) URL.PY url(r'^search/results$', search, name='search'), SEARCH.HTML {% extends "base.html" %} {% block search_posts %} {% if entrypost.exists %} {% for entrypost in entrypost %} <div class="post"> <h2><a href="{% url "entry" slug=entrypost.slug %}">{{ entrypost.title }}</a></h2> <p class="meta"> {{ entrypost.created }} | Tagged under {{ entrypost.tags.all|join:", " }} </div> {% endfor %} {% endif %} {% endblock %} SEARCH BOX CODE <form method="GET" action='{% url 'search' %}'> <input type="text/submit" name="q" placeholder='search posts'> <input type="submit" value="search"> </form> The Page renders successfully to search.html but no results on the searched post can be seen. -
Unable to show content from 3rd model db in django
I am building a website based on django.Find below my models: model.py class Projectname(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Jenkinsjobsname(models.Model): projectname=models.ForeignKey(Projectname) jobsname = models.CharField(max_length=200) def __str__(self): return self.jobsname class Jenkinsjobsinformation(models.Model): jobinformation=models.ForeignKey(Jenkinsjobsname) build = models.IntegerField() date = models.DateField(null=True) view.py def index(request): project_name=Projectname.objects.order_by('-name')[:5] context = {'categories': project_name} return render(request,'buildstatus/index.html', context) def detail(request,projectname_id): project_name=Projectname.objects.order_by('-name')[:5] jobs=Projectname.objects.get(pk=projectname_id) context = {'jobs': jobs, 'categories':project_name} return render(request,'buildstatus/detail.html', context) def jobdetail(request,projectname_id,jobinformation_id): project_name=Projectname.objects.order_by('-name')[:5] jobs=Projectname.objects.get(pk=projectname_id) job_detail=Jenkinsjobsname.objects.get(pk=jobinformation_id) context = {'jobs': jobs,'categories':project_name,'job_detail':job_detail} return render(request,'buildstatus/job_detail.html', context) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<projectname_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<jobinformation_id>[0-9]+)/$', views.jobdetail, name='job_detail'), ] detail.html {% extends "base.html" %} {% block text1 %} {% if categories %} <ul> {% for category in categories %} <li><a href ="{% url 'detail' category.id %}">{{category.name }}</a></li> {% endfor %} </ul> {% else %} <strong>There are no test categories present.</strong> {% endif %} {% endblock %} {% block text %} <ul class = "nav nav-tabs" > {% for jenkinsjobsname in jobs.jenkinsjobsname_set.all %} <li><a href= "#">{{jenkinsjobsname.jobsname}}</a></li> {% endfor %} </ul> {% endblock %} index.html {% extends "base.html" %} {% block text1 %} {% if categories %} <ul> {% for category in categories %} <li><a href ="{% url 'detail' category.id %}">{{category.name }}</a></li> {% endfor %} </ul> {% else %} <strong>There are no … -
Call django rest framework CRUD methods from single page angular application
I'm trying to create a single page application that would enable to list, create, update and delete users without refreshing the page. I'm using Django Rest framework and AngularJS which seem to me a good idea for this. I want to use my html template so I created a UserListView class derived from TemplateView and defined the CRUD methods in the view.py by myself like this: class UserListView(TemplateView): template_name = "user_list.html" renderer_classes = [TemplateHTMLRenderer] def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) def create(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def update(self, request, username=None): user = self.get_object(username) serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def destroy(self, request, username=None): user = self.get_object(username) user.delete() return Response(status=status.HTTP_204_NO_CONTENT) After that I created a template user_list.html like this: {% extends 'general_list.html' %} {% block ng_controller %}userCtrl{% endblock ng_controller %} {% block content %} {% verbatim %} <div class="table-responsive"> <table class="table"> <thead> <tr> <th>Username</th> <th>Password</th> <th>Role</th> <th>Calories per day</th> <th></th> </tr> </thead> <tbody> <tr ng-repeat="user in user_list"> <td>{{ user.username }}</td> <td>{{ user.password }}</td> <td>{{ user.role }}</td> <td>{{ user.calories_per_day }}</td> <td><button ng-click="delete(user)">Delete</button></td> </tr> </tbody> </table> </div> {% endverbatim %} <form ng-controller="userCtrl" … -
Can't make messages with Django's JavascriptCatalogView
I use Djnago with sites framework. The static root has the following structure: css js site1.bundle.js site2.bundle.js site3.bundle.js When I try to make messages (python manage.py makemessages -d djangojs -a) the command above extracts messages only from the site1.bundle.js and ignores other files. How can I make single translation file from all JS files? -
How to create a system using Django so that a naive user can edit the content of the Django website without using HTML code?
I have created a personal website for someone using Django (however it wasn't required since website is very simple, but it was their demand!). Now they want that they can edit the content of pages without editing HTML. They now want me to use Django-CMS, I again disagree as I don't think it is required (?) . What should I do to create a system so they can edit the webpage without messing with templates and HTML? The webpages contains few listings, say of 'Books', 'Recent Visits'... etc. I was thinking to create a model for each of them, and let them edit the database using admin, which will then be used by Django to create a dynamic page for their site. Do you think CMS would be a better choice (but then they don't really need me to do anything, they can do it by themselves!) ? I perhaps didn't put my problem properly, but if anyone can understand it, then please give me your suggestions. I can provide more details if anyone wants. -
Why does Django try the wrong url pattern?
Django tries the wrong url pattern but I can not find my mistake. urls.py url(r'^profile/(?P<userid>(\d+))/$', profile_view, name="profile"), url(r'^details/(?P<advertisementid>(\d+))/$', details_view, name='details'), views.py def details_view(request, advertisementid): advertisement_data = Advertisement.objects.get(id=advertisementid) return render(request, "details.html", {"advertisement_data": advertisement_data}) def profile_view(request, userid): advertisements = Advertisement.objects.filter(user__id=userid) return render(request, "profile.html", { 'advertisements': advertisements } ) details.html (from where I want to resolve to the users profile) <a href="{% url 'profile' userid=advertisement_data.user.id %}" style="text-decoration:none;"> <input type="submit" class="details-btn-profile" value="Profile"></a> <a href="{% url 'chat_view_with_toid' advertisementid=advertisement_data.id %}" style="text-decoration:none"> <input type="submit" class="details-btn-contact" value="Kontakt"></a> When I click on button class="details-btn-profile" Django gives me this error: Reverse for 'details' with no arguments not found. 1 pattern(s) tried: ['details/(?P(\d+))/$'] Why does it resolve to details ? Any ideas ? -
Django - Get Default value from another Model Field
I came across this strange problem in django where I have 3 models Books, Language, Book_language where i map book to its language. from django.db import models class Book(models.Model): title = models.CharField(max_length=200) year = models.IntegerField() class Language(models.Model): name = models.CharField(max_length=50) class Book_language(models.Model): book = models.ForeignKey(Book) language = models.ForeignKey(Language) other_title # default to title So far i am creating a book and with title and later assigning with language so the title is same for all languages, later i understand that the title may not be the same in all languages, so i want other_title to be default to title if not mention, and appear in django admin when i map with language. -
Send an Image and some metadata to Django
Is there is way to send an image with some custom metadata to django server with python script ?. django server and python script is in different servers -
How to implement dropdown list of user for sharing of file in django
i have created model, class share_files(models.Model): files = models.CharField(max_length=300) from_user = models.CharField(max_length=50) to_user = models.CharField(max_length=50,choices=user_list,default=None) but i want to_user and files as choice fields. and i want implement dropdown for column to_user and files. for example, in dropdown of to_user list of user will come from django model User. and form is class Share_file(forms.ModelForm): class Meta: model = share_files fields = ('files', 'to_user') how to proceed? -
Procfile for Heroku not working properly - Django using Waitress
Struggling to the Procfile I'm using for heroku working. Trying to learn how to get a basic django website up and running and have built something from scratch. I use windows on my PC to tinker around so decided on using waitress but perhaps gunicorn would be easier? If I can't work it out I'll just use a template from heroku and build from that but I would rather not get rid of what i've done so far. This is my directory structure. Root +--- .git Include Lib Scripts Scripts Static tcl src +--- � db.sqlite3 � manage.py � +---alex1 � � forms.py � � settings.py � � urls.py � � wsgi.py � � __init__.py � � � +---__pycache__ � settings.cpython-36.pyc � urls.cpython-36.pyc � wsgi.cpython-36.pyc � __init__.cpython-36.pyc � +---profiles � admin.py � apps.py � forms.py � models.py � tests.py � views.py � __init__.py � +---migrations � � 0001_initial.py � � 0002_profile_description.py � � 0003_auto_20170905_1654.py � � 0004_auto_20170905_1659.py � � __init__.py � � � +---__pycache__ � 0001_initial.cpython-36.pyc � 0002_profile_description.cpython-36.pyc � 0003_auto_20170905_1654.cpython-36.pyc � 0004_auto_20170905_1659.cpython-36.pyc � __init__.cpython-36.pyc � +---templates � base.html � contact.html � +---__pycache__ admin.cpython-36.pyc forms.cpython-36.pyc models.cpython-36.pyc views.cpython-36.pyc __init__.cpython-36.pyc The error I'm receiving is this 2017-10-08T09:33:38.547463+00:00 app[web.1]: There was an exception (ModuleNotFoundError) … -
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'custom_user.CustomUser'
hye . i get the error after try to solve User Registration with error: no such table: auth_user by following Manager isn't available; User has been swapped for 'pet.Person' i still cannot register user using my custom user registration form and i have been stuck for almost 2 weeks . im sorry if i ask a very fundamental question but i just cannot figured out why i still cant register my user . my registration page wont validate. profiles/views.py : from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from custom_user.forms import CustomUserCreationForm from django.contrib import auth from django.contrib.auth import get_user_model from django.http import HttpResponseRedirect #Create your views here def home(request): return render(request, "home.html") def login(request): c = {} c.update(csrf(request)) return render(request, "login.html", c) def about(request): context = locals() template = 'about.html' return render(request,template,context) @login_required def userProfile(request): user = request.user context = {'user': user} template = 'profile.html' return render(request,template,context) def auth_view(request): username = request.POST.get['username', ''] password = request.POST.get['password', ''] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HTTpResponseRedirect('account/login') else: return HTTpResponseRedirect('account/login') def register_success(request): return render(request, 'accounts/register_success.html') def logout(request): auth.logout(request) return render(request, 'logout.html') CustomUser = get_user_model() register/views.py : from django.shortcuts import render, redirect from django.contrib.auth import get_user_model … -
Simple django ajax
I use django, and I want add some html div on page with ajax. How I can make it? On main page I have script <script type="text/javascript"> $.ajax({ url: '/news/showNews', type: 'POST', dataType: 'html', success: function (response) { $('#news).text(response); } error:function(){ alert("error"); } }); } </script> I have app "news" and there files view.py from django.http import HttpResponse def showNews(request): if request.method == 'POST': return HttpResponse("Hello world") -
Attribute error while trying to migrate models in Django 1.11.4 project
I'm creating a social networking site in Django 1.11.4 with Python 3.4.5. I'd like to allow users of this application authentication through Facebook, Twitter and Google. I've installed python-social-auth module in my project in version 0.12.12. I've added social.apps.django_app.default application to my project, I've added social-auth/ url that points to social.apps.django_app.urls and I've added social.backends.facebook.Facebook2AppOAuth2 authentication backend. When I tried to migrate models I got AttributeError exception. bookmarks/settings.py: """ Django settings for bookmarks project. Generated by 'django-admin startproject' using Django 1.11.4. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ from django.core.urlresolvers import reverse_lazy import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '1atcnl)dz80wh(4td96^iefy0z$!av$6s_hb+zc7k==78-f19%' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] LOGIN_REDIRECT_URL = reverse_lazy('dashboard') LOGIN_URL = reverse_lazy('login') LOGOUT_URL = reverse_lazy('logout') EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'account.authentication.EmailAuthBackend', 'social.backends.facebook.Facebook2AppOAuth2' ) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
Some dropdown buttons don't work - Django
So I'm having this issue that is bothering me for some days. As you can see I have 2 templates base_user courses(extends base_user) All links and scripts are referenced in base_user. But when I create a drop down button in courses template, it appears on the page but nothing happens when I click it. However, drop down buttons work normally on the base_user template. Code in base_user.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}ECE DB{% endblock %}</title> {% load staticfiles %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'user/style.css' %}"/> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type='text/css'> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <!-- Header --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#topNavBar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{% url 'user:index' %}"> <div style="font-family: 'Satisfy', serif;">ECE DB</div> </a> </div> <!-- Items --> <div class="collapse navbar-collapse" id="topNavBar"> <ul class="nav navbar-nav"> <li class="{% block browse_active %}{% endblock %}"><a href="{% url 'user:browse_files' %}"><span class="glyphicon glyphicon-folder-open" data-toggle="dropdown"aria-hidden="true"></span>&nbsp; Browse Files</a></li> <li> <div class="container"> <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Test1 <span class="caret"></span> </button> <ul class="dropdown-menu"> <li class="dropdown-header">Dropdown header 1</li> <li><a href="#">HTML</a></li> <li><a href="#">CSS</a></li> <li><a href="#">JavaScript</a></li> … -
Python calling methods with variables
I dont know if title is very accurate. I have 5 methods that are webscrapping different websites. Each function looks something like this: def getWebsiteData1(last_article): ty = datetime.today() ty_str = ty.strftime('%d.%m.%Y') url = 'http://www.website.com/news' r = requests.get(url) html = r.text soup = BeautifulSoup(html, 'html.parser') articles = soup.findAll("div", {"class": "text"})[:15] data = list() for article in articles: article_data = dict() if article.find("a").get('href') == last_article: return data else: article_data["link"] = article.find("a").get('href') article_data["title"] = article.find("a").get_text() data.append(article_data) return data So each function returns data that is a list of dictionaries. I have another method that calls this method. def CreateArticle(website_number, slug): website = Website.objects.get(slug=slug) last_article = website.last_article data = getWebsiteData1(last_article) //here i want to do something like data = website_number(last_article) but ofcourse this doesnt work if len(data) == 0: return "No news" else: for i in data: article = Article(service=service) article.title = i['title'] article.url = i['link'] article.code = i['link'] article.save() service.last_article = data[0]['link'] service.save(update_fields=['last_article']) return data[0]['link'] I want to be able to call CreateArticle(website_number) and tell this method which getWebsiteData method it should call, so i can have only one CreateArticle method and not for each webscrapper method another CreateArticle method. I hope my question is clear :D -
Is it possible to limit a StreamField to accept exactly two blocks?
The title says it all, I haven't been able to find any other information online. I'm wondering if it is possible for me to get secondary_links = StreamField([ ('Page', SerialisedPageChooserBlock())]) to accept exactly two blocks. -
Django Materialize.css Navbar
I'm working on a Django webapp and I'm using Materialize for CSS I have placed the Materialize file in the static folder in the app. I have issues with the Navbar that it works fine when in full-screen but when I resize the browser the hamburger icon for mobile navbar doesn't work. When clicked on it, it just goes to the /# page and doesn't openup from the side as it should. Do I have to make any change in the Django or Javscript files files? How can I fix this issue?