Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Url with MonthArchiveView give me error 404
I want to create a site (Django 1.8) where I can select events by date, exactly what happened in a given month and year. I decided to use the generic class MonthArchiveView. The url to the main page passes the year and month, as is the url - but I get a 404 error My view: class BookingListView(ListView, MonthArchiveView): model = models.Booking queryset = models.Booking.objects.order_by('-date_start') paginate_by = 80 template_name = 'events/archive_list.html' context_object_name = 'object_list' date_field = 'date_start' allow_future = True def get_context_data(self, **kwargs): context = super(BookingListView, self).get_context_data(**kwargs) context['mode'] = 'archive' return context My url: url(r'^(?P<year>[0-9]{4})/(?P<month>\d{2})/$', views.BookingListView.as_view(), name="list"), My link with parameters hardcoded): <a href="{% url 'archive:list' 2017 09 %}" title="{% trans 'Archive' %}"> {% trans 'Archive' %}#} </a> -
django-tinymce URL Pattern Error: Your URL pattern is invalid. Ensure tha t urlpatterns is a list of url() instances
Please can you help me. Are these urls correct for Django 1.11.4 and django-tinymce 2.6.0? <code> from django.conf.urls import url from tinymce import views urlpatterns = [ url(r'^spellchecker/$', views.spell_check, name='tinymce-spellcheck'), url(r'^flatpages_link_list/$', views.flatpages_link_list, name='tinymce-linklist'), url(r'^compressor/$', views.compressor, name='tinymce-compressor'), url(r'^filebrowser/$', views.filebrowser, name='tinymce-filebrowser'),</code> This is the error i get when i run : python manage.py makemigrations <code>ERRORS: ?: (urls.E004) Your URL pattern ('^tinymce/', (<module 'tinymce.urls' from 'D:\\projects_site\\camcoso\\venv\\lib\\site-packages\\tinymce\\urls.py'>, None, None)) is invalid. Ensure tha t urlpatterns is a list of url() instances. HINT: Try using url() instead of a tuple. </code> -
Whether I can set field's comment in the Model?
Can I set comment in the Account: class Account(models.Model): balance = models.CharField(max_length=16) grade = models.CharField(max_length=1, default=1) You see the MySQL tables in the Sequel Pro, every field has a Comment, whether I can set it in the Account? -
'app_label' in standalone Django app not working
The django app I've build contains all the models and a connection file. This app facilitates the use of the models across different django projects. The file structure looks like foobar | |---- foobar | | | |---- models | | | | | |---- __init__.py | | |---- base.py | | |---- story.py | | |---- comment.py | | |---- author.py | | | |---- __init__.py | |---- connection.py | |---- signals.py | |---- test |---- .gitignore |---- README.rst |---- setup.py The base.py file contains a model which is inherited by all other models (defined under story.py, comment.py, author.py) class BaseModel(models.Model): created = models.DateTimeField(editable=False) modified = models.DateTimeField(blank=True, null=True) archived = models.BooleanField(default=False) class Meta: app_label = 'core' abstract = True I want the prefix as core_ to all the table names and so I've set app_label as "core". Although when I test it out, the app_label turns out to be foobar (app name for my package) I also tried adding db_table to all the models separately (like db_table="core_story", db_table="core_comment" etc.) but even that's not working.. I'm still getting all the tables prefixed as foobar_ Any idea why is this happening ?? -
How can I use ORM to realize the `one-to-many` table?
The Account table to RunningLog table is one-to-one. So, in the Account Model, the foreignKey do not work for this situation, alright? # the user's account class Account(models.Model): balance = models.CharField(max_length=16) runningLog = models.ForeignKey(to='RunningLog') # here only can do one-to-one # account running logs class RunningLog(models.Model): from_account = models.CharField(max_length=32) to_account = models.CharField(max_length=32) content = models.CharField(max_length=128) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) How can I use ORM to realize the one-to-many situation? -
issubclass() arg 1 must be a class
AmazonWebAdmin is a class, why does it say that 'issubclass() arg 1 must be a class' -
Refreshing Table View Efficiently
I am using Django as my backend and inside my iOS application , I am fetching data through API's. I have a UITableView where I am fetching a list of places which also have a rating value with them. After implementing the refresh control I noticed that whenever I used to refresh, it used to append the new data in the array and created duplicity. I thought of a very simple solution which is that we can actually empty our array when refreshing so that we can avoid duplicity. Is it the most efficient way to do this? I am concerned because right now I have 3 places in my backend which I am trying to fetch and what about when there will be hundreds , will we have any performance impact ? -
Strange message in my Django Development server
This night, my Django development server displayed several messages : [29/Aug/2017 02:14:08] code 400, message Bad HTTP/0.9 request type ('\x03\x00\x00+&à\x00\x00\x00\x00\x00Cookie:') [29/Aug/2017 02:14:08] "+&àCookie: mstshash=hello" 400 - [29/Aug/2017 02:24:17] code 400, message Bad HTTP/0.9 request type ('\x03\x00\x00+&à\x00\x00\x00\x00\x00Cookie:') [29/Aug/2017 02:24:17] "+&àCookie: mstshash=hello" 400 - [29/Aug/2017 02:34:15] code 400, message Bad HTTP/0.9 request type ('\x03\x00\x00+&à\x00\x00\x00\x00\x00Cookie:') [29/Aug/2017 02:34:15] "+&àCookie: mstshash=hello" 400 - [29/Aug/2017 02:44:11] code 400, message Bad HTTP/0.9 request type ('\x03\x00\x00+&à\x00\x00\x00\x00\x00Cookie:') [29/Aug/2017 02:44:11] "+&àCookie: mstshash=hello" 400 - "+&àCookie: mstshash=hello" 400 - [29/Aug/2017 02:44:11] "+&àCookie: mstshash=hello" 400 - "+&àCookie: mstshash=hello" 400 - Any idea of what is it ? A kind of attack ? Thanks -
Django, extract kwargs from url
Suppose I have a url pattern url(r'^/my_app/class/(?P<class_id>\d+)/$', my_class.my_class, name='my_class') For a given url http://example.com/my_app/class/3/, I'd like to get class_id. I can do this with regex myself. I am wondering if there's a utility function for this since Django is already doing this to resolve url to a view. -
How to display a image from Input File
Is there a way to show the image that the user has chosen from the InputFile. <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} {{ form.image }} # the InputFile </form> <img src="{{ form.image.url }}"/> -
How to set secured path settings using Python
I need one help. I am uploading file into folder and for that I have set constant in settings.py file using Python. I am explaining my code below. settings.py: FILE_PATH = os.getcwd()+'/upload/' views.py: report = Reactor.objects.all() filename = str(uuid.uuid4()) + '.csv' response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='+filename with open(settings.FILE_PATH + filename, 'w') as csv_file: file_writer = csv.writer(csv_file) response_writer = csv.writer(response) file_writer.writerow(['Name', 'Status', 'Date']) response_writer.writerow(['Name', 'Status', 'Date']) for rec in report: if rec.status == 1: status = 'Start' if rec.status == 0: status = 'Stop' if rec.status == 2: status = 'Suspend' file_writer.writerow([rec.rname, status, rec.date]) response_writer.writerow([rec.rname, status, rec.date]) return response Here I need the secured file path to upload the downloaded file into folder using Python and Django. -
Django timezone.now() not returning current datetime when script running using supervisor
I am running python script using supervisor. Script has function timezone.now(). This always returns date when I started supervisor. I am not able to find out why timezone giving the wrong date. Can anyone help? -
Is there a way to use Django's default password reset without sending reset link via email?
Is there a way to use django's inbuilt password reset function without sending reset links via email or without the email option. I am currently developing a simple system with a few number of users on which sending emails are not needed.Thanks in advance -
Django unique URL access per user
urlpatterns = [ url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), ] With this url pattern, what would be the best way to define in the view that this url should only be accessed once by the current user, and that to read another news the first one should be closed? -
Django- Concurrent request handling with db.sqlite3 models, need best approach
I have developed my first Django web app which pulls data from RTC and displays content in the dash board. I'm storing the data in to sqlite3 db and from there fetching the data on to the web page. As this data will get changed frequently, I want to use cron job to periodically (after each 10 min) delete the existing content in the Models and write the latest data. Also, as this will be used by multiple users I wanted to know the best approach to handle concurrency in sqllite3. There might be chances that users will access the web at the time of deleting and rewriting new content in the models. I realized that select_for_update() will do only row level locking which will only work in other db's like oracle, mysql etc but didn't find sqlite3 there. Moreover in my scenario Do I need table level locking ? how would I do it ? I had been through the link https://medium.com/@hakibenita/how-to-manage-concurrency-in-django-models-b240fed4ee2 Where it is given about two approaches Pessimistic(which has row level locking mentioned) and optimistic( Don't think it works in case of multi user , in my scenario) Pls throw some light on the best approach to … -
The view savedb.views.cost didn't return an HttpResponse object. It returned None instead
In view.py from django.shortcuts import render from savedb.models import Cost from savedb.forms import CostForm from django.http import HttpResponseRedirect def cost(request): if request.method == 'POST': form=CostForm(request.POST) if form.is_valid(): date = request.POST.get('date', '') cost = request.POST.get('cost', '') cost_obj = Cost(date=date, cost=cost) cost_obj.save() return HttpResponseRedirect(reverse('savedb:cost')) else: form = CostForm() return render(request,'savedb/cost.html',{'form':form,}) And error is The view savedb.views.cost didn't return an HttpResponse object. It returned None instead. how to solve this error ...please help me ....thank in advance. -
How to detect the path traversal injection using Python
I have one doubt. I am downloading some file and storing it inside the project folder using Python. I am explaining my code below. report = Reactor.objects.all() filename = 'status.csv' response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='+filename with open(settings.FILE_PATH + filename, 'w') as csv_file: file_writer = csv.writer(csv_file) response_writer = csv.writer(response) file_writer.writerow(['Name', 'Status', 'Date']) response_writer.writerow(['Name', 'Status', 'Date']) for rec in report: if rec.status == 1: status = 'Start' if rec.status == 0: status = 'Stop' if rec.status == 2: status = 'Suspend' file_writer.writerow([rec.rname, status, rec.date]) response_writer.writerow([rec.rname, status, rec.date]) return response Here I am writing the content from database into .csv file and saving it into one folder using Python. I need to know which line might create path traversal vulnerabilities and in which way it can be prevent. -
django: middleware process_request and process_response
question: after django 1.10 is it safe to say that if a middleware's process_request is called then this middleware's process_response will be called no matter what happens? by no matter what happens I mean the machine runs django server is ok at least -
How does csrf_exempt works in django?
I have a server running on JavaScript trying to post username and password to another webpage running django. I understand that django requires you to include csrf tokens. i have control of both server and codes, what I wanted to achieve is instead of manually enter username and password, I wanted to post using JavaScript to django. Let's say the django login page is "https://mayan/authentication/login/?next=/", it has username password text box and a submit button. since I don't have the csrftoken on my JavaScript server, I chose to disable csrf token instead. In "urls.py", the url patterns "url(r'^login/$', csrf_exempt(login_view), name='login_view')". My understanding is this will exempt the login page from csrf authentication? But what I need to be able to login using post, $.post({ url:"https://mayan/authentication/login/", data:"username=admin&password=mypassword&next=/", }); Am I posting wrong? or am I exempting csrf wrongly? -
__init__() got an unexpected keyword argument 'user' when I try to filter
I would like to filter through the restaurants that the request.user has done. following the docs but i keep getting init() got an unexpected keyword argument 'user' when I try to filter forms.py from .models import Restaurant from .models import Item from django import forms class LocationCreate(forms.ModelForm): class Meta: model = Item fields = [ 'restaurant' 'category', 'food_name' ] def __init__(self, user=None, *args, **kwargs): super(ItemCreate, self).__init__(*args, **kwargs) self.fields['restaurant'].queryset = Restaurant.objects.filter(owner=user) models.py class Restaurant(models.Model): restaurant_name = models.CharField(max_length=250) restaurant_photo = models.ImageField(upload_to='roote_image') category = models.ManyToManyField(Category) timestamp = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) owner = models.ForeignKey(User) def get_absolute_url(self): return reverse('post:detail', kwargs={'pk': self.pk}) class Item(models.Model): restaurant= models.ForeignKey(Roote, on_delete=models.CASCADE, null=True) food_name = models.CharField(max_length=1000) category = models.CharField(max_length=250) owner = models.ForeignKey(User) def __str__(self): return self.food_name def get_absolute_url(self): return reverse('post:detail', kwargs={'pk': self.pk}) views.py class ItemCreate(CreateView): model = Item fields = ['restaurant','category ', 'food_name '] success_url = reverse_lazy('post:index') def form_valid(self, form): if form.is_valid(): roote = restaurant.objects.filter(owner =self.request.user) instance = form.save(commit=False) instance.owner = self.request.user return super(ItemCreate, self).form_valid(form) def get_form_kwargs(self): kwargs = super(ItemCreate, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs The form works without the filter but it brings in every instance of a restaurant that has been made in the web site -
Want to create search field but error 'WSGIRequest' object has no attribute 'request'
I am doing a django project, a music app .It contains artist name,album title,genre and image. When I create a search form ,I get this error.I am using django version 1.9.1 view.py from django.views import generic from . models import Album from django.views.generic.edit import CreateView , UpdateView ,DeleteView from django.core.urlresolvers import reverse_lazy from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login from django.views.generic import View from .forms import UserForm from django.db.models import Q def get_queryset(self): query= self.request.GET.get('q') if query: return Album.objects.filter(Q(album_title__icontains=query)) else: return Album.objects.all() form.py <form class="navbar-form navbar-left" method="GET" action=""> <div class="form-group"> <input type="text" class="form-control" name="q" value='{{ request.GET.q }}'> </div> <button type="submit" class="btn btn-default" >search</button> </form> url.py #checking for search url(r'^search/$', views.get_queryset, name='search'), image of error in browser https://ibb.co/ct7sZ5 -
How to have only CSV, XLS, XLSX options in django-import-export?
I have implemented django-import-export for my project. It provides me many file format options by default fro both import and export. How to restrict the file formats to only CSV, XLS and XLSX ? -
Django CMS Landing Page
DjangoCMS page tree is as followed. What is the best practice to not have "landing" as a nav-item but still render as the homepage. Should my base url config be modified or menu.html template? Page Tree Layout Thanks in advance, Greg -
> Unexpected token '<' [duplicate]
This question already has an answer here: unexpected token < in first line of html 2 answers In my project I get the bellow error in browser: Unexpected token '<' But the code seems no error. -
Getting User Information from Django Python Social Auth in the view
First time working with python-social-auth and Django but having trouble figuring out exactly how much information about the user's social account is available to me. When I access the extra_data of the UserSocialAuth object I can get the uid, and the access_token. To get additional details am I to feed those through the social company's (ex facebook) API? I can see that for some social auths like facebook Django's user object is magically populated with the first and last names from the social profile, but for others like LinkedIn that doesn't work. How do i find out which information is available for each social auth without manually probing each one? I'm just trying to get as much "Profile" data from the user and am worried going through the API is the "long way" of achieving this. I have actually read through the documentation but it may be too advanced for me; im not sure how to use the data that is acquired by the pipeline from the view. I'm not even sure if that sentence makes sense!