Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i retrieve browsers history in python django?
I want to display all the Internet History Information of a system using Python? -
Django REST: Show details and list on 1 url
There is a Django project that uses a REST API. Most of the url-patterns follow the same paradigm: /foo_config/1 Basically /list-view/details-view But there is another type of config - which can only have 1 object, so showing it like /bar_config/1 is confusing, because user might expect #2 and #3, etc. I would like to 'map' bar_config details and list together using simple /bar_config. Tried using @detail_route, but it doesn't work: @detail_route(methods=['put']) def put_config(self, request): ... How to achieve my goal? -
django form not rendering in template. Input fields doesn't shows up
I'm not able to see the django form in my template. it is not being rendered properly. I've tried working on this, but the form not shows up. Tried the same code in a new project to test-that worked fine but here it doesn't work. This {{ form.as_p }} not shows up anything i.e. no input fields for me to enter the details and check the other part. Thanks in advance. My forms.py looks like this : forms.py `class ContactForm(forms.Form): contact_name = forms.CharField(required=True) contact_email = forms.EmailField(required=True) contact_subject = forms.CharField(required=True) content = forms.CharField( required=True, widget=forms.Textarea )` My views.py for the contact section looks like this. views.py def contact(request): form_class = ContactForm if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get( 'contact_name' , '') contact_email = request.POST.get( 'contact_email' , '') contact_subject = request.POST.get( 'contact_subject' , '') form_content = request.POST.get('content', '') # Email the profile with the # contact information template = get_template('contact_template.txt') context = Context({ 'contact_name': contact_name, 'contact_email': contact_email, 'contact_subject' : contact_subject, 'form_content': form_content, }) content = template.render(context) email = EmailMessage( "New contact form submission", content, "Your website" +'', ['youremail@gmail.com'], headers = {'Reply-To': contact_email } ) email.send() return redirect('contact') return render(request, 'contact.html', { 'form': form_class, }) The template for … -
python2.7 install MySQL-python in virtualenv error "failed with exit status 2"
enter image description here In virtualenv , I can't setup backages some like MySQL-python-1.2.3.win-amd64-py2.7.exe . platform: win10 x64 python2.7.12 mysql -
how to track the users browser history using django?
I found some packages like simple history etc,but it is used to track the history of model class but i want the users browser history,so please give the sample code thank you in advance -
How to get multiple rows and columns using mysql db through django
Getting single row and single column below code is executed sucessfully. How to get multiple columns and rows? views.py def get_db_data(request): conn = MySQLdb.connect (host = "localhost", user = "test_user", passwd = "test_pwd", db = "myproject") cursor = conn.cursor () cursor.execute ("SELECT email_address, mobile_number,id, city, state FROM user") if cursor.rowcount == 0: html = "<html><body>There is no Faculty member with id %s.</body></html>" % email_address else: row = cursor.fetchone() html = "<html><body>E-Mail address %s.</body></html>" % row[0] return HttpResponse(html) Please help me with this. -
Django model foreign key issue
I'm using model like this: class Product(models.Model): name = models.CharField(max_length=100) group = models.ForeignKey(Category.objects.filter(group__category__name='foo')) issue is getting error django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
How to rename all django's default auth, permission,groups tables?
I am working on a django app. I understood django creates some tables for users, permissions, groups in database. In that database, already another django app is running. so, already it has default tables. Now, I need to create other app in same database. But I think it creates conflict on users,groups,permissions. So, I want to create all tables with some other names My question is How to create/migrate django app with different table names for users,groups, permissions or is there any other way? Sorry for my silly question. Thanks -
How to update mysql data using django?
How to update mysql data through django? I am not getting any error also. views.py def update_db_data(request): conn = MySQLdb.connect(host= "localhost", user="test_user", passwd="test_pwd",db="myproject") cursor = conn.cursor() try: cursor.execute("UPDATE user SET user_name = 'test'") print("sucess") html = "<html><body>sucess</body></html>" conn.commit() except: print("fail") html = "<html><body>fail</body></html>" conn.rollback() conn.close() return HttpResponse(html) Please tell me where is the problem in my code. How to do condition updates? eg:- UPDATE user SET user_name = 'test' where id =2; -
What is the use of PyInstaller? Can I use it for Django project?
I have created one website in django.I don't want to host it, instead of hosting I want to create installer of that website. Is it possible with PyInstaller ? Is there any application available through which we can convert django project to installer? -
TypeError('view must be a callable or a list/tuple in the case of include().')
i used the Django's version is 1.10.4 and was seeting in my file mysite/urls.py from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/',include(admin.site.urls)), url(r'^website/$',"website.views.first_page"), ] and views.py in mysite/mysite/ # -*- coding: utf-8 -*- from django.http import HttpResponse def first_page(request): return HttpResponse("<p>hello Django</p>") do this seetings but always has current error help me. -
How to reference User foreign key in template?
I can't seem to grasp this very well. So I have an Album model, which is using a class based view and I'm giving it the context with all objects: class Album(models.Model): # Columns artist = models.CharField(max_length=50) album_title = models.CharField(max_length=200) genre = models.CharField(max_length=100) album_logo = models.FileField() user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) The default was put to see if it was working within the Admin page, which it did. On every Album object there was a user field, but when I tried to display it on a template, it wasn't showing. {% for album in all_albums %} <h2>{{ album.album_title }}</h2> <h4>{{ album.artist }}</h4> <h6 class="text-muted">Created by: {{ album.user }}</h6> {% endfor %} The album_title and artist displayed just fine, but not the User (str is username). When I tried getting it up on the shell, I got this: django.contrib.auth.models.DoesNotExist: User matching query does not exist. -
Json formatting trouble, when updating or editing my json file
I can't figure out why my json file is getting ekstra brackets. this is my products.json file. Which has three too many brackets on the right end. {"products": {"27": {"price": 5, "pk": 27, "name": "gfasd", "amount": 3, "type": "sokker", "imageURL": "/media/gg_6A1aZ75.jpg"}}}}} I use a post_save function to update the json file whenever my model instance is geting saved. @receiver(post_save, sender=item, dispatch_uid="update_json") def update_stock(sender, instance, **kwargs): pk = str(instance.pk) with open(MEDIA_ROOT + '/json/products.json', 'r+') as json_file: products = json.loads(json_file.read()) print(products) <--- 1 products["products"].pop(pk, None) print(products) <--- 2 products["products"][pk] = instance.returnAsJSON() print(products) <--- 3 json_file.seek(0) json_file.write(json.dumps(products)) The print outs is: {'products': {'27': {'price': 123, 'type': 'sokker', 'name': 'gfasd', 'amount': 3, 'pk': 27, 'imageURL': '/media/gg_6A1aZ75.jpg'}}} {'products': {}} {'products': {'27': {'price': 5, 'pk': 27, 'name': 'gfasd', 'amount': 3, 'type': 'sokker', 'imageURL': '/media/gg_6A1aZ75.jpg'}}} The last print does not have the three ekstra brackets, so I'm guessing it may be the last two lines of my function. But I do not really know why they do it. -
How to select only date part in postgres by using django ORM
My backend setting as following Postgres 9.5 Python 2.7 Django 1.9 I have a table with datetime type, which named createdAt. I want to use Django ORM to select this field with only date part and group by createdAt filed. For example, this createdAt filed may store 2016-12-10 00:00:00+0、2016-12-11 10:10:05+0、2016-12-11 17:10:05+0 ... etc。 By using Djanggo ORM, the output should be 2016-12-10、2016-12-11。The corresponding sql should similar to: SELECT date(createdAt) FROM TABLE GROUP BY createdAt. Thanks. -
Finding most popular tag Taggit Tastypie Django
Context I have been having conflict. Currenly, I am creating a question answer application. Each question has a tag, and I want to show the most popular tags (e.g. tags that have the most questions associated with it). Specifics I am using django-taggit's TaggableManager to do so. Here is the model definition of the Question: class Question(models.Model): tags = TaggableManager() date = models.DateTimeField(default=timezone.now) text = models.TextField(null=True) So now I have the several tags attached to questions. Question How do I make a tastypie resource to display the tags and sort them by which tag has the most questions associated with it? My attempts I have really only had one decently successful attempt at making this work. Here is the tastypie resource: class TagResource_min(ModelResource): def dehydrate(self, bundle): bundle.data['total_questions'] len(Question.objects.filter(tags__slug=bundle.obj.slug)) return bundle class Meta: queryset=Tag.objects.all() Returns a nice JSON with a variable called total_questions with the number of questions associated with it. Although, dehydrate is after the sort_by part of the request cycle specified here, so I cannot sort the resource by total_questions. Another attempt I had went a different way trying to make the queryset be formed from the Question model: queryset=Question.objects.filter(~Q(tags__slug=None)).values('tags', 'tags__slug').annotate(total_questions=Count(Tag)) The problem with this was that the filter … -
Best practice to handle different group of users accessing their own content
I am building a web app where different companies will upload their own audio files with some additional information. I am building it using Django, Postgres and hosting it on AWS. Users belong to different companies will only be able to access their data when they log into the website. The website allows those users to upload content, search content and access content. My question is, what's the best practice to handle those uploaded content? Is it better to create different schema for each company or putting all the content together and allow users to access different content based on the company id that each entry associates with? -
Sending an SMS to each group based on form selection(s)
So I have an SMS app working perfectly with a Django form. I have an sqlite table "Employees" and each employee has one relationship of either "dcare," "admin," or "recreation". In my form, I used a radio button to select one of these relationships and the messages are sent to those employees...no problem there. The issue is when I switched it from a radio button to a multiple choice widget. So I am having trouble finding the appropriate language/syntax of "For each group selected, send the SMS to each person in that group." Views.py below def contact(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/') else: if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data client = twilio.rest.TwilioRestClient('xxxx', 'xxxx') recipients = employees.objects.filter(group__contains=cd['togroup']) #check to see which group is selected if cd['togroup'] != "everyone": for recipient in recipients: client.messages.create(body=cd['message'],to=recipient.phone_number, from_='+xx') return HttpResponseRedirect('/contact/thanks/') else: #if "everyone" is selected, change recips to all recipients = employees.objects.all() for recipient in recipients: client.messages.create(body=cd['message'], to=recipient.phone_number, from_='+xxxx') return HttpResponseRedirect('/contact/thanks/') else: form = ContactForm() return render(request, 'contact_form.html', {'form': form}) -
Why 'model' object is not iterable?
I'm trying to add a radioselect in my admin panel only. I use a many to many field in order to connect objects of another model (Background). What I have now : The radio select is here and works on the admin panel, but I get this error when I proceed and save the changes : 'Background' object is not iterable. How can I save and keep the information as selected ? MyApp/models.py class Background(models.Model): bk_color = models.CharField(max_length=20) ... class FormOne(models.Model): name = models.CharField(max_length=40) background = models.ManyToManyField(Background, blank=True) ... MyApp/forms.py class FormOneForm(forms.ModelForm): class Meta: model = FormOne fields = ['name', 'background'] background = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=Background.objects.all(), required=False) MyApp/admin.py class FormOneAdmin(ModelAdmin): fields = ['name', 'background'] form = FormOneForm site.register(Background) site.register(FormOne, FormOneAdmin) I couldn't debug the problem, I'd be glad to know from where it is coming and how I can resolve it ? -
Django Postgres objects.create ValidationError
I'm getting a strange error where Django can no longer create objects. I've got a batch script to load Django's database (Posgres backend). At some point the database gets into a weird state and I can no longer create objects. A call to: Chapter.objects.create(title = 'hello') throws the error: Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: duplicate key value violates unique constraint "genesis_chapter_pkey" DETAIL: Key (id)=(2) already exists. title is not a unique field. How is this even possible? I suspect Django has gotten out of sync with Postgres and tried to assign a used id, but import script does nothing but make calls to objects.create. How could that ever get Django out of sync? I can share the script but I doubt it'd be useful. It's just a bunch of loops ultimately calling object.create. Nothing more than that. -
Template solutions similar to thymeleaf for jinja2/python/django?
Java has the template engine thymeleaf that can render templates as plain html even though they have tags that takes data from the backend and a framework. Is there something similar for jinja2, django or python? I use jinja2 with google appengine and I'm happy with it, it's just that I would like to collaborate with a front-end programmer who does CSS and HTML without forcing him to run the entire stack. -
How to reuse common Wagtail Page objects (streamfields, edit_handler, content_panels)
From the demo page, I've seen reuse of common StreamBlock elements, with abstract classes that inherit from django.Models. I would like to know how I can reuse a set of Wagtail Page objects. Given this model: class EventPage(Page): body = StreamField( HomePageStreamBlock(), verbose_name='main content', default='' ) headingpanel = StreamField( HeadingPanelStreamBlock(), verbose_name='overpanel', default='' ) sidepanel = StreamField( SidePanelStreamBlock(), verbose_name='sidepanel', default='' ) master_event_id = models.CharField(max_length=1024, unique=True) creator = JSONField(null=True, blank=True) recurrence = ArrayField( models.CharField(max_length=200), null=True, blank=True ) google_cal_url = models.URLField('Google calendar link', max_length=1024) calendar = models.ForeignKey( Calendar, on_delete=models.PROTECT, verbose_name='Calendar', related_name='events', null=True, blank=False ) search_fields = Page.search_fields + [index.SearchField('body')] content_panels = Page.content_panels + [ FieldPanel('calendar'), FieldPanel('title'), StreamFieldPanel('body'), ] pagesection_panels = [ StreamFieldPanel('headingpanel'), StreamFieldPanel('sidepanel'), ] edit_handler = TabbedInterface([ ObjectList(content_panels), ObjectList(pagesection_panels), ObjectList(Page.promote_panels), ObjectList(Page.settings_panels, classname='settings'), ]) I would want to reuse the streamfield objects (body, headingpanel, sidepanel) and the content_panel StreamFieldPanel('body'), and the edit_handler. The only compelling reason for wanting this is the common DRY principle. I would like to know if trying to do code reuse here is viable and worth pursuing. I don't fully understand the Django ORM and the exact way of how Wagtail implements the Page model. My inclination is to just keep things super basic by avoiding code reuse, to avoid … -
Delete posts that pass 7 days of update time in django
I want delete all posts that pass 7 days of last update time, how can do this in my project. -
Django Error: TypeError: __init__() got an unexpected keyword argument 'attrs'
I am trying to create a form using Django wherein I am getting certain contact details from the user. I have defined the fields in ModelForm in models.py and providing other attributes like placeholder and css class using widgets in forms.py. But it is throwing me the following error: TypeError: __init__() got an unexpected keyword argument 'attrs' Following is my code: models.py from django.db import models class Contact(models.Model): your_name = models.CharField(max_length=100) your_email = models.EmailField() your_subject = models.CharField(max_length=100) your_comment = models.TextField(max_length=200) def __str__(self): return self.name forms.py from django.forms import ModelForm, TextInput, TextInput, EmailField from .models import Contact class ContactForm(ModelForm): class Meta: model = Contact fields = ('your_name', 'your_email', 'your_subject', 'your_comment') widgets = { 'your_name' : TextInput(attrs={'placeholder': 'Name *', 'class': 'form-control'}), 'your_email' : EmailField(attrs={'placeholder': 'Email *', 'class': 'form-control'}), 'your_subject' : TextInput(attrs={'placeholder': 'Subject *', 'class': 'form-control'}), 'your_comment' : Textarea(attrs={'placeholder': 'Comment *', 'class': 'form-control'}), } I have referred the Django docs for Overriding default fields and also this question init() got an unexpected keyword argument 'attrs' but cannot resolve the error. I am quite new to Python and Django and would highly appreciate any help. -
The image in django doesn't work
I use the carousel in bootstrap I made the two version. One is the html static file. The other is in Django framework, But I can't use django to do the following result . The following is html static file. <! DOCTYPE html> <html > <head lang="zh-Hant-TW"> <title></title> <meta name="viewport" content="width=device-width ,initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> </head> <body> <div class="col-xs-12 col-sm-12 col-md-8 col-lg-8"> <div class="panel panel-warning"> <div class="panel-heading">Most Popular Products</div> <div class="panel-body"> <div id="bestSellers" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#bestSellers" data-slide-to="0" class="active"></li> <li data-target="#bestSellers" data-slide-to="1"></li> <li data-target="#bestSellers" data-slide-to="2"></li> <li data-target="#bestSellers" data-slide-to="3"></li> </ol> <div class="carousel-inner"> <div class="item active"> <img src="images/spring.jpg" alt="First slide" class="img-responsive"> <div class="carousel-caption">Product 1</div> </div> <div class="item"> <img src="images/summer.jpg" alt="First slide" class="img-responsive"> <div class="carousel-caption">Product 2</div> </div> <div class="item"> <img src="images/autumn.jpg" alt="First slide" class="img-responsive"> <div class="carousel-caption">Product 3</div> </div> <div class="item"> <img src="images/winter.jpg" alt="First slide" class="img-responsive"> <div class="carousel-caption">Product 4</div> </div> </div> <a class="left carousel-control" href="#bestSellers" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a class="right carousel-control" href="#bestSellers" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> </a> </div> </div> </div> </div> </div> <div class="col-xs-12 col-sm-12 col-md-8 col-lg-8"> <div class="panel panel-warning"> <div class="panel-heading">Weather data</div> <div class="panel-body"> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> <li data-target="#carousel-example-generic" data-slide-to="2"></li> <li data-target="#carousel-example-generic" data-slide-to="3"></li> </ol> <div class="carousel-inner" role="listbox"> … -
Django Url filtering
I have a third party app that I'm including in my app: urlpatterns = [ url(r'webhook/', include('telegram.urls', namespace='api_webhook')), ] Let's say the telegram app has such url configuration: urlpatterns = [ url(r'^(?P<token>[-_:a-zA-Z0-9]+)/$', TelegramView.as_view(), name='api_webhook'), ] Now I want to do it in such a way that the token argument will only be my own token. Let's say if I have a token jbhgfjkljnmbvgcfhjbmnbv then I want to only accept requests to <mysite>.com/webhook/jbhgfjkljnmbvgcfhjbmnbv. How do I do this? If i just include the telegram app's urls then requests with other will be accepted in my app which will cause problems.