Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get the User Id Class Based View
How to get the Id of the User logged in a Class Based View ? Here is my CBW class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' context = 'activate' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['activate'] = 'Polls' return context def get_queryset(self): """Return the last five published questions.""" return Question.objects.exclude(panel__user='???', panel__valid=False) .order_by('-pub_date')[:5] -
Using Django (Mongo ORM) with CosmosDB?
I am currently trying to use djongo with a CosmosDB database as CosmosDB integrate the MongoDB API. I enabled both 'Aggregation Pipeline' and '3.4 wire protocol' as Djongo require MongoDB 3.4 to work. With this setup, i cannot pass the initial django migration. I did not have any problem with a local MongoDB instance. Here is djongo output when running python manage.py migrate: djongo.sql2mongo.SQLDecodeError: FAILED SQL: CREATE TABLE "django_migrations" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "app" char NOT NULL, "name" char NOT NULL, "applied" datetime NOT NULL) Pymongo error: OrderedDict([('_t', 'OKMongoResponse'), ('ok', 0), ('code', 48), ('errmsg', "a collection 'iot_data.__schema__' already exists"), ('$err', "a collection 'iot_data.__schema__' already exists")]) I can see in the data explorer of CosmosDB that two collections has been created: __schema__ and django_migrations but django_migrations is empty. I have no previous experience with no-sql so maybe I am misunderstanding something. I don't know if anyone already try to use Djongo with a CosmosDB database but any help would be appreciated :) -
Django request.session value is missing
I working on two views where view1 will generate and set a string code (Eg: ABCDEF) to the session and view2 which will validate input by the user with code stored in session. class CodeView(View): def get(self, request): code = generate_code() request.session['code'] = code ### return response class SubmitView(View): def post(self, request): code = request.session.get('code') #### Do stuffs It seems I am unable to get the code from request.session. Anyone has any clue? I have already set 'django.contrib.sessions.middleware.SessionMiddleware', and 'django.contrib.sessions' in settings.py -
Django : custom management command not registered
I'm trying to build some custom commands for one of my Django app. I followed the documentation and put the code of my command inside a file, with this folder structure : |--myapp |--management |--commands |--__init__.py |--index.py |--__init__.py |--__init__.py |--apps.py |--... I need to have an apps.py file because I'm using signals in this app. Thus, my init.py file in myapp folder is: default_app_config = 'myapp.apps.MyAppConfig' and the apps.py file is: from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' def ready(self): import myapp.signals Then, once I run the server, I try to call my custom command, but it is not registered. I tried to call python manage.py and the command was not present. After that, I tried to do the same, but I only changed my init.py file by making it empty. Thus, my app use the default AppConfig. And it worked, my command was available with manage.py. But I can't use signals anymore. So, my question is, how can register custom commands inside an app if I'm not using the default app config but a custom one? Thanks -
Count of many to many and optimize query
I have a Word model it has a many to many field to Phrase model I am passing my words to frontend in json format fronend like this: words_json = [] words = Word.objects.filter(....filter_by_some_params) for word in words: single_word_json = {} single_word_json['id'] = word.id single_word_json['name'] = word.name single_word_json['count'] = len(word.phrases.all()) words_json.appen(word_json) return words_json I feeel like this is not effective and doesn't scale (I will have up to 10k words and phrases, so what do I do? -
Calling django view from AJAX request (parsing celery task_id)
I'm trying to output data from a celery task into a separate window. I'm a novice to JavaScript and AJAX, and this is where my current issue lies. After a view is executed, the celery task is initiated and the next html page (success.html) is rendered: success.html {% block content %} <body> {% if task_id %} <h1>task_id has been called: {{ task_id }}</h1> <script src="{% static 'MyAPP/bootstrap/js/task_output_retrieval.js' %}"></script> <script type='text/javascript'> task_state("{{ task_id }}"); </script> <script src="{% static 'MyAPP/bootstrap/js/update-hello-user.js' %}"></script> <script type='text/javascript'> second(); </script> <h1> END </h1> {% endif %} </body> {% endblock content %} I know the JavaScript is called, because a window is at least opened. Here is the .js: task_output_retrieval.js function task_state (task_id) { var taskID = task_id; var newWin = window.open('', 'new window', 'width=200, height=100'); $.ajax({ url: '{% url validate_task_state %}', data: {'taskID':taskID}, method: 'POST', dataType : "json", success: function(data){ $(newWin.document.body).html(data); newWin.document.write(data); newWin.document.close(); newWin.focus(); newWin.print(); newWin.close(); }, error: function (){ alert('An error occured'); } }); } task_state(task_id); And the url.py: url(r'^ajax/task_state/$', task_state, name='validate_task_state'), # for ajax And the view: admin_scripts.py def task_state(request): print ("You reached the task_state function") data = 'Fail' task_id = request.GET.get('task_id') #task_id = request.session['task_id'] try: async_result = AsyncResult(task_id) except KeyError: ret = {'error':'No optimisation … -
Django import export add on existing admin
I am trying to use django import-export UI admin part. I can make it work in vanilla stage but when I want to implement it to admin I already have I get problems. If we go with this example here https://django-import-export.readthedocs.io/en/latest/getting_started.html#admin-integration I am adding class BookAdmin(ImportExportModelAdmin): resource_class = BookResource and then I need to register that like admin.site.register(Book, BookAdmin) so it shows up, problem is that I already have this line above as I have a BookAdmin where I change how regular admin looks like class BookAdmin(admin.ModelAdmin): So I need to try to add import/export class with some different name like class BookAdminExport, but then I cant register it to admin anymore as if I try admin.site.register(Book, BookAdminExport) it says "The model book is already registered" so I dont have any ideas what to do next? -
Can Django set permissions on apps instead of models
I want to have authority control over my project, some user can see some app's entry while others can't. I want to set permissions on apps instead of models, i have searched but only find how set permissions on models, so i want to know how to set permissions on apps. -
How to make new accounts(object) in Django?
#views.py def signup(request): if request.method == "POST": form = ProfileForm(request.POST) if form.is_valid(): *new_user = Profile.objects.create_user(**form.cleaned_data)* login(request, new_user) return HttpResponse('signup success.') else: form = ProfileForm() return render(request, 'registration/profile.html', {'form': form}) I want to make new accouont(object) so, I want to use User.objects.create_user method #models.py class Profile(models.Model): studentNumber = models.CharField(max_length=30, blank=True) name = models.CharField(max_length=10, blank=True) major = models.CharField(max_length=20, blank=True) email = models.CharField(max_length=30, blank=True) password = models.CharField(max_length=15, blank=True) phoneNumber = models.CharField(max_length=15, blank=True) github = models.CharField(max_length=150, blank=True) sns = models.CharField(max_length=150, blank=True) it is my model! How can I save my model to DB? -
Why use get_context_data (self,**kwargs) and super ()
In class based view i simply use get_context_data as a function but why class CBV (TemplateView): def get_context_data(self,**kwargs): context = super ().get_context_data (**kwargs) -
How to route tasks to different queues in Celery
I am using the following stack: Python 3.6 Celery v4.2.1 (Broker: RabbitMQ v3.6.0) Django v2.0.4. According Celery's documentation, running scheduled tasks on different queues should be as easy as defining the corresponding queues for the tasks on CELERY_ROUTES, nonetheless all tasks seem to be executed on Celery's default queue. This is the configuration on my_app/settings.py: CELERY_BROKER_URL = "amqp://guest:guest@localhost:5672//" CELERY_ROUTES = { 'app1.tasks.*': {'queue': 'queue1'}, 'app2.tasks.*': {'queue': 'queue2'}, } CELERY_BEAT_SCHEDULE = { 'app1_test': { 'task': 'app1.tasks.app1_test', 'schedule': 15, }, 'app2_test': { 'task': 'app2.tasks.app2_test', 'schedule': 15, }, } The tasks are just simple scripts for testing routing: File app1/tasks.py: from my_app.celery import app import time @app.task() def app1_test(): print('I am app1_test task!') time.sleep(10) File app2/tasks.py: from my_app.celery import app import time @app.task() def app2_test(): print('I am app2_test task!') time.sleep(10) When I run Celery with all the required queues: celery -A my_app worker -B -l info -Q celery,queue1,queue2 RabbitMQ will show that only the default queue "celery" is running the tasks: sudo rabbitmqctl list_queues # Tasks executed by each queue: # - celery@Network.local.celery.pidbox 0 # - celeryev.209274c5-317b-46e4-9e2e-a493612cfb5e 0 # - celery 2 # - queue1 0 # - queue2 0 Does somebody know how to fix this unexpected behavior? Regards, -
Cached object is reused in Django
I am working on a Django project and have some instances of a class. I cached instance A with key 'A', and create a new instance B in another request. The thing is instance B now has data of instance A. When I change instance B's data and get instance 'A' from cache, instance A's data changes too. I guess this has something to do with python's reuse mechanism. Anyone know how to fix this problem? -
How to use widgets from django snippet?
I want to use this widget in my code https://djangosnippets.org/snippets/10522/ My question is where to paste this code? and how to use it in my forms? My code requires me to select only month and date from the user using a drop-down menu. The date is set to '1' by default. I found this widget very helpful but I am unable to figure out how to use it in my code -
Handle multiple Django form in a template
I am passing two forms to a template, only one of these forms is compulsory while the other one is optional. Everything is fine if the user chooses to fill-out both forms, the problem comes when the user only fill-out the compulsory form and leaves the optional one, in this case, when the user submits the form, Django will prompt the user to fill the form fields of the optional form even though the user may not be interested in it. "bankingDetailsForm" is the the optional for below while "companyProfileForm" is the compulsory one. #userRegForm = CustomUserForm() companyProfileForm = CompanyProfileForm() bankingDetailsForm = BankingDetailsForm() args = {#'userRegForm': userRegForm, 'package': packageOption, 'billing_cycle': b_cycle, 'companyProfileForm': companyProfileForm, 'bankingDetailsForm': bankingDetailsForm } args.update(csrf(request)) return render(request, 'user_account/subscribe.html', args) How can I force the "bankingDetailsForm" form to be optional on submit? -
iOS POST to nginx/Django is interpreted as GET
I have an iOS app which makes a POST request using Siesta as such: MyService.shared.myRequest.request(.post, json: params) .onSuccess { (entity) in completion(true) } .onFailure { (error) in completion(false) } When I make this particular request (just this one request) to nginx on a remote server, something interprets it as a GET request, which is not allowed, so I get back 405. The application on nginx is written in Django and everything works perfectly fine when I run it using the Django development server. I'm completely lost for ideas, what can I do at this point? -
How to get data from ManaToManyField from forms into Django Views?
models.py class Posts(models.Model): """model for CreatePost""" author = models.CharField(max_length=100, null=False, blank=False) blog_title = models.CharField(max_length=100, null=False, blank=False) sub_catagory = models.ManyToManyField('SubCatagory') post_cover_image = models.ImageField(upload_to='post_cover_images', null=False, blank=False) post_discription = HTMLField(max_length=5000, null=False, blank=False, help_text='Enter the detailed post in max. 5000 characters') date_published = models.DateField(null=False, blank=False) class Catagory(models.Model): """model for Catagory""" name = models.CharField(max_length=150, help_text='Enter a ctagory for blogpost') class SubCatagory(models.Model): """model for subcatagories""" catagory = models.ForeignKey('Catagory', on_delete=models.CASCADE) sub_catagory_name = models.CharField(max_length=150, help_text='Enter subcatagory') forms.py class PostCreationForm(forms.ModelForm): class Meta: model = Posts fields = ('blog_title', 'sub_catagory', 'post_cover_image', 'post_discription') views.py @login_required def createpost(request): if request.method=="POST": PostForm = PostCreationForm(request.POST, request.FILES) if PostForm.is_valid(): postcont = Posts() if request.user.is_authenticated: postcont.blog_title = PostForm.cleaned_data['blog_title'] postcont.post_cover_image = PostForm.cleaned_data['post_cover_image'] postcont.post_discription = PostForm.cleaned_data['post_discription'] postcont.author = request.user.username postcont.sub_catagory = PostForm.cleaned_data['sub_catagory'] postcont.date_published = datetime.date.today() postcont.save() return HttpResponseRedirect(reverse('postcreationsuccessful')) else: return HttpResponseRedirect(reverse('createpost')) else: PostForm = PostCreationForm() return render(request, 'createpost.html', {'PostForm':PostForm}) template {% extends "base_generic.html" %} {% block title %}<title>Create Post</title>{% endblock %} {% block content %} <div class="container-fluid"> <div class="row w-100"> <div class="col-md-3"> </div> <div class="col-md-6 shadow-sm p-3 mb-5 bg-white rounded"> <form method="POST" enctype="multipart/form-data" action="{% url 'createpost' %}">{% csrf_token %} <div class="row"> {% load bootstrap %} <div class="col-md-12"> {{ PostForm.blog_title|bootstrap }} </div> <div class="col-md-12"> {{ PostForm.post_cover_image|bootstrap }} </div> <div class="col-md-12"> {{ PostForm.sub_catagory|bootstrap }} </div> <div class="col-md-12"> {{ PostForm.post_discription }} … -
dict zip key values django template
Pairing of 2 dict values.It works. pair = dict(zip(hide_dict, fp_dict)) context = { 'instance': project, 'user': user, 'pair': pair, } My django html template part,where I am getting error. Exception Type: ValueError Exception Value: Need 2 values to unpack in for loop; got 6. Am I done false the for loop part ? Earlier I tried pairing, I tried separately and it works fine. Now with pairing it shows that the error is in context rendering,but I can't see where. {% for fp_dict.items,hide_dict.items in pair %} {% for key, values in hide_dict.items %} {%if values == 1%} <div style="display:none"> {% elif values == 0 %} <div> {% endif %}{% endfor %} <div class="row"> <div class="col-sm-12"> <div class="panel panel-default"> <div class="panel-body"> <table class="table"> <thead> <tr> <th>FP Items</th> </tr> </thead> <tbody> <tr> {% for key, values in fp_dict.items %} {% for instance in values %} <td></td> <td>{{ instance.FP_Item }}</td> </a> </td> --> </tr> </tbody> </table> </div> </div> </div> </div> </div> {% endfor %} -
Django-ORM: Why is distinct() not working with annotations?
I'm using postgresql: articles = Article.objects.filter(articleinreports__report__in=reports_in_time_range).distinct().annotate( total_views=Case( When(articleinreports__report=last_report, then=(F("articleinreports__ios_views") + F("articleinreports__android_views"))) , default=0, output_field=IntegerField() ) ).order_by('-total_views') Why is distinct() not getting applied and I'm getting two-articles instead of one for each unique article in the database? Removing order_by does not solve (and that creates another problem anyway), only removing both the annotation and the order_by. When I try to do distinct('id'), I get an error that it must match the order_by field, which defeats the purpose of ordering by my desired criteria. -
Django; How should I deal with default image?
I'm working on Django project, which is hosted on AWS elastic beanstalk. And I am wondering how I should deal with default image. I was thinking of storing default image into media folder. But I am wondering how I upload the image into AWS S3. If I store it into static folder, I'm wondering how I can refer to the image after user change the picture. Sorry if my question is confusing. models.py is here. class CustomUser(AbstractUser): objects = CustomUserManager() picture = models.ImageField( upload_to='blog/profile', max_length=255, default='path/to/default-picture.png', ) I mean if I store it into static, I can refer to it. <img src="{% static path %}> But I am wondering how I can swtich to refer to file in media after user change the picture. -
AttributeError: 'module' object has no attribute 'celery' when docker-compose up
I'm trying to start project on Docker. After docker-compose up console gives out: celery_redis_1 | Traceback (most recent call last): celery_redis_1 | File "/usr/local/bin/celery", line 11, in <module> celery_redis_1 | sys.exit(main()) celery_redis_1 | File "/usr/local/lib/python2.7/site-packages/celery/__main__.py", line 16, in main celery_redis_1 | _main() celery_redis_1 | File "/usr/local/lib/python2.7/site-packages/celery/bin/celery.py", line 322, in main celery_redis_1 | cmd.execute_from_commandline(argv) celery_redis_1 | File "/usr/local/lib/python2.7/site-packages/celery/bin/celery.py", line 496, in execute_from_commandline celery_redis_1 | super(CeleryCommand, self).execute_from_commandline(argv))) celery_redis_1 | File "/usr/local/lib/python2.7/site-packages/celery/bin/base.py", line 273, in execute_from_commandline celery_redis_1 | argv = self.setup_app_from_commandline(argv) celery_redis_1 | File "/usr/local/lib/python2.7/site-packages/celery/bin/base.py", line 479, in setup_app_from_commandline celery_redis_1 | self.app = self.find_app(app) celery_redis_1 | File "/usr/local/lib/python2.7/site-packages/celery/bin/base.py", line 501, in find_app celery_redis_1 | return find_app(app, symbol_by_name=self.symbol_by_name) celery_redis_1 | File "/usr/local/lib/python2.7/site-packages/celery/app/utils.py", line 370, in find_app celery_redis_1 | found = sym.celery celery_redis_1 | AttributeError: 'module' object has no attribute 'celery' Does anybody know why the 'celery' attribute cannot be found? Thank you for help. My operation system is macOS High Sierra 10.13.6 My tasks.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals import youtube_dl import requests import json from django.conf import settings from django.core.mail import send_mail from celery import shared_task from youtube_dl import YoutubeDL @shared_task(name='download') def download(url, email): ... My docker-compose.yml: version: "3" services: web: build: context: . dockerfile: Dockerfile ports: - "8080:8080" … -
Does anyone knows if python can use the message group in activemq
Our project use Django and my leader want me to use the message group in activemq, but I did't find how to use it with python, I need your help. -
Django model field unique among all subclasses
I have the following model structure: class A(models.Model): ... class Meta: abstract = True class B(A): ctx_order = models.PositiveIntegerField(blank=False, null=False, default=1) class C(A): ctx_order = models.PositiveIntegerField(blank=False, null=False, default=2) I want to make sure that the ctx_order field is unique among all subclasses that inherit from A. Is there a way to accomplish that or would I have to do the validation myself? -
Differences between Django one-to-one and foreign key relationships at db level?
Is OneToOneField just ForeignKey with unique=True.What is the difference at db level,how about performance? Thanks so much. -
using tablib and django-import-export to import data, getting error with excel, but with csv it's working
At first trying to read excel/csv data to check it before inserting into database, While csv working fine can read data, but xlsx and xlx showing following error UnicodeDecodeError at /academy/add_advisor 'utf-8' codec can't decode byte 0xa1 in position 10: invalid start byte Snippet of my code: from tablib import Dataset this_file = request.FILES['bulk_file'] dataset = Dataset() imported_data = dataset.load(this_file.read().decode("utf-8"),format='xlsx') for data in dataset: print(data[0], data[1], data[2], data[3], data[4]) According to error message error coming from this line imported_data = dataset.load(this_file.read().decode("utf-8"),format='xlsx') The excel file i am trying to import, i downloaded it from google drive excel as xlsx file(microsoft excel). Also downloaded one from onedrive(microsoft) xlsx file still getting same error. Few more ways i have tried with are imported_data = dataset.load(this_file.read().decode("ISO-8859-1"),format='xlsx') imported_data = dataset.load(this_file.read().strip().decode("ISO-8859-1"),format='xlsx') imported_data = dataset.load(this_file.read().strip().decode("CP1252"),format='xlsx') imported_data = dataset.load(this_file.read().strip().decode("windows-1252"),format='xlsx') imported_data = dataset.load(this_file.read().strip().decode("Latin-1"),format='xlsx') But no luck :( Please share if there has any better way i can try :)(: Thank you for read :) -
Django Ajax POST request: Internal server error
Note that I'm a big noob in AJAX, since I started recently. I'm using Django 2.0 and Python. I'm trying to return a list of not compatible options under the form of an array. Here is my model : class Door(models.Model) : image = models.ImageField(upload_to=upload_location) color = models.ForeignKey(Color, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2, default='119.99') not_comp_options = models.ManyToManyField(Option) Here is my js template: $.ajax({ type: "POST", url: "/get_not_compat_options/" + door_id, data: "", dataType: 'json', success: function() { console.log(data.onct) } }) Here is my urls: urlpatterns = [ # Other url patterns path('get_not_compat_options', views.get_not_compat_options, name="get_not_compat_options") ] Here is my views: def get_not_compat_options(request, door_id) : onct = [] door = get_object_or_404(Door, id=door_id) not_compat_options = door.not_comp_options for option in not_comp_options.all() : onct.append(option.name) data.append({"onct": onct}) return JsonResponse(data) Unfortunately, in the browser console, I get an error saying: 500 (Internal Server Error) PS: If that could help, I'm using Nginx and gunicorn for my server.