Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allow user to select random blog bost
I've started using Django 2.0 and Python 3.6.3 to develop a website which will display customized "Posts", as in a blog Post. I want the user to be able to click a button that basically says "Random Post". This button will take them to a template which loads a random blog post. Here's my Post model: class Post(models.Model): post_id = models.AutoField(primary_key=True) ... other fields ... other fields def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Here are some relevant views: class PostListView(ListView): model = Post template_name = 'blog/post_list.html' class PostDetailView(DetailView): model = Post template_name = 'blog/post_detail.html' Here is my problematic view: import random def random_post(request): post_ids = Post.objects.all().values_list('post_id', flat=True) random_obj = Post.objects.get(post_id=random.choice(post_ids)) context = {'random_post': random_obj,} return render(request, 'blog/random_post.html', context) Here I am trying to create a Values List of all post_id values for the Post model. Then I'm trying to get a random choice from this Values List, which would be a random id. Then I'm trying to create a context and render a template using this logic. Here are relevant urlpatterns: urlpatterns = [ path('post/<int:pk>/', views.PostDetailView.as_view(),name='post_detail'), path('post/random/<int:pk>', views.random_post, name='random_post'), Needless to say this is not working. If I leave off the "int:pk" it renders a blank … -
RedirectView.as_view not working at the root
In a django 1.8 project, I am attempting to redirect http://myProject/ads.txt to an external url http://a.location.that.has.the.ads.txt.file and thus serve the ads.txt file without using ftp to simply place the ads.txt in the root. Given this minimal directory structure: django projects myProject myapp urls.py views.py someotherapp yetanotherapp myProject settings.py urls.py (this is the top urls.py) views.py in myProject/myProject/urls.py, (the “top” urls.py) I have as the first entry in the urlpatterns list, the lines: urlpatterns = patterns('', (r'^ads\.txt', RedirectView.as_view(url=http://a.location.that.has.the.ads.txt.file', permanent=False)), followed by many more pattern matching regex’s. This does not work and fails with a 404. What does work is urlpatterns = patterns('', (r'^foo/ads\.txt', RedirectView.as_view(url=http://a.location.that.has.the.ads.txt.file', permanent=False)), and then calling http://myProject/foo/ads.txt Unfortunately, ads.txt files must be placed at the site root. I have tried many different regex’s that test fine in a regex validator, but just don’t work (returns 404). How do I do this without the extra dir “foo”? Any thoughts appreciated. Thank you. -
Django DB-Queryset
Hey i want to get each entry from my database where date = today and time >= now do you know a Django way to do that? in my Model DB is a DateTimeField named date whith the folowing entrys: 2018-01-08 20:00:00, 2018-01-08 20:00:00, 2018-01-08 19:00:00, 2018-01-08 20:00:00, 2018-01-08 20:35:00, 2018-01-08 20:00:50, 2018-01-08 18:00:00, 2018-01-10 20:00:00, 2018-01-09 20:00:00, 2018-02-08 19:00:00, -
an a interviewer ask me what is the command "how to check your model has no error"
an a interviewer ask me what is the command "how to check your model has no error" django have any type of command or not, i think there is no command like this -
Deployed Django instance not recognising a file as a file
I have a deployed django webapp which has been working fine. It scrapes sites for newly published .csv files and then uses them for data analysis which is then returned to the user. The most recent .csv is not being recognised as a file on the deployed version, but is on the test version on my local machine. The structure is as follows: -indicator-analyser -Analyser -AnalysisScripts -uploads -data -2017 -Monthly_File_Jun_Final.csv -Monthly_File_Sep_Final.csv When a user attempts to run the script on the Monthly_File_Jun_Final.csv, the webapp performs as expected. When they run the same script on Monthly_File_Sep_Final.csv, django throws an error as there is no file found. I have taken the file path that is passed in and used that to open the file in explorer, and I have used the same file path to load the .csv as a dataframe in pandas within the console with no problems. The path that is passed to the loading script is: C:\\webapp\\indicator-analyser\\Analyser/uploads/data/2017/Monthly_File_Sep_Final.csv When this is evaluated using os.path.isfile(filepath), it is being returned as False. However, when the other file is selected, this is returned and recognised as a file: C:\\webapp\\indicator-analyser\\Analyser/uploads/data/2017/Monthly_File_Jun_Final.csv Just for reference, this is running on a IIS server. I have restarted the … -
Django 2.0 - Using LoginRequiredMixin and ListView error
I'm trying to make a ListView with a form which when I submit returns me the object list. Below is the code for my views.py. class ChatListView(ListView): model = Chat form_class = NewMessageForm queryset = model.objects.all().order_by('-created_at')[:20][::-1] #returns 20 latest objects template_name = 'chat.html' def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() return redirect('chat') return render(request, self.template_name, {'form': form}) #code for form in the same view def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.form_class return context This works for me. But I want this view to only available to log in users. So I added a LoginRequiredMixin. class ChatListView(LoginRequiredMixin, ListView): model = Chat form_class = NewMessageForm queryset = model.objects.all().order_by('-created_at')[:20][::-1] template_name = 'chat.html' login_url = 'login' (Form got saved in the database but the data doesn't show up in the list view.) When I look at the bash the error is "POST /chat/ HTTP/1.1" 302 0. How can I implement the login required thing without this error? -
Django is not writing logs to a local file and how to log the requests
I am trying to log the below requests to a local file. I am using a logging function in settings.py file. Django is creating an empty file but its not writing any thing. Can any one help me what is the wrong i am doing and is it the right logging code to use for logging the below format data? Thank you. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/home/bluedata/mysite/info.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, 'mysite': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } [![These are the requests i want to log.][1]][1] **I WANT TO LOG THESE BELOW PLEASE HELP ME HOW TO DO** [05/Jan/2018 22:26:19] "GET /contact/ HTTP/1.1" 200 1833 [05/Jan/2018 22:26:20] "GET /static/personal/css/bootstrap.min.css HTTP/1.1" 304 0 [05/Jan/2018 22:26:20] "GET /static/personal/img/logo.jpg HTTP/1.1" 304 0 [05/Jan/2018 22:26:22] "GET / HTTP/1.1" 200 5533 [05/Jan/2018 22:26:22] "GET /blog/ HTTP/1.1" 200 1909 [05/Jan/2018 22:26:23] "GET /contact/ HTTP/1.1" 200 1833 [05/Jan/2018 22:26:23] "GET / HTTP/1.1" 200 5533 [1]: https://i.stack.imgur.com/KHh9j.png -
How to retrieve foreign key object from inside a django model validator
I have two models: class Photo(models.Model): # photo attributes and methods class Category(models.Model): banner = models.ForeignKey(Photo, validators=[validate_image_size]) My validator takes the Photo.id ForeignKey, gets the Photo object: def validate_image_size(photo_id): photo = Photo.objects.get(id=photo_id) # open the image using urllib # if image size too large, raise ValidationError() Is there a way to pass the Photo object to the validator? Instead of the photo_id. -
Django - loop through through records and update the record inside the loop?
I cant seem to find the documentation for this, but I want to update the record within a loop of a QuerySet example: data = Site.objects.all() for i in data: ... do stuff i.update(field="value") I know I could do it by: data = Site.objects.all() for i in data: ... do stuff Site.objects.filter(pk=i.pk).update(field="value") but this seems inefficient as I already have the record, so shouldn't need to query for it again. Thanks -
Python 3.6 - Celery not communicating with Redis backend - Using Heroku and Django
I am trying to get asynchronous tasks working with Heroku. I believe Celery is not communicating with the Redis backend properlly. If you could help me troubleshoot, that would be awesome. Thank you a thousand times. I followed these tutorials : Django with Celery: http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html Celery with Heroku: https://devcenter.heroku.com/articles/celery-heroku When I run theadd.delay() function (add being a function in my shared_tasks app) it doesn't seem to connect to the Redis Database. It just freezes after I input the delay function until I press control+C. It looks like: C:\Users\Jup\Drop>heroku ps:scale worker=1 Scaling dynos... done, now running worker at 1:Hobby C:\Users\Jup\Drop>heroku run python Running python on shrouded-ocean-19461... up, run.6193 (Hobby) Python .6.3 (default, Nov 14 2017, 17:29:48) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from Buylist.tasks import * >>> add(2,4) 6 >>> mul(3,4,3) 36 >>> add.delay(3,4) I'm supposed to see the tasks running via heroku logs -t -p but of course I don't. I've tried reading over the tutorial many times but I can't figure out what the problem is. The logs looks like: C:\Users\Jup\Drop>heroku logs -t -p worker 2018-01-08T16:13:10.157170+00:00 heroku[worker.1]: Stopping all processes with SIGTERM 2018-01-08T16:13:10.199379+00:00 app[worker.1]: 2018-01-08T16:13:10.199562+00:00 app[worker.1]: worker: Warm shutdown (MainProcess) … -
Django - does transaction live after view ends
I'm using Django 1.10 - Using middleware and doing some DB changes after view is called (see below). The question is - Assuming that some DB changes occurred on the Request (View called) - when getting to that part in the middleware, am I still in the same transaction or is it already done? def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. MyControlMiddleware.init(True) response = self.get_response(request) # Code to be executed for each request/response after # the view is called. if response: # does the transaction still live here? # ..... code to run after request is done.... MyControlMiddleware.clear() -
How to set Django-Crispy-Forms multiple fields in one line?
I'm trying to set multiple fields in one line with Django Crispy Forms but it's not working. Here's what I got: from crispy_forms.helper import * from crispy_forms.layout import * from crispy_forms.bootstrap import * class ExampleForm(forms.Form): mins = forms.ChoiceField(choices=[(x, x) for x in range(0, 60)]) hrs = forms.ChoiceField(choices=[(x, x) for x in range(0, 24)]) month = forms.ChoiceField(choices=[(x, x) for x in range(1, 13)]) weeks = forms.ChoiceField(choices=[(x, x) for x in range(0, 7)]) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.layout = Layout( Div( Div('mins',css_class='col-md-6',), Div('hrs',css_class='col-md-6',), Div('month',css_class='col-md-6',), Div('weeks',css_class='col-md-6',), css_class='row', ), FormActions( Submit('submit', 'Submit'), ), ) super(ExampleForm, self).__init__(*args, **kwargs) What am I doing wrong? -
How do I allow users to write python code that runs with using code on the backend?
So I have a Django Application that uses a "framework" we have created that includes methods and classes that are known to the user. I want to implement a feature such that the user can write code on the website's provided editor, which would then include this framework library and display the code written. I am using Django and I am not sure how would I be able to execute the code and display the returning values from the code written by the user. -
Expecting value: line 1 column 1 (char 0) JSONDecoderror
I have been researching for quite some time without finding the error, I am using the Django Rest framework with an ajax call in order to use chart.JS My code is working properly on local but since I uploaded to heroku I am getting that error JSONDecodeError at /website/project/12/api/chart/data2/ Expecting value: line 1 column 1 (char 0) and I have no idea how to solve it, Could someone please give me a hand on this ? the complete traceback is : Environment: Request Method: GET Request URL: https://guarded-tor-21020.herokuapp.com/website/project/12/api/chart/data2/ Django Version: 1.11.5 Python Version: 3.6.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', 'website', 'django_extensions', 'crispy_forms', 'survey', 'bootstrapform', 'rosetta', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/app/.heroku/python/lib/python3.6/json/decoder.py" in raw_decode 355. obj, end = self.scan_once(s, idx) During handling of the above exception (0), another exception occurred: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/views.py" in dispatch 489. response = self.handle_exception(exc) File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/views.py" … -
Django template for loop - dependant on variable. 'int' object is not iterable
I'd like to run a for loop within a Django template, where the range is dependant on the value of a variable. For the size of the name, add a space. The name is a string value. {% for i in person.name|length %} &nbsp; {% endfor %} Running this code produces an 'int' object is not iterable Django Error. However, calling the following works, and will dispay the length of the name {{ person.name|length }} Thanks! -
convert left outer join query with django orm
I have this model: class Player(models.Model): firstname = models.CharField(max_length=200) stage = models.CharField() class PlayerSummary(models.Model): player = models.ForeignKey(Player, related_name="playersummary").count() I want to do this query: select COUNT(*) from player p left outer join player_summary ps on p.id=ps.player_id where p.stage in ('Noob', 'Beginner', 'Pro') (this is only a fictional example). I tried this: queryset = Player.objects.filter( stage__in=('Noob','Beginner','Pro') ).selected_related('playersummary').count() this gives the correct count, though when i try to print queryset.query gives me this output: <repr(<django.db.models.query.QuerySet at 0x85a1710>) failed: django.core.exceptions.FieldError: Invalid field name(s) given in select_related: ......> which is correct as i think select_related does not works for reverse relation. secondly i tried: queryset = Player.objects.filter( stage__in=('Noob', 'Beginner', 'Pro'), playersummary__isnull=True) this way i get left outer join with two tables but i also get this in my where clause: player_summary.id is NULL (which i dont understand) will this exclude players whose record in player_summary exists? how can i reach equivalent of my raw sql query in django ORM? -
Django Rest Framework - automatically annotate queryset
I use one Serializer in many different places in my project. I need to use one annotation but the problem is that I don't want to annotate it in all views so I would like to do universal annotation in the Serializer itself. It is possible? Now I need to do this before every serialization: City.objects....filter....annotate( number_of_users_here_now=Count('current_userprofiles')) I tried: class NumberOfUsersInCityNowField(serializers.Field): def to_native(self, value): count = value.annotate( number_of_users_here_now=Count('current_userprofiles'))['current_userprofiles__count'] return count class CityMapSerializer(serializers.ModelSerializer): number_of_users_here_now = NumberOfUsersInCityNowField() class Meta: model = City fields = ('place_id', 'lat', 'lng', 'number_of_users_here_now', 'formatted_address') This Serializer returns: AttributeError at /api/ajax-check-trip-creation Got AttributeError when attempting to get a value for field number_of_users_here_now on serializer CityMapSerializer. The serializer field might be named incorrectly and not match any attribute or key on the City instance. Original exception text was: 'City' object has no attribute 'number_of_users_here_now'. -
Django Model check data type integrity before saving
I have a Django project where I am forced to do a raw sql query (so not using a Model for saving this information), but I still want to check for correctness or data types on some of the arguments of this query. Let's say I have this model: class MyModel(Model): name = models.CharField(max_length=768) product_count = models.PositiveIntegerField(null=True, blank=True) paid_amount = models.DecimalField(decimal_places=2, blank=True) And I want to do a simple Raw SQL query like: insert into mymodel (name, product_count, paid_amount) values (%s, %s, %s); Now I know I can do this with Django models directly, but please let's think that I am forced to do this with raw SQL (also my real query is very different that this one, I am just presenting an example to expose my case). Now, I have three variables I want to insert on my Raw SQL, but for each of them I want to check data type, so before calling the database insert, I want to use my Django model for checking its type: check if my name variable is actually string (and maybe that it won't pass 768 characters, but with only checking if it is string is ok). check if my product_count variable … -
ManyToManyField is not displayed in the Python shell
I am learning how to work with mysql database,using Django. I've created models in myapp. I've added ManyToManyField to my models. I've applied the changes made to these models, using makemigrations and migrate in Python shell. All processes have been going OK. However, this ManyToManyField is not displayed in Python shell when I type the command: >>> Employer._meta.fields Employer is the name of my model. And I want to print all Fields of this model in the terminal. When I type this command, I get Employer's fields printed in the terminal except for this ManyToManyFiled. Could you explain why? (<django.db.models.fields.AutoField: id>, <django.db.models.fields.related.ForeignKey: employees>, <django.db.models.fields.CharField: name>, <django.db.models.fields.DateField: foundation_date>) -
Is it possible to apply the image tag to the result of another image tag?
I have a little question about the image tag of wagtail. Is it possible to apply the image tag twice time on the same image in a concatenated manner? For example: {% image photo width-1500 as photo_scaled %} {% image photo_scaled fill-400x300 as image %} Thanks in advance -
Django / Angular 5
I am not an expert in programming. Is it a good practice to work with Django for the backend and Angular 5 for the frontend? Is it difficult to work in concert with these two frameworks? -
Django RunTime Warning due to receiving a native DateTime. How to solve?
In my settings.py TIME_ZONE is set to 'UTC'. In one of my models I'm importing the created_on field from an external API which returns time in utc format. For eg: 1515374422.0 To convert that into DateTime format I use: created_on=datetime.datetime.fromtimestamp(float(1515374422.0)) post=Post(name="ABC", created_on=created_on) But that always runs with a RunTime warning of: RuntimeWarning: DateTimeField Image.added_on received a naive datetime (2017-12-14 14:48:22) while time zone support is active. I don't understand it. What does that mean? Is something wrong with the DateTime conversion code? -
SubQuery in Django 1.11.8 is very slow - can I speed it up?
I have some tables that aren't joined by a FK relationship in two separate Django models and I'm trying to do a SubQuery. Data looks like this: # "master" data table - reflects real property ownership by humans # there are often changes to property ownership class OwnershipRecord(Model): parcel = CharField(max_length=10, unique=True) owner_name = ... other data fields ... # Poor man's 'elastic search' or an index of sorts for OwnershipRecord class Lead(Model): ownership_record = OneToOneField(OwnershipRecord) preforeclosure = BooleanField(default=False) aggregated data/booleans/etc... # "descriptor" table for a property # there are not often changes to a property's physical traits ResidentialMasterRecord(Model): parcel = CharField(max_length=10, unique=True) # These are the SAME as OwnershipRecord livablesqft = ... lotsqft = ... So I'm working on a query that can filter Lead objects by square footage. The Lead is related to the OwnershipRecord, but there are no relationships to ResidentialMasterRecord - it exists as a "fact table" kind of like a set of coordinates would for a specific address. I thought a SubQuery would work in this case, where I can reference the parcel from the OwnershipRecord and ResidentialMasterRecord to link the two real-time. This is extremely slow. Here is the query I'm attempting: from django.db.models … -
How to filter choices in Django2's autocomplete_fields?
In Django 2.0, autocomplete_fields was added, which is great. Without autocomplete_fields, I can change the queryset of a ForeignKeyField using formfield_for_foreignkey. But combining the two together doesn't work - it looks like the list of options for autocomplete is dynamic and coming from a different url, instead of from the current form. So the question is - How can I change the queryset in the autocomplete widget? -
How can I insert local image file with Django CKEditor RichTextField?
I am using Django 2.0 and CKEditor 5.4 and according to the document's procedure to test, it work for me with one question as the title stated. I had tried RichTextField, I can only use the external or local server URL link but not the client's resource such as desktop's image file; and and RichTextUploadingField which can upload to local server first and get the local server's URL to fill in but it seems not nature to me. Do I mis-understand the CKEditor's feature for image insertion ? I suppose this behavior should like MS Word's drag&drop from the DeskTop or Download folder. Can anyone tell me ? Thanks a lot !!