Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get push notifications from YouTube API in python?
I am working on a project, where I want to get a push notification when certain youtube channel post a video. I am using YouTube API for posting comments . YouTube API has a post for setting up push notifications. https://developers.google.com/youtube/v3/guides/push_notifications According to this I need to set up a callback server that can handle incoming Atom feed notifications. I don't know how to set up the same. I have come across this https://github.com/fanout/webhookinbox and tried there web instance. I gave that url in the youtube setting here https://pubsubhubbub.appspot.com/subscribe. But I didn't get any notification, when I uploaded a new video on the channel (I used my own channel to check). Please help. -
django channel async function run in sequence
i was trying to the write the message to database after group send function in channels. But rather than completing the group send function it executes the group send function pauses the function in between executes the database write function and then executes the group send which adds delay in group send function. is there is any way to run the group send function to complete first await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': final_message_data } ) await self.create_chat_message(user, message_data['msg']) -
How to limit catch all urls in django
I have a django project with specific urls, setup by a 'catchall' URL. This is so I can go to mysite/living, and have it pass living as a parameter and pull up the appropriate details from my db. My urls.py: url(r'^$', views.index, name='index'), url('about/', views.about_view, name='about_view'), url('contact/', views.contact_view, name='contact_view'), url('(?P<colcat>[\w\-]+)/collection/(?P<name>[\w\-]+)$', views.collection_detail, name='collection_detail'), url('(?P<colcat>[\w\-]+)/$', views.collection_view, name='collection_view'), I am running into the problem where, anything can be passed as a parameter. This is particularly notable with search engines, where mysite/index.html/index.html returns a valid page. Is there a way to limit the urls that are 'allowed' to be matched? -
Sum greatest values of each day from period with Django Query
My proj has a model that goes like: class Data(Model): data = FloatField(verbose_name='Data', null=True, blank=True) created_at = DateTimeField(verbose_name='Created at') And my app creates a few hundred logs of this model per day. I'm trying to sum only the greatest values of each day, without having to iterate over them (using only Django queries). Is it possible without writing SQL queries? -
error ' [Errno 2] No such file or directory' when trying to create a new django project
I'm following a udemy course on learning python and i have got to a part about learning django. I have created a folder on my desktop and tried to start a django project in it using cmd, however when i try to start the project i get the error 'd:\python\python: can't open file '3.6\python.exe': [Errno 2] No such file or directory', i have tried finding solutions but since I've never really used cmd i have no idea what to do, please help! i have tried searching up solutions but I've been unable to find others with the same problem, here is what i typed in cmd: C:\Users\Thomas>cd desktop C:\Users\Thomas\Desktop>cd newsite C:\Users\Thomas\Desktop\newsite>django-admin startproject mysite d:\python\python: can't open file '3.6\python.exe': [Errno 2] No such file or directory C:\Users\Thomas\Desktop\newsite> -
HyperLinkedModelSerializer: Could not resolve URL for hyperlinked relationship using view name
I'm new to django and drf and I'm trying to setup a simple api to return the List and Detail views of the "Personality model. I want the urls to use the slug field instead of the default pk. It works fine when using the default "pk" field for resolving urls but when i tried using the slug field via lookup_field, I'm getting the following error: [ERROR] 'ImproperlyConfigured at /personality/ Could not resolve URL for hyperlinked relationship using view name >"personality-detail". You may have failed to include the related model in >your API, or incorrectly configured the lookup_field attribute on this >field.' models.py: class Personality(models.Model): personality_name = models.CharField( "Influential Person", unique=True, max_length=100 ) slug = models.SlugField(blank=True, unique=True, max_length=100) info = models.TextField("Information") trivia = models.TextField("Trivia") def __str__(self): return self.personality_name def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.personality_name) super(Personality, self).save(*args, **kwargs) views.py class PersonalityViewSet(viewsets.ModelViewSet): queryset = Personality.objects.all().order_by("id") serializer_class = PersonalitySerializer lookup_field = "slug" serializers.py: class PersonalitySerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name="personality-detail", lookup_field="slug" ) class Meta: model = Personality fields = ("pk", "personality_name", "url", "slug", "info", "trivia") read_only_fields = ("pk", "slug") # lookup_field = "slug" # extra_kwargs = {"url": {"lookup_field": "slug"}} quotes/urls.py router = routers.DefaultRouter() router.register(r"personality", views.PersonalityViewSet) urlpatterns = [path("", include(router.urls))] urls.py … -
How to add a custom model in Django. So that when i specify a integer. It generates the same number of text fields in the admin page
How to add a custom model in Django. So that when i specify a integer. It generates the same number of text fields in the admin page. I want to add a Integer which takes the value from admin page and returns the same number of text fields in the same model in the admin section. -
Cant order my form field in python django correctly
I try to order my form (in django) but it doesnt work. I tryed some ways but nothing helps. I tryed for example with SortedDict from django.utils.datastructures. But this is not up to date... class RegisterForm (UserCreationForm): email = forms.EmailField(required=True) name = forms.CharField(required = True) class Meta: model = User fields = {'name','email', 'username','password1','password2'} field_order = {'name','email', 'username','password1','password2'} def __init__(self, *args, **kwargs): super(RegisterForm,self).__init__(*args, **kwargs) #self.rearrange_field_order() def save(self, commit=True): user = super(RegisterForm,self).save(commit = False) user.email = self.cleaned_data['email'] user.name = self.cleaned_data['name'] if commit: user.save() return user This is the order of the output: Username: Password: Name: Password confirmation: Email: Can anyone help? At least with a method that is uptodate? -
Django: Can't GROUP BY on a template table
I'm trying to show a table in the template, which shows transactions with their dates. The query is: resultado = Asiento.objects.filter(Empresa=request.session['codEmp'], codcta=cod_cta).exclude(anulado='S').order_by(date) But the user can check a checkbox which if set to true should show one row per date in the table. Without group by: +-------------------------------+-------+ | date | trans_in | trans_out | total | +--------+----------+-----------+-------+ |2019/5/3| $5.000 | $0 | $5.000| +--------+----------+-----------+-------+ |2019/5/3| $0 | $2.500 |-$2.500| +--------+----------+-----------+-------+ |2019/5/4| $1.000 | $0 |$1.000 | +--------+----------+-----------+-------+ And what I'm trying to do is: +-------------------------------+-------+ | date | trans_in | trans_out | total | +--------+----------+-----------+-------+ |2019/5/3| $5.000 | $2.500 |$2.500 | +--------+----------+-----------+-------+ |2019/5/4| $1.000 | $0 |$1.000 | +--------+----------+-----------+-------+ I've already tried by doing resultado = Asiento.objects.filter(Empresa=request.session['codEmp'], codcta=cod_cta).exclude(anulado='S').order_by(date).values('date').annotate(dcount=Count('date')) Using annotate but it doesn't work! I really can't figure yet how to group by easier. Later in the code I iterate with a for loop over resultado to add and substract the amount of money for each object in the queryset. for asiento in resultado: add = add+asiento.add sub = sub+asiento.sub asiento.total = asiento.add-asiento.sub total = add-sub -
Pre-populate slug field into a form field of a Django site
I've create a form for publish a post on a site. Into the model there is a SlugField that is a pre-populated field in admin.py for the title of the post. forms.py class TestPostModelForm(forms.ModelForm): title = forms.CharField( max_length=70, label="Titolo", help_text="Write post title here. The title must be have max 70 characters", widget=forms.TextInput(attrs={"class": "form-control form-control-lg"}), ) slug_post = forms.SlugField( max_length=70, label="Slug", help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents", widget=forms.TextInput(attrs={"class": "form-control form-control-sm"}), ) ..... class Meta: model = TestPostModel fields = [ "title", "slug_post", "description", "contents", .... ] If I create a post from the administration panel the slug is correctly populated automatically, but the same thing don't happen if I create a post from the form. In this second case the post is created but the slug field remain empty. I've read that I must use slugify for create a pre-populated field into my form but I have not clear in which method I can do this. Can I have some example? -
Input time with custom form trouble
I have a problem with TimeFileld on my custom form I cant remove seconds from fields and my validation doesn't see the value in the field I've tried to use a lot of input_formats in TimeInput and formats in TimeField class OrderForm(forms.Form): client_name = forms.CharField(required=True) client_lastname = forms.CharField(required=True) client_patronymic = forms.CharField(required=True) client_phone = forms.CharField(required=True) master = forms.ModelChoiceField(Master.objects.all()) client_car = forms.CharField(required=True) plan_date = forms.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) plan_time = forms.TimeField(input_formats=['%H:%M','%I:%M %p'], widget=forms.widgets.TimeInput(attrs={'class':'time_field', 'type': 'time'},format=["%H:%M","%I:%M %p"])) class Meta: model = Order fields = ('client_name', 'client_lastname', 'client_patronymic', 'client_phone', 'plan_date', 'plan_time', 'master', 'client_car') {% extends 'base.html' %} {% block title %}Order{% endblock %} {% block content %} <h2>Create order</h2> <form method="post" action="make_order"> {% csrf_token %} {{ form.as_p }} <button type="submit">Create</button> </form> {% endblock %} I want to input time in 'HH:MM' format, but now I input time and there are '--' for seconds and time not input -
How can I authenticate in Django using LDAP using django-auth-ldap in my models and views?
I need to know how to setup my models and views to be consistent with validating against LDAP active directory server. I already have the settings configured for Django-Auth-LDAP package. But I need to know how to set up my model and view to authenticate / login to LDAP credentials with the Django User. I wrote a python script to connect to the server. In Django, I am ignorant how to set up the model to reflect the user from LDAP and how to write my login and form to connect with LDAP. Any feedback and snippets of models and views would be great! I am using Python 3.7 and Django 2 + -
WSGI script cannot be loaded as Python module: Django server with Apache
I'm setting up a new server using Apache and Django, but i have problems with WSGI when trying to access server. This is the apache log: [Sat Mar 23 09:13:35.367639 2019] [wsgi:error] [pid 19535:tid 140663217088256] [client 139.47.79.250:8469] mod_wsgi (pid=19535): Target WSGI script '/root/frontend/frontend/wsgi.py' cannot be loaded as Python module. [Sat Mar 23 09:13:35.367773 2019] [wsgi:error] [pid 19535:tid 140663217088256] [client 139.47.79.250:8469] mod_wsgi (pid=19535): Exception occurred processing WSGI script '/root/frontend/frontend/wsgi.py'. [Sat Mar 23 09:13:35.367999 2019] [wsgi:error] [pid 19535:tid 140663217088256] [client 139.47.79.250:8469] Traceback (most recent call last): [Sat Mar 23 09:13:35.368076 2019] [wsgi:error] [pid 19535:tid 140663217088256] [client 139.47.79.250:8469] File "/root/frontend/frontend/wsgi.py", line 16, in <module> [Sat Mar 23 09:13:35.368098 2019] [wsgi:error] [pid 19535:tid 140663217088256] [client 139.47.79.250:8469] application = get_wsgi_application() [Sat Mar 23 09:13:35.368127 2019] [wsgi:error] [pid 19535:tid 140663217088256] [client 139.47.79.250:8469] File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Sat Mar 23 09:13:35.368145 2019] [wsgi:error] [pid 19535:tid 140663217088256] [client 139.47.79.250:8469] django.setup(set_prefix=False) [Sat Mar 23 09:13:35.368164 2019] [wsgi:error] [pid 19535:tid 140663217088256] [client 139.47.79.250:8469] File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 19, in setup [Sat Mar 23 09:13:35.368181 2019] [wsgi:error] [pid 19535:tid 140663217088256] [client 139.47.79.250:8469] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Sat Mar 23 09:13:35.368200 2019] [wsgi:error] [pid 19535:tid 140663217088256] [client 139.47.79.250:8469] File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 57, in __getattr__ [Sat Mar 23 09:13:35.368216 2019] [wsgi:error] [pid 19535:tid 140663217088256] … -
How to launch server side script (bash script) when toggle checkbox is set to On/Off
I'm actually trying to set a on/off toggle but I don't know how to execute a script on django which is located in /opt/script/interfacestatus.sh. What I want to do is that when the checkbox is set to check it execute /opt/script/interfacestatus.sh eth0 up. /opt/script/interfacestatus.sh eth0 down. Can someone help me on that. Cordially. views.py: user=request.user interfaces = Anubis_Interface.objects.all() output = subprocess.check_output('/opt/scripts/anubis/installinterfaces.sh', shell=True) if user is not None and user.is_active: return render(request, 'registration/interfaces.html', {'interfaces': interfaces}) else: return HttpResponseRedirect ('/auth') interfaces.html: {% for interface in interfaces %} <tr> <td><input type="checkbox" id="{{interface.Anubis_Interface_id}}" onchange="myFunction('{{interface.Anubis_Interface_name}}','{{interface.Anubis_Interface.Anubis_Interface_name}}" style="display:none">{{interface.Anubis_Interface_name}}</p></td <td> {% endfor %} <script> function myFunction(myitems,myitems2) { var text = document.getElementById(myitems); var checkBox = document.getElementById(myitems2); if (checkBox.checked == true){ text.style.display = "block"; } else { text.style.display = "none"; } } } </script> -
How can i create a chatbot, which uses users data and answers from ours database or some api?
I want to create a chatbot for medical help. The user will tell the symptoms, and the chatbot will search the database or api related to it. And produce the response. The chatbot should accepting users data like age, name, weight, etc. That chatbot should be voice enabled and made by python. How can i do it? -
Is there a way to have rest framework return a type of error not only a type of response for form validation?
I am new to frontend development. Now I am creating a form using VueJS and I created backend using Django. What I want to do is to show validation error message below form just like Django form does. However, Rest framework is supposed to return just the type of the response like 400 when the user send invalid data and I'm wondering if there's a way to show various error messages depending on the type of the invalid data the user sent. For example, when user input incorrect password, I want to show Password is incorrect. But I think I need to get the type of error from backend in order to achieve this kind of thing. Anyone could give me tips? -
How to search in "all" category elements (Selector)
my site has a search function and uses elasticsearch but currently im only able to search onto a specific category and i don't know how to make this working for all categorie-elements that exist. My target is to have a default selector set to "All" so that all categories are getting searched. urls.py url(r'^search/$', app_views.search_elastic, name='search'), views.py def search_elastic(request): qs = request.GET.get('qs') page = request.GET.get('page') if qs: post_a = Post_A_Document.search().query("multi_match", query=qs, fields=["title", "content", "tag"]).to_queryset() post_b = Post_B_MultipleDocument.search().query("multi_match", query=qs, fields=["title", "content", "tag"]).to_queryset() post_c = Post_C_Document.search().query("multi_match", query=qs,fields=["title", "content","tag"]).to_queryset() qs = list( sorted( chain(post_a, post_b, post_c), key=lambda objects: objects.pk )) else: qs = '' paginator = Paginator(qs, 10) # Show 10 results per page try: qs = paginator.page(page) except PageNotAnInteger: qs = paginator.page(1) except EmptyPage: qs = paginator.page(paginator.num_pages) return render(request, 'app/search/search_results_elastic.html', {'object_list': qs}) base.html: <div class="search"> <form id="searchform" action="{% url 'search' %}" method="get" accept-charset="utf-8"> <div class="form-row align-items-center"> <input class="class-search-input-fields" id="searchbox" name="qs" required="required" type="text" placeholder="Search ..."><a>in</a> <div class="custom-dropdown"> <a>{{ categorysearch_form.category }}</a> </div> <button class="btn btn-outline-dark" type="submit"> <i class="fa fa-search"></i> </button> </div> </form> </div> -
Routing and redirecting problem in django
I'm reaching the stage of preparing users code, but im stell unable to prfeorm successively any one of the following :register new users,showing a redicting message and redicting to home page after trying to add a new user Here is my code blog/templates/blog/base.html {% if message in message %} {% for message in message %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} {% block content %}{% endblock %} sittings.py INSTALLED_APPS = [ 'blog', 'django.contrib.admin', 'users', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, mysite/urls.py path('register/', user_views.register,name='register'), path('', include('blog.urls')), [ The blog blog/views.py def home(request): context = { 'posts':Post.objects.all() } return render(request,'blog/home.html',context) blog/urls.py from . import views urlpatterns = [ path('', views.home, name='blog-home'), users/templates/register.html {% block content %} ....... {% csrf_token %} ........ {{form.as_p}} ...... {% endblock content %} I have no error message in the Powershell but i have the following message in Pycharm Debug django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
How to access stored user data in django?
I'm new to django, especially the storing of user data. Basically, I want to save user data searches. They put in a query into a search_bar and I want to save that query. I'm trying to create a list for each user with their search queries at user['search'] and the results of these queries at user['results']. However, I added some code and it does not seem to save the results. Here is my code for user['results']. It's the same as for user['search']. I'm trying to save the query results by using request.session['result'] = query_result. The reason the results are not obvious is that they make a few choices between entering the query and seeing results. from django.contrib.sessions.models import Session request.session.modified = True object_save = list(_objs.values('service__code')) if not 'result' in request.session or not request.session['result']: renderequest.session['result'] = [object_save] request.session.save() else: result_list = request.session['result'] result_list.append(object_save) request.session['result'] = result_list request.session.save() I'd expect this to be able to save and I can look at the searches in python manage.py shell. When I try to pull all the session data with s = Session.object.get(pk='pk') and s['result'] I get nothing. s has no attribute 'result' is the error. Maybe I'm completely not understanding user sessions, please help. -
How to create a technical documentation page in django?
I would like to click on a heading in the page heading navbar that when clicked scrolls to the top of this heading in the page. What are the best practices? Any examples maybe? -
How to manage the navigation part in Django?
What is the correct way to create the "navigation" part of a web application in Django? Everything in django has to be part of an app? If I had to create an app about clothes, for example, the part of "showing clothes, divided in categories" has to be managed in a separate app like for example "browse" or can be in the general directory of app? This part does nothing but showing something in my web app. Nothing concrete What is the right way of proceeding? I've created a browse app that includes everything for a general navigation in the website -
problem in Setting up sphere engine problems API and creating submission ID
I have endpoint,access token and even client object is retreived but im getting error as problem not found while im creating the submission. I want any example in python to create this submission -
django AbstractUser : How to properly write user profile page
I Use AbtractUser to extend user model as decribed at https://wsvincent.com/django-custom-user-model-tutorial/ And since I want a nonstaff user to be able to do some limited admin activity, I followed https://tryolabs.com/blog/2012/06/18/django-administration-interface-for-non-staff-users/ it works as expected Currently my result posted at http://oi65.tinypic.com/25kuale.jpg As picture say, a non staff user that have permission 'change on user model' have 'Users' under 'Radius' Application menu. My Question is : How to add 'MyProfile' at the 'top menu' (the same place as 'Change Password' that if clicked will call the user-change-form (pictured at the most right side)?. at models.py class RadiusUser(AbstractUser) : radius_password = models.CharField(max_length=40, verbose_name="Hotspot Password", help_text='Password for Accessing Our Network/Hotspot',blank=True, null=True) enable = models.BooleanField(default=False) gb_all = models.FloatField(default=0.0) gb_day = models.FloatField(default=0.0) gb_night = models.FloatField(default=0.0) expired_date = models.DateTimeField(auto_now_add=True) is_partner = models.BooleanField(default=False) can_add_credit = models.BooleanField(default=False) balance = models.IntegerField(blank=False, default=0) def __str__(self): return self.username at admin.py class RadiusUserAdmin(UserAdmin): add_form = RadiusUserCreationForm form = RadiusUserChangeForm model = RadiusUser list_display = ['username'] radius_basic_fieldset = ('Radius Configs', {'classes': ('wide',), 'fields': ('radius_password','gb_all','gb_day','gb_night','balance')}) radius_permission_fieldset = ('Radius Permission', {'classes': ('wide',), 'fields': ('enable','is_partner','can_add_credit')}) def get_queryset(self, request): print('REQUEST=', str(request)) qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(pk=request.user.pk) def get_fieldsets(self, request,obj): print('OBJECT',obj) if not obj: return self.add_fieldsets if request.user.is_superuser: fieldsets = UserAdmin.fieldsets + (self.radius_basic_fieldset, self.radius_permission_fieldset) else … -
Saperate PostgreSQL db for each client, with automated migrations on creating client on single Django app and on same server
client_obj = Client.objects.create(name='client1') status = create_database('client1') def create_database('client1'): con = None dbname = cateror con = connect(dbname='postgres', user='***', host = 'localhost', password='***') con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = con.cursor() cur.execute("SELECT 1 FROM pg_catalog.pg_database WHERE datname = '{}' ".format(dbname)) exists = cur.fetchone() if not exists: cur.execute('CREATE DATABASE ' + dbname) print "DATABASE NOT EXISTS" else: print "DATABASE EXISTS" cur.close() con.close() How to make migrations automated once the db has been created? Or is there another way to accomplish this? -
loading images by list view in django template
I am trying to render by django template with photos saved in database by using listview so they can act like thumbnails like that of amazon.com but images are not loading {% for offer in offer_details %} {% if offer == None %} <a href="#"><img src="{% static "pics/s7.jpg" %}" class="im"></a> {% else %} <a href="#"><img src="{{offer.photo.url}}"></a> {% endif %} {% endfor %} views.py class Index(ListView): context_object_name = 'offer_details' model = models.Offer_discription template_name = "index.html"