Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 %}   {% 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 !! -
In django-rest-framework, is it possible to use oauth and session authentication simultaneously?
Here's what I'm trying to do: I'm building a finance app. There's a web component, which is using Django templates and jQuery for AJAX requests, and a mobile client. My goal is to use session-based authentication for the AJAX requests coming from the web app, using django-allauth for authentication, and OAUTH2 for the mobile app with django-oauth-toolkit. I'm using django-rest-framework for the endpoints. The AJAX behaviour was working fine before I added the OAUTH middleware/authentication backend. This code from my view.py now prompts a 401 unauthorized when accessed via AJAX call, even when the user is authenticated using django-allauth. It worked previously (and still works when accessed via curl with an access token): @api_view(['GET']) def portfolio(request): """ Get account balances, total portfolio value in CAD, and balances converted to CAD at current market rates. """ try: account = request.user.account except ObjectDoesNotExist: return Response(status=Status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = AccountSerializer(account) return Response(serializer.data) Here are the relevant bits of mysettings.py: MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django_otp.middleware.OTPMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = ( 'allauth.account.auth_backends.AuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', 'oauth2_provider.backends.OAuth2Backend', ) An older method I wrote that doesn't use django-rest still works fine: @verified_account_required def get_rates(request): if request.method == 'POST': … -
Django @login_required decorator does not redirect to specific page
I'm trying to make a limited user edit page if the login is not executed. After logging in, the edit page opens with any user_id in the url. Although edit page should be open only with user_id already logged in user. For example, I logged in with user_id=7, so only one next url (http://127.0.0.1:8000/user/7/edit) have to have access to edit page. And this edit page is available by any next urls also (http://127.0.0.1:8000/user//edit) Are there any errors or mistakes in my code? I already have cleared cache in Opera and Chrome, but issue still exist. Django ver. 1.11.9. LOGIN_URL is not defined in settings.py urls.py urlpatterns = [ url(r'^login/$', user_login, name='user-login',), url(r'^(?P<user_id>\d+)/edit$', user_edit, name='user-edit',), ] views.py def user_login(request): login_form = AuthenticationForm(request.POST or None) if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user: # login(request, user) print("next is {}".format(request.GET.get('next'))) return redirect(user_edit, user.id) else: return redirect(user_login) return render(request, 'user_login.html', {'form': login_form}) @login_required(login_url='/user/login/') def user_edit(request, user_id): print(request, request.user) print("next is {}".format(request.GET.get('next'))) return render(request, 'user_edit.html', {'userid': user_id, 'user': request.user}) -
Celery very strange error, when calling another method
I call the Celery tasks with two arguments: @app.task my_task.delay(path, company_id) In task I call another method, an utility: @app.task def my_add_task(path, company_id): crop_image(path) the utility: def crop_image(path): image = Image.open(path) image_clone = image.copy(image) image_clone.thumbnail(100, 100) I get the following error: File "...tasks.py", line 15, in my_add_task crop_image(path) File "...utils.py", line 29, in crop_image image_clone = image.copy(image) TypeError: copy() takes 1 positional argument but 2 were given If I remove the company_id from the task everything works, so no 2 arguments now passed to crop_image my_task.delay(path) If I remove crop_image, and return the arguments no issue with them are ok I used celery purge do be sure no message are left -
How can I set a nginx index page for the domain name using Django?
I am using Django and nginx to make a web site.(Plus, uWSGI, and AWS EC2...) I already set nginx for IPv4 domain(http://123.45.67.89), so I can get to the correct index page. But I am not sure why I cannot do it for domain name(http://example.com)! I can just access "defalut page"(Welcome to nginx!) for nginx. Could you help me to do for a domain name? My Django project file(root) is /home/ubuntu/proj/mysite My index page is in /home/ubuntu/proj/mysite/taxi/templates/taxi/index.html I've set all in AWS Route 53. Following is my /etc/nginx/sites-enabled/mysite server { listen 80; server_name 123.45.67.89; #example #access_log /var/log/nginx/log/mysite.access.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/proj/mysite; } location / { root /home/ubuntu/proj/mysite; index /taxi/templates/taxi/index.html; #location of index page include /home/ubuntu/proj/mysite/uwsgi_params; uwsgi_pass unix:/run/uwsgi/mysite.sock; } } I don't know what I show you more to help me... Actually I am not sure whether it is a problem in nginx or not. -
Django IntegrityError while updating a record
I have a model with double columns as primary key. I do a filter on it and get the records I want, change a field and save it. As I know save will update the record and does not create a new instance of the model in db. so It should be all okay but I'm stuck with an integrityError Duplicate entry '10-2' for key 'PRIMARY' when I try to save the record Here is the code snippet: for anal in analysis: anal.analysisresult_path = some_string anal.save() #this line is where the error occurs And here is my model: class AnalysisResult(models.Model): analysisresult_path = models.CharField(db_column='analysisResult_path', max_length=255, blank=True, null=True) # Field name made lowercase. detectionresult_path = models.CharField(db_column='detectionResult_path', max_length=255, blank=True, null=True) # Field name made lowercase. targetcode = models.ForeignKey('TagetCode', models.DO_NOTHING, db_column='targetCode_id') # Field name made lowercase. request = models.ForeignKey('Request', models.DO_NOTHING, primary_key=True) class Meta: managed = False db_table = 'analysis_result' unique_together = (('request', 'targetcode'),)