Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django to create and change mysql database for learning purposes
I am leaning Python programming language. I want to familiarize myself with mysql database as well. I've installed mysql database and Django on my computer. I have Ubuntu 14.04 and python 3.4 installed. I've configured Django settings to use mysql database. I tested Django connection to mysql db and all things work properly. I am a complete newbie with web development. I didn't create my own website and I didn't start developing any web application. My purpose currently is to master creation of mysql database and tables, making changes/migrations/queries, using Django models. Is it reasonable/possible to use Django ORM for work with mysql database without simultaneous development of a web application/local application? As I've said, I don't have my own website. I want just to try using mysql and Django together on my computer in order to get deeper knowledge as to Django and mysql in this respect. -
Django Tweepy Streaming in browser
I want to implement a live streamer in the browser of the Tweeter data. I am using Tweepy library to stream the tweets. class MyStreamListener(tweepy.StreamListener): def on_status(self, status): return status.text This allows me to stream the data to the console, however, I would like to stream and display the data in the browser. What are the steps to achieve that? Should I use Ajax to make a request from time to time in order to populate the data? Is it possible to achieve this by using only the Tweepy library? Thanks, Adrian -
NoReverseMatch at /app/detail/3/
I got an error,NoReverseMatch at /app/detail/3/ Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['app/detail\/(?P[0-9]+)\/$'] . I wrote in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] page = _get_page(blog_content, request.GET.get('page')) return render(request, 'top.html',{'content':content,"page":page}) class DetailView(generic.DetailView): model = POST template_name = 'detail.html' in top.html <div> {% for content in page %} <h2>{{ content.title }}</h2> <p><a href="{% url 'detail' content.pk %}">SHOW DETAIL</a></p> {% endfor %} </div> in detail.html <div> <h2>Comment List</h2> <a href="{% url 'detail' pk %}">Comment</a> {% for comment in post.comment_set.all %} Name:{{ comment.name }} <br> Text:{{ comment.text }} <br> <a href="{% url 'recomment' comment.pk %}">Reply</a> <br> {% endfor %} </div> <div> <h2>Comment Form</h2> <form action="" method="POST"> {{ form.as_p }} {% csrf_token %} <button type="submit">Send</button> </form> </div> When I access top.html, web site is shown correctly , so it is ok. But when I put SHOW DETAIL links, this error happens. I really cannot understand why this error happens. -
Integrating pyejabberd with django api to make ejabberd user registration
i am using django rest framework for making API. I have to integrate django with ejabberd xmpp to register users with ejabberd and get thier jabber id (JID). I came across pyejabberd which provided fucnctionality to register user with ejabberd. I need to know how to integrate it with my django project . The link to pyejabberd is - https://pypi.python.org/pypi/pyejabberd I tried to include it in installed apps to to use it after importing. I am also not sure whether we can use pyejabberd with django or not. Any help will be highly appreciated . Is there any other library to use if we want to register users with ejabberd and obtain JID in django -
Divs with similar structure would all act when only clicked on one
I use div to show a heading and a paragraph. I include a thumb up image on the bottom right corner. My intent is that when thumb up is clicked, it will change color and scale. However, with my code, when click on one thumb up, all thumbs would act the same way. I'm using Django template, here is a mock-up. I think something is wrong with my js file, please let me know how to fix it. Many thanks. var $icon = $(".icon"); $icon.on('click', function() { if ($icon.closest("div").hasClass('anim')) { $icon.closest("div").removeClass('anim'); } else { $icon.closest("div").addClass('anim'); } }); .icon-wrapper { position: absolute; bottom: 0; right: 0; padding: 10px; text-align: center; cursor: pointer; display: inline-block; } .icon-wrapper .icon { color: #90A4AE; } .icon-wrapper i { transform: scale(1); } .icon-wrapper.anim .icon { color: #39CCCC; } .icon-wrapper.anim i { animation: icon-animation cubic-bezier(0.165, 0.84, 0.44, 1) 1.2s; } @keyframes icon-animation { 0% { transform: scale(0); } 100% { transform: scale(1); } } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="things"> <div class="thing"> <div class="icon-wrapper"> <span class="icon"><i class="fa fa-thumbs-up"></i></span> </div> <h2>Wachet auf, ruft uns die Stimme</h2> <p>Wachet auf, ruft uns die Stimme (Awake, calls the voice to us),[1] BWV 140,[a] also known as Sleepers Wake, is a church cantata by … -
super function in Python
Wrt to the code snippet below, why is super().__init__ used in the model? How does it work? model.py class DuckForm(forms.ModelForm): class Meta: model = Duck fields = ('description', 'name') def __init__(self, community, *args, **kwargs): super().__init__(*args, **kwargs) self.community = community def save(self, commit=True): duck = super().save(commit=False) if not duck.community_id: duck.community = self.community if commit: duck.save() return duck views.py def add_duck(request): if request.method == 'POST': form = DuckForm(request.animal.community, data=request.POST) if form.is_valid(): duck = form.save() return redirect('DuckData') else: form = DuckForm(request.user.community) return TemplateResponse(request, 'MyDuck.html', {'form': form}) -
How can I define my metrics for test on django?
I need to define some metrics for my tests in my application. So I need to my application only deploy if the minimum for my code coverage was 50%, like I defined. So if my tests doesn't pass, my deploy will stop (I use Travis CI for my automation deployment) I use Django for my tests. It's possible? -
Nothing is shown in detail.html
Nothing is shown in detail.html. I wrote in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] page = _get_page(blog_content, request.GET.get('page')) return render(request, 'top.html',{'content':content,"page":page}) class DetailView(generic.DetailView): model = POST template_name = 'detail.html' in top.html <div> {% for content in page %} <h2>{{ content.title }}</h2> <p><a href="{% url 'detail' content.pk %}">SHOW DETAIL</a></p> {% endfor %} </div> in detail.html <h2>{{ POST }}</h2> <p>{{ POST.text }}</p> in urls.py urlpatterns = [ path('top/', views.top, name='top'), path('detail/<int:pk>/', views.DetailView.as_view(), name='detail'), ] When I access top.html, web site is shown correctly , so it is ok. But when I put SHOW DETAIL links, nothing is shown. I really cannot understand why detail.html does not show model's content.How should I fix this?What is wrong in my code? -
How to SELECT a field from a LEFT JOIN'ed table/model with Django's ORM (1.11)
Context: Using Django Rest Framework, I've created a ModelViewSet. I'm overriding the list() method to customise the query as explained below. With these models: class Claim(models.Model): permalink = models.SlugField(max_length=255, blank=True, unique=True) author = models.ForeignKey(get_user_model(), db_index=True, on_delete=models.SET_NULL, null=True, blank=True) deleted = models.BooleanField(db_index=True, default=False) collaborators = models.ManyToManyField(get_user_model(), through='ClaimCollaborator', through_fields=('claim', 'user'), related_name='claims') # ...other fields class ClaimCollaborator(models.Model): claim = models.ForeignKey(Claim, db_index=True, on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), db_index=True, on_delete=models.CASCADE) access_project_only = models.BooleanField(default=True) I'm trying to query Claim to LEFT JOIN ClaimCollaborator and bring back the access_project_only field. ClaimCollaborator is actually an intermediary model handling the ManyToMany relationship between claims and users (collaborators of the claim). So far I have the following (cut down for brevity): class ClaimViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated, ) queryset = models.Claim.objects.all() serializer_class = serializers.ClaimSerializer lookup_field = 'permalink' def list(self, request): result = models.Claim.objects.filter(Q(author=request.user) | Q(claimcollaborator__user=request.user)) print(result.query) return JsonResponse(serializers.ClaimSerializer(result, many=True, context={'request': request}).data, safe=False) Listing produces this SQL: SELECT "api_claim"."permalink", "api_claim"."author_id", "api_claim"."deleted" LEFT OUTER JOIN "api_claimcollaborator" ON ("api_claim"."id" = "api_claimcollaborator"."claim_id") WHERE ("api_claim"."author_id" = 39 OR "api_claimcollaborator"."user_id" = 39) So I'm getting the LEFT JOIN on "api_claimcollaborator" (ClaimCollaborator) just fine, but none of the fields. I've tried .only(, 'claimcollaborator__access_project_only') and .selected_related('claimcollaborator') on the query but this just produces errors (I can be more specific about … -
Slug field from foreignkey in admin
when I select a Community from a dropdown menù I want the community name to appear in the slug field. Mymodel.py: class Province(models.Model): community = models.OneToOneField(community.Community, null=True, on_delete=models.PROTECT) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Myclass, self).save(*args, **kwargs) class Community(models.Model): name = models.CharField(max_length=16, unique=True) My admin.py: class ProvinceAdmin(admin.ModelAdmin): search_fields = ['community__name'] prepopulated_fields = {'slug': ('community',)} #prepopulated_fields = {'slug': ('community__name',)} #prepopulated_fields = {'slug': ('community.name',)} The search field is working like expected but the prepopulated_field isn't: the only working is the first solution, but the slug is the id and not the name. The other solutions give this error message: <class 'core.admin.ProvinceAdmin'>: (admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to 'community__name', which is not an attribute of 'core.Province'. Thank you -
Django Viewflow basic questions
Here are few questions i am searching answers for: 1. Difference between BPMN and pure workflow. 2. Can we integrate any system or it has to be Django based? 3. If we want to set up life cycle of a process, Can we get the info which task is stuck at which stage? 4. How much development effort would require to set up a simple workflow? It would be really helpful if anyone could help me with this. -
Django: How to serial a subset of fields in a model instance?
I was wondering if there is a way of serializing (into Json) a subset of all fields in all instance of a model. An example instead of having for a cinema everything that relates to each cinema like seats, screening , movies and so on. Just cinema name and location coordinators. Thank you for your time. Only using vanilla django. -
Using namespace in django for anchor tag
I am nobish in django ,started django before 3 weeks.I am facing a issue regarding url in anchor tag in html page.I am including all files music urls.py from django.conf.urls import url from . import views app_name = 'music' urlpatterns = [ url(r'^$', views.index,name='music index'), url(r'^albums/$', views.albums,name='albums'), url(r'^albums/(?P<album_id>[0-9]+)/details/$',views.album,name='details') ] main urls.py from django.conf.urls import include,url from django.contrib import admin urlpatterns = [ url(r'^$', include('music.urls')), url(r'^music/', include('music.urls')), url(r'^admin/', admin.site.urls), ] music views.py from django.shortcuts import render , get_object_or_404 from .models import Albums,Music def index(request): return render(request,'music/index.html',{}) def albums(request): all_albums = Albums.objects.all() return render(request,'music/index.html',{'allalbums' : all_albums}) def album(request,album_id): single_album = get_object_or_404(Albums,pk=album_id) return render(request,'music/details.html' ,{'album' : single_album}) index.html <!DOCTYPE html> <html> <head> <title></title> </head> <body> <ul> <h1>This is music Page</h1> {% for album in allalbums %} <li><a href="{% url 'music:details' album.id %}">{{ album.album_name}}</a></li> {% endfor %} </ul> </body> </html> settings.py INSTALLED_APPS = [ 'music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] but when I run this code ,I am getting this issue(attaching image) ..and one more thing .. I am using linux, django 1.11.7 version -
Django: Per View authentication scheme
The django rest framework does allow per view authentication schemes: http://www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme I think this is handy and I ask myself why this gets reinvented in the django rest framework. "Why does django not provide this?" is a question which would get closed here on stackoverflow soon. That's why I ask: How to get per view authentication schemes in django? -
changing behavior unique=true in nested relation serializer _ Django Restframework
I have two model in my models.py .they are related with OneToOne relation. with this structure: models.py class A (models.Model): foo = models.CharField() class B (models.Model): title = models.CharField(unique=True) some = models.OnToOneField(A, on_delete=models.CASCADE, related_name="some") serializers.py class BSerializer(serializers.ModelSerializer): class Meta: model = B fields = "__all__" class ASerializer(serializers.ModelSerializer): some = BSerializer() class Meta: model = A fields = "__all__" def update(self, instance, validated_data): some_data = validated_data.pop('some') instance.some.title = some_data.get('title', instance.some.title) instance.foo = validated_data.get('foo', instance.foo) a = instance.some instance.save() a.save() return instance so this structure working when i try to update.the title field must be always a unique. basically , the object is created so when i try to update this the title field must be unique but i need too exclude the instance from that uniqueness.how should i tell the django exclude this object from entire database? -
TemplateDoesNotExist at /app/detail/3/
I got an error,TemplateDoesNotExist at /app/detail/3/ app/post_detail.html.I wrote codes def top(request): content = POST.objects.order_by('-created_at')[:5] page = _get_page(blog_content, request.GET.get('page')) return render(request, 'top.html',{'content':content,"page":page}) class DetailView(generic.DetailView): model = POST def detail(request, pk): content = POST.objects.get(id=pk) return render(request, 'detail.html',{'content': content}) in top.html <div> {% for content in page %} <h2>{{ content.title }}</h2> <p><a href="{% url 'detail' content.pk %}">SHOW DETAIL</a></p> {% endfor %} </div> in detail.html <h2>{{ content.title }}</h2> <p>{{ content.text }}</p> When I access top.html,ordinary web site is shown, so it is ok.But when I put SHOW DETAIL links the error happens.I did not write post_detail.html anywhere in my codes, so I really cannot understand why post_detail.html causes mistake.As a test,I made post_detail.html is in same directory with top.html&detail.html,but same error happens.I wanna make a system when I put SHOW DETAIL links ,content's detail is shown.How should I fix this?What is wrong in my code? -
Check if a link is working and hide/disable if it's broken using HTML/JavaScript
So I am building my website using HTML/CSS. I would like to know what is the easiest way to check if a URL is availble? For example, I have a table with a cell that shows a link to some URL - <td width="100%"><center><a href="10.0.5.1"> Server.com </a></center></td> In this cell, there is a link to some url. I want to show the link as URL (a href) only if 10.0.5.1 is working using http! If it's not, I will show just a text, or not show it all... I have found some functions in Javascript that return true and false, but I dont know how to call the function in my html. Like, I was thinking of doing if (link works) : show link with a href, else: show just the string... Is it possible using Javascript function? If so, what's the function and how do I call it? -
limit and ajax in with select2
I am working with a selct2 widget and I want to add 2 options: 1- just show 10 items in default combo and reach others by search 2- have an Ajax call every time on keyup to search the entered string in search field. if that matters I am using this in django and use it as a widget: class Select2(forms.Select): """A combobox (a select field with filter)""" _html_template = trim_docstring(""" <script> $("#{id}").select2({{ language: "{language}", dir: "{dir}", }}); </script> """) @property def media(self): js = ("utils/select2-4.0.3/dist/js/select2.js", "utils/select2-4.0.3/dist/js/i18n/%s.js" % translation.get_language(), "utils/select2-corrections.js", ) css = {'all': ("utils/select2-4.0.3/dist/css/select2.css",)} return forms.Media(js=js, css=css) -
How to validate forms with a recursive validation function
I'm trying to validate some JSON post data recursively, but having trouble returning error reponses in the "child" calls. Here's a simplified version: POST data: { response_type: "parent", subresponses: [ { response_type: "foo", value: "something" },{ response_type: "bar", value: "something else" } ] } The post data can have an arbitrary number of child subresponses. View: def process_response(response): forms = { 'foo': FooForm, 'bar': BarForm, } if response.get('response_type') == 'parent': for subresponse in response.get('subresponses'): self.process_response(subresponse) else: form = forms[response.get('response_type')](response) if form.is_valid(): form.save() else: return JsonResponse({"message": str(form.errors)}, status=400) Of course, the process_response function will throw away the JsonResponse returned by an invalid subresponse in a child object; I need to test the return value instead. I throught about raising an exception in the child and catching it in the parent, but response_type may not be "parent" - so form validation and exception raising would occur at the "top level" in that scenario. Example: { response_type: "bar", value: "something" } Is there a Djangoey way of doing this? And if I'm doing it right, how do I test for returning JsonResponse(status=400) if so? -
fabric GUI interface doesn't load completely in browser
i installed fabric-bolt in my Ubuntu Desktop 16.04 according the Quickstart guid on this link : https://github.com/fabric-bolt/fabric-bolt but the GUI Interface can not load correctly in my browser. where is the problem. i need to do another steps to run fabric-bolt GUI completely? this is a picture of fabric-bolt GUI that i have : fabric-bolt GUI Interface -
How to change Django's start server time format?
When I start django server using following command: python manage.py runserver It shows current time likes: January 02, 2018 - 15:35:17 But I want to see time format: January 02, 2018 - 3:35:17pm How can I do it? Thank you -
Django project does not recognize installed packages
I made two projects using Pycharm (1st one is Python project and 2nd is Django project) and below are the screenshots for the installed packages I don't understand why Django project does not recognize my packages but Python project does recognize. Python version is also same i.e. Python3.5. I also checked the permission issues but you can see below there are similar permissions. user@user3 PycharmProjects]$ ls -l total 0 drwxr-xr-x. 8 user users 208 Dec 14 12:52 RMUE-APP drwxr-xr-x. 6 user users 80 Jan 2 10:51 RmueWeb Please guide me know what should I do to make it work ? -
Django SUM from INNER JOIN
I have a DB like this: class MyCPU(models.Model): cpu_name = models.CharField(max_length=100) cpu_count = models.IntegerField() class MyMachine(models.Model): hostname = models.CharField(max_length=50) ip = models.CharField(max_length=50) cpu = models.ForeignKey(CPU, on_delete=models.CASCADE) How can I achieve the result of following raw SQL command in Django ? select sum(cpu_count) as sum_cpu from my_machine inner join my_cpu on my_machine.cpu_id=my_cpu.id I basically want to sum how many CPU in all of machines. I have tried this solution but it did not work Machine.objects.annotate(total_cpu=Sum('cpu__cpu_count')) -
Django+gunicorn+nginx site runs perfect when using example.com:8000 but not when using example.com
I have a site on Digital Ocean VPS. But I get a bad gateway when accessing example.com but not when example.com:8000. Also when visiting the django-admin at example.com:8000/admin the default formatting is not coming. I guess nginx is not being able to serve the static content. Below is the service file for gunicorn: [Unit] Description=gunicorn daemon After=network.target [Service] Group=www-data WorkingDirectory=/FINlit ExecStart=/FINlit/venvforfinlit/bin/gunicorn --access-logfile - --workers 3 --bind unix:/FINlit/Finlit.sock Finlit.wsgi:application [Install] WantedBy=multi-user.target and the nginx config: upstream app_server_wsgiapp { server 127.0.0.1:8000 fail_timeout=0; } server { listen 80; server_name my_ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /FINlit; } location / { include proxy_params; proxy_pass http://unix:/FINlit/Finlit.sock; } } Thanks -
How to send image as input to django view using angular frontend?
I have an existing django web api with angular frontend, using which i can upload images and display them to the user.Now i want to extend this.On clicking the button "segment"(see image) it should pass the corresponding image to my python script on the backend, which does some processing on the image. I have my python script in the views.py file of the main app,which is some thing like this: from django.shortcuts import render def segment_image(request): if request.method == 'GET': form = segment_form() else: if form.is_valid(): info = request.POST['info_name'] output = script_function(info) ''' Here i am calling script_function,passing the POST data info to it''' return render(request, 'your_app/your_template.html', { 'output': output, }) return render(request, 'your_app/your_template.html', { 'form': form, }) '''here info is our image in some format''' def script_function(info): ... '''here goes my mian logic to process the image.''' ... return x,y,w,h I have never worked with images as inputs in angular,i dont know how to route the image using angularjs to my view.Now how can i implement this segmentImage() function in app.js file so that the function would call the corresponding view by passing this image as a POST argument. Below is my index.html file. <!DOCTYPE html> <html lang="en-US"> <head> …