Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Celery Beat Schduler sends next task with current one
I have trouble configuring Celery Beat to reliably send tasks at the scheduled time. It sometimes sends the next scheduled task at the same time than the current one, which then messes the whole schedule. Here is the 4 tasks I need to run, configured in celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oust.settings.local') app = Celery('oust') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.timezone='Europe/Zurich' app.conf.beat_schedule = { 'Send pickup reminders': { 'task': 'send_pickup_reminders', 'schedule': crontab(hour=17, minute=0), }, 'Decrease pickup counters': { 'task': 'decrease_pickup_counters', 'schedule': crontab(hour=23, minute=55), }, 'Update all pickups': { 'task': 'update_all_pickups', 'schedule': crontab(hour=2, minute=0), }, 'Generate new invoices': { 'task': 'generate_new_invoices', 'schedule': crontab(hour=0, minute=15), }, } And here is an example of a task sent with the previous one : Apr 07 19:00:00 oust-prod app/beat.1: [2018-04-08 04:00:00,010: INFO/MainProcess] Scheduler: Sending due task celery.backend_cleanup (celery.backend_cleanup) Apr 07 19:00:00 oust-prod app/worker.1: [2018-04-08 04:00:00,017: INFO/MainProcess] Received task: celery.backend_cleanup[d3d30f13-0244-4582-8944-80fc56ae7b94] Apr 07 19:00:00 oust-prod app/worker.1: [2018-04-08 04:00:00,022: DEBUG/MainProcess] Task accepted: celery.backend_cleanup[d3d30f13-0244-4582-8944-80fc56ae7b94] pid:9 Apr 07 19:00:00 oust-prod app/worker.1: [2018-04-08 04:00:00,029: INFO/MainProcess] Received task: send_pickup_reminders[e01ea890-86b2-4192-9238-0ee358e2ca1b] Apr 07 19:00:00 oust-prod app/worker.1: [2018-04-08 04:00:00,080: INFO/ForkPoolWorker-1] Task celery.backend_cleanup[d3d30f13-0244-4582-8944-80fc56ae7b94] succeeded in … -
how to use django-storages for media storage
I am using django-storages to serve media files on Dropbox. But I cannot get it working. I'v installed dropbox and django-storages, and created an app with permission type:app folder, then added related settings. Here's my settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' DEBUG = False INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', 'website', 'storages', ) # for dropbox DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = 'my_generated_token_from_dropbox' DROPBOX_ROOT_PATH = 'media' MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) to be able to upload the media files to Dropbox (and reading them) what has to be changed in the settings code? Thanks -
Connect nested models django rest framework API serializer
I want to achieve this: a API to get all products for a category. Models.py class Category(models.Model): main_category = models.CharField(max_length=200, default = '') def __str__(self): return '%s' % (self.main_category) class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) sub_category = models.CharField(max_length=200, default = '') def __str__(self): return '%s' % (self.sub_category) class Products(models.Model): sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE) product_name = models.CharField(max_length=200, default = '') def __str__(self): return '%s' % (self.product_name) Views.py class ProductCategoryFilter(django_filters.FilterSet): category = django_filters.CharFilter(name="category__main_category") class Meta: model = Products fields = ['category'] class ProductCategoryListAPIView(ListAPIView): queryset = Products.objects.all() serializer_class = ProductCategorySerializer filter_class = ProductCategoryFilter Serializers.py class ProductCategorySerializer(ModelSerializer): #category_name = serializers.CharField(source='category.main_category') category_name = CategorySerializer(source='category_set') class Meta: model = Products fields = [ 'category_name', 'product_name', ] I get the error : AttributeError at /api/productcategories/ Got AttributeError when attempting to get a value for field category_name on serializer ProductCategorySerializer. The serializer field might be named incorrectly and not match any attribute or key on the Products instance. Original exception text was: 'Products' object has no attribute 'category'. And I want the output like this: [ { "category_name": "main category 1", "product_name": "product 1" }, { "category_name": "main category 1", "product_name": "product 2" },.......... OR output like this : [ { "category_name": "main category 1" :{ "product 1", … -
Django variables in <script> tag
I am trying to assign True or False to a javascript variable based on the value of a django template variable. My django template variable has many states(added,created,submitted and some more). I would like to give the value true to javascript variable, if the django variable has a state of submitted(enumerated as 5). I tried var submitted = {{variable.state == 5|yesno:"true,false" }} but i get Could not parse some characters: question.status| == 5||yesno:"true,false" Thanks for any help! -
django to snowflake connection and running ORM queries
I ma looking to shift out of Postgres to SnowFlake as some of my features requires run time analysis which is pretty faster in SnowFlake. I could only get the Python connector API for Snowflake which would require to create raw queries instead of Djago ORM queries. Is there anyway, we can connect to Snowflake using Django and execute the same Django ORM queries on Snowflake. I saw this old post How to query this (snow flake) data schema in django But couldn't find as to how can we set up django connection with the snowflake. -
Django performance in raw sql sum query vs using loops
I know in general it's good practice to rely on your database for actions like getting sum of records. However here's a special situation: I'm using raw sql with django and I want to get a list of records first, let's say I want a list of books and their prices and their discount percents, after that I want to have the sum of prices and the sum discount (price * discount price for each book). for example : one way to do this is to use the SUM() function of SQL but since I already have the records why not just use a for loop to calculate that? I know database is supposed to be faster but it takes some time for Django to connect to the database and the number of books are not that much (around 5). can someone help me, which solution is better? any help appreciated and thanks in advance. -
Group queryset of content type model by related objects
I sthere a way in django to group a model using content types for generic relations by the generic relation object? More explicitly what I mean is this.... Lets say I have a Tag class class Tag(models.Model): content_type = ... object_id = ... .... and on other models I'm using this model througha generic relation like so: class ModelA(models.Model): tags = GenericRelation(Tag) .... Whenever I query the Tag model I want the queryset to be group by the tags for each related object. So, grouped by ModelA's tags, ModelB's tags, etcetera. -
Django-MPTT - confusion using template blocks
I have a blog project in django, and am trying to make use of MPTT to create a list of child categories. The parent category at the moment is just "Travelling", with one child "Vietnam", except I have a filter in my views to just show the child (my aim is to use MPTT to create a nav bar with child.category drop-downs, but for now I just want to display them on my page). Views.py def getCategories(request): allcategories = Category.objects.all() childCats = Category.objects.filter(children__isnull=True) context = { 'allcategories': allcategories, 'childCats':childCats, } return render(request, 'categories/getCategories.html', context) getCategories.html {% extends "posts/base.html" %} {% load static %} {% load mptt_tags %} {% block category_list %} <ul> {% recursetree childCats %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> {% endblock %} base.html <!DOCTYPE html> {% load static %} {% load mptt_tags %} <html> <body id="content" class="sans"> <div class="flex-wrap justify-end w-full p-6 m-auto border"> {% block category_list %} {% endblock %} </div> <div class="flex-wrap justify-end w-full p-6 m-auto border"> {% block content %} {% endblock %} </div> </body> </html> urls.py from django.conf.urls import url from . import views from django.views.generic.base … -
IntegrityError NOT NULL constraint failed
I'm building a simple blog app using Django. I want to realize the function of adding a new blog using form. Some problems occurs. Here is my models.py from django.db import models from django.utils import timezone from django.template.defaultfilters import slugify from django.contrib.auth.models import User class Blog(models.Model): title=models.CharField(max_length=60) content=models.TextField() author=models.ForeignKey('auth.User',on_delete=models.CASCADE,) date=models.DateTimeField(default=timezone.now) slug=models.SlugField(null=True,unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Blog, self).save(*args, **kwargs) def __str__(self): return self.title class UserProfile(models.Model): user=models.OneToOneField(User) website=models.URLField(blank=True) def __str__(self): return self.user.username forms.py from django.template.defaultfilters import slugify from blog.models import UserProfile from django.contrib.auth.models import User class BlogForm(forms.ModelForm): title=forms.CharField(max_length=60, help_text="blog title") content=forms.CharField(help_text="blog content") author=forms.CharField(help_text="blog author") date=forms.DateTimeField(help_text="blog date") class Meta: model=Blog fields=('title',) class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model=User fields = ('username','email','password') class UserProfileForm(forms.ModelForm): class Meta: model=UserProfile fields=('website',) the add_blog method in views.py def add_blog(request): form=BlogForm() if request.method =='POST': form=BlogForm(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: print(form.errors) return render(request, 'add_blog.html',{'form':form}) When I want to add a new blog in my webpage, I can't input the record. It shows me IntegrityError at /add_blog/ NOT NULL constraint failed: blog_blog.author_id Could anybody help me fix this problem? Thanks a lot! -
Django: Requiring Multiple Logins for same website
I have just deployed my django project on dogitalocean (nginx/ubuntu 16.04) server. In Allowed hosts I added ['.example.com', 'IP'] In the DNS records of my digitalocean droplet I added two A type records one is pointing example.com to the IP, & the second is pointing www.example.com to the same IP. Problem is that I visited the site as example.com & logged in as a normal user, & then I opened a new tab (still logged in at example.com) & visited site using www as www.example.com & i'm not logged in there. Why i need to log in again & how can we fix this issue? -
Contiuous updating Django for standalone app
I am new to Django and I am having a lot of trouble with a certain concept. I see many questions about this but they are usually about much more complicated applications. I am trying to build an app that will be used on a single computer and only as a stand alone non web app. I am just using html for the user interface. I would like to continually update a value by rerunning the get_context_data and have it appear on the website as the newly produced value. I understand that solutions such as AJAX exist, but the tutorials available are for seemingly much more complex situations. To help me unerstand, lets say: Which I add to the index page as follows: I would like to update that random number at regular intervals. I could just refresh the page but this would cause the side menu to go back to its default extended state at each page refresh which I do not want. Can someone provide me an example of the simplest (least dependencies possible) way to implement such a solution. -
Is there a cleaner way to write this SCSS code?
I'm building a Saleor Site and I'm relatively new to Django and SASS. I'm currently making my own styling rules in my SCSS files where there's some duplicated code and I feel like there's probably a way of reducing the amount of that duplicated code. Couldn't find any style guides in regards to SCSS. Can I get some suggestions on a better way of doing this code? .p { &-around { &_none { padding: $none; } &_x-small { padding: $x-small; } &_small { padding: $small; } &_medium { padding: $medium; } &_large { padding: $large; } &_x-large { padding: $x-large; } } &-top { /* only real difference is just "padding-top" instead of "padding" */ &_none { padding-top: $none; } &_x-small { padding-top: $x-small; } &_small { padding-top: $small; } &_medium { padding-top: $medium; } &_large { padding-top: $large; } &_x-large { padding-top: $x-large; } } /* There's more with right, bottom, vertical, horizontal padding as well */ } All input is welcome. -
Docker compose errors using volumes
Here's the deal: I want to create an image based on python:latest, for django development. I want to create the django project INSIDE THE CONTAINER and make it reflect on a host folder, via docker volumes. I want to use the python interpreter from the container for development. This way, I can have only my Dockerfile, docker-compose.yml and requirements.txt on my project folder, not depending on Python, virtualenvs or anything like that on my host. Here's my Dockerfile: FROM python:latest ARG requirements=requirements/production.txt COPY ./app /app WORKDIR /app RUN pip install --upgrade pip && \ pip install --no-cache-dir -r $requirements && \ django-admin startproject myproject . EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] And here's my docker-compose.yml: version: '3' services: web: build: context: . args: requirements: requirements/development.txt networks: - main depends_on: - postgres environment: - PYTHONUNBUFFERED=1 ports: - "8000:8000" volumes: - "./app:/app:rw" postgres: image: postgres:latest networks: - main ports: - "5432:5432" environment: - POSTGRES_PASSWORD=123 volumes: - ./data:/var/lib/postgresql/data networks: main: The main issue are the volumes in web. If I build the image via docker build -t somename:sometag . the build works fine. If I run docker run -it my_image bash it shows me all the files created inside /app. But if … -
FormSet Not Saving Image or validating
When I enter info into my formset, the images gets erased and I'm not able to advance to the next page. No errors appear on the page. Essentially, the form data isn't passing "is_valid". I'm pretty certain that there is something wrong in my view.py. Models.py class Testimonial(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) image = VersatileImageField('image_testimonial', upload_to=upload_location, validators=[file_size], null=True, blank=True) message = models.CharField(max_length=300, default='', null=True, blank=True) name = models.CharField(max_length=100, default='', null=True, blank=True) city = models.CharField(max_length=100, default='', null=True, blank=True) state = models.CharField(max_length=100, default='', null=True, blank=True) def __str__(self): return self.author.username forms.py class TestimonialForm (forms.ModelForm): class Meta: model = Testimonial fields = ('image', 'message', 'name', 'city', 'state',) views.py @login_required(login_url="/accounts/login/") def testimonials(request): TestimonialFormSet = modelformset_factory(Testimonial, form=TestimonialForm, extra=3) if request.method == 'POST': formset = TestimonialFormSet(request.POST or None, request.FILES or None) if formset.is_valid(): instances = formset.save(commit=False) for instance in instances: #for instance in instances.cleaned_data: instance.author = request.user fix_orientation(instance.image) instance.save() return redirect('/accounts/profile/') else: args = {'formset': formset} return render(request, 'accounts/page6.html', args) else: formset = TestimonialFormSet(queryset=Testimonial.objects.filter(author=request.user)) return render(request, 'accounts/page6.html', {'formset': formset}) -
Django: object creation in atomic transaction
I have a simple Task model: class Task(models.Model): name = models.CharField(max_length=255) order = models.IntegerField(db_index=True) And a simple task_create view: def task_create(request): name = request.POST.get('name') order = request.POST.get('order') Task.objects.filter(order__gte=order).update(order=F('order') + 1) new_task = Task.objects.create(name=name, order=order) return HttpResponse(new_task.id) View shifts existing tasks that goes after newly created by + 1, then creates a new one. And there are lots of users of this method, and I suppose something will go wrong one day with ordering because update and create definitely should be performed together. So, I just want to be shure, will it be enough to avoid any data corruptions: from django.db import transaction def task_create(request): name = request.POST.get('name') order = request.POST.get('order') with transaction.atomic(): Task.objects.select_for_update().filter(order__gte=order).update(order=F('order') + 1) new_task = Task.objects.create(name=name, order=order) return HttpResponse(new_task.id) Or something more should be done, for example, task creation should be implemented in a different way? Thx -
Patient user can be Responsible from himself - Django Admin
First of all I would like to say that I am extremely new to Django and Python. I am writing an application using Django 2.0. I have two inheritances to the user: the patient and responsible. A patient needs a user to exist and a responsible needs a patient to exist. A responsible may have several patients but one patient may only have one responsible. However I am having the following problem: A patient can not be responsible for himself and currently this happens. How can I stop this from happening? patient model: class Patient(models.Model): user = models.OneToOneField(User, related_name='patient', on_delete=models.CASCADE, unique=True) (...) responsible model: class Responsible(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, limit_choices_to=Q(patient=None)) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) As you can see I'm using the "limit_choices_to" but it causes all users who are patients are not listed in the time I create a new responsible. -
Query Django ORM with foreign key fields
I am having issues with using Django ORM queries in order to retrieve specific information. I have three models all linked by foreign keys, these are Hosts, Groups and Organisations. So each host belong to a group and these groups belong to an organisation. I need to get the query set of all hosts that belong to a specific organisation named 'Y' for example. Below are my model.py, can anybody help me to formulate a query set that will achieve this? or point me in the correct direction to figure this out? Hosts class Host(models.Model): host_name = models.CharField(max_length=120, blank=False, unique=True) url = models.CharField(max_length=120, blank=False, unique=True) group = models.ForeignKey(Group, on_delete=models.CASCADE) slug = models.SlugField(blank=True, null=True) def __str__(self): return self.host_name Groups class Group(models.Model): org_name = models.ForeignKey(Organization, on_delete=models.CASCADE) group_name = models.CharField(max_length=120, blank=False, unique=True) def __str__(self): return self.group_name Organizations class Organization(models.Model): org_name = models.CharField(max_length=120, blank=False, unique=True) org_code = models.CharField(max_length=120, blank=False, unique=True, default=GenerateOrganozationCode) def __str__(self): return self.org_name -
difference between using super() and super(ViewName,self)
I have been using in generic views (CBVs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) but I've noticed that people here do: context = super(ClassViewName,self).get_context_data(**kwargs) is there is a difference ? -
variables de entorno en Windows 8 para django?
acabo de instalar lo que es django 2.0.4 en su ultima version y tengo un problema al querer crear un nuevo proyecto, al hacer el comando django-admin.py startproyect myproyect al principio me aparecia un error de que no existia el archivo django-admin y me abria una ventana donde tenia que selecionar algun paquete para abrir el archivo, probe con seleccionar el archivo python para poder ejecutar el comando, pero no me resulto, y ahora me aparece esto... esta es la imagen -
How to create a package of models in Django
Having a quite large models.py file (which contains several models), I'm trying to refactor, with one model per file. I'm therefore trying to create a models package, with the following structure: app/models/__init__.py app/models/first_model.py app/models/second_model.py Unfortunately, I cannot get Django lazy reference mechanism to work well, i.e.: first_model = models.ForeignKey('app.FirstModel') returns the error that Django cannot find the model. Any idea? Thanks! -
uploading and saving base64 image data to a Django image field in django rest framework
I'm having trouble saving base64 image data to a django image field, this is what i have tried: so basically i receive the base64 image data from the front end, using axios POST request. then handle the image data in my django rest framework api View. I have tried two variations: 1) writing the decoded base64 to a TemporaryFile, then passing it to the imageField. 2) opening the TemporaryFile using PIL.Image.open(img_temp) and then converting the PIL.Image to a InMemoryUploadedFile and passing that to the imageField. However in both cases i get an error: image : ["Upload a valid image. The file you uploaded was either not an image or a corrupted image."] I'm not quite sure why i get this error because when i used the img.show(), the image came out fine. Django rest framework base64_data = request.data['image_data'][22:] decode_image = base64.b64decode(base64_data) img_temp = TemporaryFile() img_temp.write(decode_image) img_temp.flush() img = PIL.Image.open(img_temp) img_format = '.' + img.format img.show() image_io = BytesIO() img.save(image_io, format=img.format) file = InMemoryUploadedFile ( image_io, None, 'photo' + img_format, 'image/' + img.format, sys.getsizeof(image_io), None, ) img.close() data = { 'image': File(img_temp) # I have tried passing File(img_tem) and "file" into the image field } serializer = ListSerializer(data=data, context={'request': request}) if … -
Changing default file upload input
I'd like to add the following attribute to the tag on the django file upload form as part of a progress bar implementation: onchange="uploadFile()" Do you know how I would be able to modify the default file upload input with this assignment? -
How to deploy a Django production server on IBM Cloud?
I want to know how to deploy a Django production server on IBM Cloud. Right now I have a Cloud Foundry Python app running without problems. But I'm using python manage.py runserver to start the app on the cloud. There is a way to run the app without using the django server? Like, how we do running that kind of apps using Apache o Nginx web servers. -
Django/Python: How to change filename when saving file using models.FileField?
I found this example to upload a file using FileField and it works great. https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html Problem is that it saves the original filename of the file being uploaded. I don't want that. I can change the filename within models.py by overriding the save function (see below). For the life of me, I cannot figure out how to pass a filename in when I execute form.save() from views.py. I need to know the filename for another process. I thought about even returning a filename from the models.py save function. I'm a bit of a noob so forgive any missing details. I've searched this site and read loads of documentation, but I'm missing something. Any advice would be appreciated. Forms.py class DocumentForm(forms.ModelForm): message = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 50})) class Meta: model = Document fields = ('description', 'document', ) Models.py class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='atlasapp/documents/') uploaded_at = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): randomNum = random.randint(10000,90000) new_name = str(randomNum) + ".txt" self.document.name = new_name super(Document, self).save(*args, **kwargs) Views.py def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('model_form_upload') else: form = DocumentForm() return render(request, 'model_form_upload.html', {'form': form}) -
Slice a string and store it as list in django python inside HTML file
I am sending a variable names = "['name1', 'name2', 'name3']" as String to an HTML file from my method in views.py along with other information. When I tried to split the string names with names.split() as: {% for name in names.split(',') %} {{ name }} {% endfor %} then I am facing this TemplateSyntaxError Could not parse the remainder: '(',')' from 'share.share_per_person.split(',')' When I tried to print the string as {{ for name }} then output is ['name1', 'name2', 'name3'] I want to display individual names on screen. Kindly provide a solution