Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can you put static folder in project root, rather than app root?
For example, if I want to use the same style.css for all my apps, where should I put the static folder? I'm pretty sure Django site says to put it in the application folder? But what if I have multiple apps? -
GeoDjango saving Point geometry from form
I have one form and one formset in my django project. The form has one input with a Point geometry. So I have input there which looks something like that: 39.237103, 25.667217 when user sends a form I want to split this input and save this as Point geometry, in models Point looks like this: position = gismodels.PointField(null=True, srid=4326) I use this code for validation and saving form, formset and Point geometry if request.method == "POST": checklist_form = ChecklistForm(request.POST) observation_formset = ObservationFormSet(request.POST) #error if checklist_form.is_valid() and observation_formset.is_valid(): checklist = checklist_form.save(commit=False) latitude, longitude = request.POST.get('position', '').split(', ', 1) checklist.position = Point(longitude, latitude) checklist.save() for observation_form in observation_formset: observation = observation_form.save(commit=False) observation.checklist_id = checklist observation.save() But the problem is that POST data for position has bad format so validation of checklist_form raise this error before I can split the coordinates: String or unicode input unrecognized as WKT EWKT, and HEXEWKB. I read that I can copy POST data and change them, but I also read it is a bad practice. What I think about is using javascript for changing coordinates for appropriate format but GeoDjango surely has better functionality for saving Point geometry. -
Modify django models.Model so that includes certain boiler plate fields [duplicate]
This question already has an answer here: Django: how to create custom “base” model 2 answers I would like to subclass django.models.Model with from django.db import models from django.utils import timezone class ArcheModel(models.Model): created = models.DateTimeField() modified = models.DateTimeField() active = models.BooleanField(default=True) def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.created = timezone.now() self.modified = timezone.now() return super(ArcheModel, self).save(*args, **kwargs) So that all the other models can inherit from it and all have those info. class TestModel(ArcheModel): test = models.CharField() However, after substituting subclassing from models.Model to ArcheModel, when I try to perform the migration, I am asked: You are trying to add a non-nullable field 'archemodel_ptr' to ... without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: Why am I asked to set for archemodel_ptr (pointer to the parent model) instead of the additional fields? Is it possible to extend django models.Model with ArcheModel fields without having the archemodel_ptr, but just … -
Django templatetags rendered as None in the template
Somebody can help me how to solve this problem, why my templatetags isn't rendered in the template? but, only rendered as None instead. Previously I working with Django==1.10.4. 1. templatetags/total_tags.py, I already created __init__.py inside this folder. from django import template from myapp.models import Category register = template.Library() @register.simple_tag def total_categories(): """ {% load total_tags %} {% total_categories %} used in: `includes/menus_dashboard.html` """ print(Category.objects.all()) # this worked well Category.objects.all().count() 2. myapp/dashboard.html {% extends "base.html" %} {% load i18n %} {% block title %}{% trans "Dashboard" %} :: {{ block.super }}{% endblock %} {% block content %} <div class="ui two column stackable grid"> <div class="four wide column dashboard-menu"> {% include "includes/menus_dashboard.html" %} </div> </div> {% endblock %} 3. includes/menus_dashboard.html The templatetags of {% total_topics %} is similiar with {% total_categories %} {% load total_tags %} <div class="ui fluid large inverted vertical pointing menu"> <a class="active item"> Dashboard </a> <a class="item"> Categories <div class="ui small label">{% total_categories %}</div> </a> <a class="item"> Topics <div class="ui small label">{% total_topics %}</div> </a> <a class="item"> Moderators <div class="ui small label">2</div> </a> <div class="item"> <div class="ui icon input"> <input type="text" placeholder="Search threads..."> <i class="search icon"></i> </div> </div> </div> Another idea, I tried like this answer: http://stackoverflow.com/a/12143011. and … -
Django - CreateView with DetailView
I'm trying to make a web page with calendars. Every calendar have events. I'm trying to make a form to add an event to a calendar. We can make this if we click on "Add new event" on a certain calendar. So, as I understand I would need two views combined - DetailView (to know on which calendar we should put our event) and CreateView. This is how I'm making this: class EventCreate(CreateView): model = Event form_class = EventForm success_url = '/prijavljen/' def form_valid(self, form): form.instance.calendar = self.request.calendar return super(EventCreate, self).form_valid(form) def get_context_data(self, *args, **kwargs): context = super(EventCreate, self).get_context_data(*args, **kwargs) context['calendar'] = self.model return context But it's not working, I don't event get calendar when I click on it. Any help would be appreciated. -
How to learn Django in Django Documention?
I have finished python and I am starting to learn django, and everyone recommend me to learn from django documentation, but I am confused to learn from that documentation because there are so many sections and it's too hard to understand. So which section should I read first from that documentation or how to learn properly, because I have to know how to learn the codes. -
Django ORM - Error retreiving data -
I'm creating a page that has one video , as many comments , replies for each comment I could retrieve video and comments but replies for each comment haven't been retrieved eventually. I made some for loops in views file but didn't know also how to retrieve it in the templates file. I'm stuck between views and templates till now I'm using django 1.10.4 models.py class Video(models.Model): title = models.CharField(max_length=120) embed_code = models.CharField(max_length=500) slug = models.SlugField(null=True, blank=True) category = models.ForeignKey("Category", null=True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) active = models.BooleanField(default=True) featured = models.BooleanField(default=False) free_preview = models.BooleanField(default=False) share_message = models.CharField(max_length=150, default=default_share_message) objects = models.Manager() # activemodel = ActiveModel() featuresandactive = Features() class Meta: unique_together = ('slug', 'category') def __str__(self): return self.title def get_absolute_url(self): try: return reverse('video_detail', kwargs={'vid_slug':self.slug, 'cat_slug':self.category.slug}) except: return "/" class Comment(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(MyUser) path = models.CharField(max_length=350) video = models.ForeignKey(Video, null=True, blank=True) text = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) Timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) active = models.BooleanField(default=True) objects = CommentManager() def __str__(self): return self.text class Reply(models.Model): user = models.ForeignKey(MyUser) comment = models.ForeignKey(Comment,null=True, blank=True) text = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) Timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) active = models.BooleanField(default=True) objects = ReplyManager() def __str__(self): return self.text views.py … -
Forbidden You don't have permission to access a Django site
I followed the Django docs and edited apache2.conf with this setup, WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py WSGIPythonPath /path/to/mysite.com <Directory /path/to/mysite.com/mysite> <Files wsgi.py> Require all granted </Files> </Directory but when I access mysite.com I get this error. Forbidden You don't have permission to access / on this server. Apache/2.4.18 (Ubuntu) Server at www.mysite.com Port 80 I'm on a VPS. -
uWSGI says "no python application found" running Django
I was following this guide when I suddenly stuck at the point where I should run Django project via uWSGI. When I try uwsgi --http :8000 --chdir /path/to/your/project --module project.wsgi --virtualenv /path/to/virtualenv I can see nothing but "Internal Server Error" sign in my browser and messages like no python application found and no app loaded, going in full dynamic mode and Import Error: no module named django.core.wsgi Again, I was following the guide. Step by step. And yes, I've tried everything I found on the Net, starting with creating an .ini file, and nothing helped. Hope to get some useful advice. -
Django rest framework and cross origin requests
I try to do some request from a javascript client to rest api build with Django rest framework. All GET request to /api/test are public, then no session or token or watever are needed. All POST to api/test are private and user have to use oauth2 According to the documentation, I have to manage cross origin request with django-core-headers. After installing this module to my django, I've set CORS_ORIGIN_ALLOW_ALL to True but: 1) is it a good practice ? 2) is there a good solution to allow cross origin request only on some points ? Thanks -
How should I keep a private chat history for each user ?
I would like to keep a chat history between my users, just like this : Username of who sent or Username of who received : Last sent or received message But I have no idea how I should do it since I don't know how can separate the objects of each person and retrieve the last message. models.py class userComment(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, blank=True, null=True, related_name="receiver") sent_at = models.DateTimeField(auto_now_add=True) comment = models.TextField(max_length=255, null=True) urls.py url(r'^$', inbox, name='comments_inbox'), url(r'^(?P<username>\w+)/$', addComment, name='add_comment_form'), views.py def inbox(request): username = User.objects.? users = userComment.objects.filter(?) ... def addComment(request, username): username = User.objects.get(username=username) users = userComment.objects.filter(Q(Q(sender=request.user) & Q(receiver=username)) | Q(Q(sender=username) & Q(receiver=request.user))).order_by('sent_at') ... Result on chat profile addComment view shows the message of each individual conversation on user's chat profile as the image below : Expected result on the inbox page inbox view should show the conversation history of each user with whom he chated, as the image below : templates/addComment.html {% for user in users %} {% if user.client == request.user %} <li style="text-align:left; background:yellow;"> <p>from {{ user.client }} to <strong>{{ user.worker }} </strong> | {{ user.sent_at }}</p> <p>{{ user.comment }}</p> </li> {% else %} <li style="text-align:right; background:#eaeaea;"> <p>from {{ user.client }} … -
How to filter for current object on FormView
I'm having this urls.py ... url(r'^storageitem/(?P<pk>[\w]+)/merge/$', login_required( StorageItemMergeView.as_view()), name='storage_item_merge'), ... with this view.py ... class StorageItemMergeView(FormView): form_class = MergeStorageItemsForm success_url = reverse_lazy('storage_item_list') template_name = 'pmgmt/storageitem/merge.html' ... As the URL might look like localhost:8000/storageitem/155/merge/ I'd like to exclude 155 from the form. I tried to define a custom queryset queryset = StorageItem.objects.exclude(pk=kwargs["pk"]) but kwargs is seems not be present at this very point. ... queryset = StorageItem.objects.exclude(pk=kwargs["pk"]) NameError: name 'kwargs' is not defined What is the correct way to create a FormView based on a model with all items beside the current one? -
Server returning id then failing when that id is used as a foreign key
I am trying to rapid-fire save a series of items related by foreign keys. After the parent item is saved, I then use the returned id of the parent item when creating the child item. The works once or twice, but on the second or third time, I get the message {"parent_id":["Invalid pk \"5063\" - object does not exist."]}. I have verified that The ID being sent to create the related item is in fact the same one that was returned in the 'done()' after saving the parent item If I add in a delay before the child item is created, I can check in the database and verify that the parent item was indeed created and saved to the database If I add in a long enough delay before the child item is created (~15 s), no error is produced Since the backbone.js front-end seems to be sending valid POST requests, and the items are being written to the database correctly right away, I presume that this is a django problem. Any suggestions? var i = 0; function createNew() { var parent = ParentObjects.add({name: "New Parent Item"}); parent.save().done(function(var attributes, stuff, stuff) { var id = attributes.id; var child = … -
best framework to build a music download web application?
I am looking to build a web application that allows people to download music from my website, what is the best framework I can use? Or how can I go about doing that> -
Image doesn't appear in my "media" folder after upload Django
I have some trouble uploading picture with Django. settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') MEDIA_URL = '/uploads/' models.py: class Dater(AbstractUser): AbstractUser.username = models.CharField(max_length=30) AbstractUser.password = models.CharField(max_length=30) picture = models.ImageField(upload_to="users_picture", blank=True, null=True) summary = models.TextField() .... forms.py: class UserForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Enter your username'})) password = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','type': 'password','placeholder': 'Enter your password'})) summary = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control col-xs-2'})) ... class Meta: model = models.Dater fields = ['username', 'password', 'summary', 'picture'] My html: <form id="signupForm" method="post" action="" enctype='multipart/form-data'> {% csrf_token %} {% include 'website/form-template.html' %} <button type="submit" class="btn btn-danger">Submit</button> </form> I have create a folder: "uploads" at the same level than the file manage.py. Inside this folder I also create another folder: "users_picture" where I was expected my picture to be uploads to, but when I add the user the image is not upload at all. -
Setting cookies on ajax likes in Django
Have some problem with setting cookies on likes, so here you can see the code in the views.py. Watched many tutorial on how to work with cookies in django but I can't adopt any code to this one, so I need your advice how can I set cookies in this code? def add_like(request): book_id = None if request.method == 'GET': book_id = request.GET['book_id'] likes = 0 if book_id: bk = Books.objects.get(id=int(book_id)) if bk: likes = bk.likes + 1 bk.likes = likes bk.save() return HttpResponse(likes) this is js code: $('.likes-button').click(function () { var bkid; bkid = $(this).attr("data-ansid"); $.get('/add_like/', {book_id: bkid}, function (data) { $('#like_count').html(data); $('#likes').hide(); }); }); -
How to get object using filter on ManyToManyField
I need to get object which have 2 concrete objects in his ManyToManyField, but I don't know how to write it in filter arguments. Model: class Dialogue(models.Model): name = models.CharField(max_length=30, blank=True) is_conference = models.BooleanField(default=False) participants = models.ManyToManyField( Person, related_name='dialogues', null=True, ) def __str__(self): return self.name or self.pk And in view I want to get suitable dialogue which contain in participants field 2 objects - request.user and companion: target_dialogue = Dialogue.objects.get(is_conference=False,participants__in=[request.user,companion]) Bit it doesn't work. I have NoneType error. I think I simply don't know commands for it and it is hard to find for me. Help me please. -
how to send form data from one page to another using django
Problem:I want to send the form data of index.html to greetings.html which show the username on greetings.html, But it is displaying error. Can you suggest a simple method to send the form data to another page using django. I want a select box which display the option present in list. Inside the form. greetings/template/index.html {% load static %} <!DOCTYPE html> <html> <head> <title> </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'greetings/css/style.css' %}" /> {% verbatim %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> {% endverbatim %} </head> <body > <div class="container-fluid" > <div id="home" class=""> <form class="input-form text-center" name = "form" method = "POST" action="{% url 'greetings.views.greetings'%}"> {% csrf_token %} <h1> Create your wishes </h1> <input type="text" name = "username" placeholder="Enter your name"/> <select name="select"> <option value=''>Please Choose your wish</option> </select> <br/> <input id="btn" type="submit" name="submit" value="Create"/> </form> </div> </div> </body> </html> greetings/template/greetings.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="demo-wish"class="card text-center"> <h4> {{ username }} </h4> <h3> Wishes you </h3> <h4> Happy{{ username }} </h4> </div> <div id="demo" class="card text-center"> <form> <h2>Create Your Wishes</h2> <h4>ENTER YOUR NAME TO WISH YOUR FRIENDS AND FAMILY MEMBERS</h4> <span>{{ username }}</span><br/> … -
django rest-farmework nested relationships
Using django rest-farmework to implement the API, there is a problem in the nested relationship here. The content associated with the foreign key can not be displayed, the specific code is as follows: models.py class Category(models.Model): name = models.CharField(max_length=30) amount = models.IntegerField() class Source(models.Model): name = models.CharField(max_length=50) rss_link = models.URLField() amount = models.IntegerField() # ForeignKey category = models.ForeignKey(Category) views.py class CategoryListView(APIView): def get(self, request): category = Category.objects.all() serializers = CategorySerializers(category, many=True) return Response(serializers.data) serializers.py class SourceSerializers(serializers.ModelSerializer): class Meta: model = Source fields = ("id","name","amount") class CategorySerializers(serializers.ModelSerializer): source = SourceSerializers(many=True, read_only=True) class Meta: model = Category fields = ("id","name","amount","source") Program running results: enter image description here Why can not show 'source' in the result? I hope the result is like this [ { "id": 1, "name": "默认分类", "amount": "0", "source": [ { "id": 34, "name": "博客园", "amount": "231" }, { "id": 35, "name": "CSDN", "amount": "643" } ] }, { "id": 2, "name": "科技频道", "amount": "0", "source": [] } ] -
formset should contain a valid Django Formset
I am trying to make a form where I can add multiple object to a list. When I try to use the formset I get the error, everything seems to work when I remove the formset from the template. Parameter "formset" should contain a valid Django Formset. I have looked at multiple examples, but none seem to work. template: <form action="{% url 'usermanager:organization_edit_details' organization.id %}" method="post" class="form"> {% csrf_token %} {% bootstrap_form form layout='inline' %} {%bootstrap_formset formset %} {% buttons %} <button type="submit" class="btn btn-primary"> {% bootstrap_icon "star" %}Submit </button><button class="btn btn-primary">Cancel -dead</button> {% endbuttons %} </form> view.py def organization_edit_details(request, organization_id): organization = get_object_or_404(Organization, pk=organization_id) form = OrganizationForm(request.POST or None, request.FILES or None, instance=organization) formset = StaffFormSet(request.POST or None, instance = organization) if form.is_valid(): organization.organization_name = form.cleaned_data['organization_name'] organization.description = form.cleaned_data['description'] organization.rules = form.cleaned_data['rules'] organization.open_times = form.cleaned_data['open_times'] organization.website = form.cleaned_data['website'] organization.email = form.cleaned_data['email'] organization.street_name = form.cleaned_data['street_name'] organization.street_number = form.cleaned_data['street_number'] organization.postcode = form.cleaned_data['postcode'] organization.country = form.cleaned_data['country'] organization.kvk_number = form.cleaned_data['kvk_number'] organization.save() if formset.is_valid(): return HttpResponseRedirect(reverse('usermanager:organization_edit_details')) return render(request, 'user_manager/organizationEdit.html',{'organization':organization, 'form':form}) forms.py from django.forms import ModelForm, Textarea, inlineformset_factory from organizations.models import Organization, StaffMemberList class OrganizationForm(ModelForm): class Meta: model = Organization fields = ['organization_name', 'description', 'rules','open_times',\ 'website', 'email', 'street_name', 'street_number', 'postcode', 'country'] widgets = { 'description': … -
Django the rss library generated xml Why does the browser does not resolve it?
URL configuration: from blog.feeds import RssSiteNewsFeed urlpatterns = [ url(r'^rss.xml$', RssSiteNewsFeed()), ] Feeds module: #!/use/bin/env python # _*_ coding:utf-8 __ from django.contrib.syndication.views import Feed from .models import Article from django.utils.feedgenerator import Rss201rev2Feed class CorrectMimeTypeFeed(Rss201rev2Feed): mime_type = 'application/xml' class RssSiteNewsFeed(Feed): feed_type = CorrectMimeTypeFeed author_name = "" title = "" link = "" description = "" def items(self): return Article.objects.all().order_by('-created_time')[:5] def item_title(self, item): return item.title def item_link(self, item): return '/article/%s' % item.url Then there is a strange phenomenon, img Obviously has been parsed out xml content, there are two issues: Why parse out of the content is parsed twice? The browser explicitly said is Content-Type: application / rss + xml;charset = utf-8 types of documents, but why show the exact string? And should not display the contents of xml format. -
How to use GroupBy in Django ORM?
I'm trying to write a query which depends on two ForeignKeys. There is an Product which can have many Occurence objects (ForeignKey). Occurence object can have many Scan objects (ForeignKey too). Now I want to get for every occurence of object last scan, if its attribute price is not Null (Price is a OneToOneField), according to its datetime attribute. The naive approach: product = Product.objects.first() scans = [] for occ in product.occurences.all(): scan = occ.scans.filter(price__isnull=False).orderby("-datetime").first() if scan: scans.append(scan) >>> result is scans list This approach has many disadvantages. One product can have hundreds of occurences and millions of scans so the best would be database to do the work. So I'm looking for query which can do this. Scan.objects.filter(occurence__product=product,price__isnull=False) this returns all scans for the product with not null price attribute. I think I should use GroupBy but I don't know how. -
how to get a saved value in redis and use it again (django)
I'm new to redis. developing a django project, I wonder how to set a value in redis in one function in my views.py and in another function get it and use it again. (imagine I want to can anyone help me with an actual example? Thank you very much -
Errno 22 invalid mode ('rb') while unzip a zip from url using python
I'm trying to unzip the file from an URL, and stuck with the below Error. I would get the URL's dynamic so the path may keep vary. [Errno 22] invalid mode ('rb') or filename: 'http://example.com/media/example.zip' url = r"http://" + request.get_host() + uploaded_file_url with zipfile.ZipFile(url, "r") as zip_ref: zip_ref.extractall("c:/tmp") zip_ref.namelist() The above is the piece of code that i use for unzip. As per my understanding expected is to pass the escape character so that it can read url "IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'" How we can do this for URL. -
How to test - django-rest web app with 3rd party python libs and ReactJs frontend
I am building a web app that consists of the following components: Python package(s) written by myself Django backend Django-rest API ReactJs frontend I want to know what testing framework(s?) and workflow/pattern to use to allow me to guarantee that specific branches of the code are fully tested and also provide % coverage.