Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. Import module error. ModuleNotFoundError: No module named 'foo'
This is very simple. I have a new project with these files: in my urls file, how can I import the home.views? I thought this would work: from django.contrib import admin from django.urls import path from website.home import views <--- urlpatterns = [ path('admin/', admin.site.urls), ] But when I runserver o makemigrations or anything I get: ModuleNotFoundError: No module named 'website.home' I am clueless. Plz help. I have included 'home' in INSTALLED APPS -
Can I host Python Django Application on german V-Server (Provider: Strato)
Hello dear Community, I have developed a Python Django project and want to host it on my german V-Server on the provider strato. I don't know if the server provider "strato" makes it possible to run a Django application on it. Therefore the QUESTION, if you can host a Django application on every V-Server? or if it has to be a special provider e.g. DigitalOcean. I am very grateful for any advice! Thank youu :) Best regards, programmerg -
I am getting a date of "598146673" when I use JSONEncoder with a Date type
Title says it all. I don't mind getting the date as "598146673" but I just need to convert it when I receive that on my Django. Ideally, I would like to what format it is or how I can have xcode leave it in "2019-12-15 23:51:13 +0000" -
Django 2.2 Cannot figure out how to authorize user to edit or delete blog post if user created that blog post
So this is the third time I'm asking this question. I don't know how to allow only a user, that created a particular blog post, to edit or delete that post. So this blog is like any other blog. All users can look at all other users blog posts. To create a blog post, a user must be logged in with an account already. Same thing for edit and delete a blog post. However, I don't know how to check to see if a user can edit or delete a blog post based off whether that user was the one that created the blog post or not. I'm typing this question since no one answered my previous questions I posted. below are three files for models, views, and the html for update/edit a blog post. I can figure out the delete once I figure out the edit. I know Django creates add, change, delete permissions automatically. Unfortunately, the change and delete permissions always return false, even if that user is already logged in. I've been stuck on this for days. Like 15+ hours already over three days. blog/models.py from django.db import models from django.conf import settings from django.utils import timezone … -
Best way to add custom SQL to a queryset in Django 2.2.4+?
I'm looking to add the following line of SQL to my django queryset's SQL query. "SET LOCAL enable_nestloop = 'off';" (this line configures my postgres database to behave a certain way, which I need for this specific query I'm running). This line of SQL has nothing to do with the query, so .extra doesn't seem appropriate. https://docs.djangoproject.com/en/2.2/ref/models/querysets/#extra The context I'm in (a django-rest-framework ViewSet w/ a custom filter) requires me to maintain a queryset object. Therefore I can't use .raw either, because it returns a RawSQL object https://docs.djangoproject.com/en/2.2/topics/db/sql/#performing-raw-sql-queries Finally, I cannot write a completely raw cursor.execute command because the query is dynamic and extremely complicated, so a queryset is a must. How do I add this 1 line of SQL to the queryset query? Thank you! -
Django, How to transform from a queryset to json and use a value from a key?
This is my model.py class Ont_Pruebas_Json(models.Model): usuario_id = models.CharField(max_length=12) data = jsonfield.JSONField() def __str__(self): return '{}'.format(self.usuario_id) On data field I am storing this: {u'1': {u'user': u'user1',u'mac': u"'00:00:00:00:00:01'"}, u'2': {u'user': u'user1',u'mac': u"'00:00:00:00:00:01'"}} On my views.py I am passing the query set this way: context['context_json'] = Ont_Pruebas_Json.objects.all() How can pass from the queryset to json format so I can choose for example from 1 the key mac and get the value: 00:00:00:00:00:01. -
How to associate only a subdomain to my Django App on Digital Ocean?
We already have a website called X.com. Now I am building a Django App on a Digital ocean Droplet. I am able to access it using the IP-address. But we want to have it called reporting.X.com for sharing it with our users. On my domain providers, I already added an A record like the below Host- reporting Type - A Content - <ip-address> of digital ocean droplet However I keep getting a 400 error when I try to access reporting.X.com. What should I do? -
Django update template after download completes
I have a function which is called via a user action in my template: <a href="{% url 'channels:download_channel' channel.id %}" onclick="showLoader()"> download_channel is a function that merges audio files (into one file) and initiates a file for download. This can take some time and isn't instantaneous. So I show a spinner. showLoader() is a javascript function that simply shows a spinner to let the user know the process/download is ongoing. My problem is when the download is finished on the server side, I have no way of communicating with the template to hide the spinner I've tried via ajax, but I guess you can't initiate downloads that way (unsafe). This was the ideal solution I was hoping would work. function downloadChannel() { showLoader() $.ajax({ type:'GET', url:'{% url "channels:download_channel" topic.id %}', success:function(json){ console.log('got some success of heah') hideLoader(); location.reload(); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); hideLoader(); // provide a bit more info about the error to the console } }); } I've looked at django channels, but sockets seem like a big setup for such a simple problem. I'm a bit stumped on how to properly approach this problem. Any feedback is greatly appreciated -
Django media files, and horizontal scalabilty
I have recently started working on web development with Django, and I am planning to make a horizontally scalable web app. I would like the web app to allow users of the website to upload/download files/images and media in general. Seems like a lot of tutorials out there, including Django doc's approaches do not support horizontal scalability, as they rely on local storage for saving media. https://docs.djangoproject.com/en/2.2/topics/files/ Something I was wondering I could do is to save those images in the SQL database, but some people I know were quick to point out that this may slow down the database tremendously. And now I am here with the question: What do you think is a good way of solving this issue, where I would like a scalable web app, that supports media upload/download capabilities. Note: I am by no means trying to transfer terabytes of data. This is more of a school project for myself, but I would like to get it right from the get-go. -
Is it possible to run django app on raspberry pi zero w [closed]
As per title, considering no calculations are performed on app side, is it safe to assume a simple django app will work okay? Are there specific system requirements for django, or does it run on anything capable running python? -
Issues with Pipenv on git-bash.exe
OS Info: OS: Windows 10 Version: 1909 Build: 18363.476 Python Info: Python: v3.8.0 Python path: C:\Python\38 Pip: v Pip Path: C:\Python\38\Scripts Terminal: shell: bash.exe (git-bash) version: 2.24.0.2-64-bit Issue: Trying to initiate dependency management running on bash.exe (git-bash) and end up with some issues... $ pipenv shell Warning: Python 2.7 was not found on your system… You can specify specific versions of Python with: $ pipenv --python path\to\python Trying to install another package such as pipenv install django would give me same error. I am not sure what's exactly error was and I cannot find any solution after searching around answers for 2 days. What have I done? I have downloaded python3.8 (Windows x86-64 executable installer for win 64 AMD64/EM64T/x64) from this site https://www.python.org/downloads/release/python-380/. Installed python3.8 following my customized path C:\Python\38 and made sure "Add Python3.8 to PATH" is checked before begin installing. After completed install python in my system, I have installed pipenv following pip install pipenv Installation was success after confirmed with pipfreeze pip freeze astroid==2.3.3 autopep8==1.4.4 certifi==2019.11.28 colorama==0.4.1 isort==4.3.21 lazy-object-proxy==1.4.3 mccabe==0.6.1 pipenv==2018.11.26 pycodestyle==2.5.0 pylint==2.4.3 six==1.13.0 virtualenv==16.7.8 virtualenv-clone==0.5.3 wrapt==1.11.2 and there's pipenv.py inside C:\Python\38\Scripts. What exactly is my issue, and is there a way to resolve it? Thanks in … -
Downsides of using Gunicorn with Django for development
Gunicorn + Django is a typical combo for production environments. Are there any downsides, apart for the added complexity, of using Gunicorn also for development, instead of runserver? -
Como criar um campo personalizado de modelo no django que funcione como uma lista que armazena objetos de uma outra tabela? [closed]
Estou fazendo um crud onde eu tenho uma tabela de empréstimo de livros, e preciso de um campo da model do django que funcione como um array ou lista de objetos para armazenar 1 ou mais livros que serão emprestados. Obs: Livro também é um tabela armazenada no banco de dados. E também se for possível fazer isso utilizando os próprios relacionamentos foreignkey ou manytomanyfield fornecidos pelo Django, se puderem me dar alguns exemplos de como fazer isso. -
Difference between declaring and excluding models when using dumpdata?
I'm having serialization dependency errors when trying to use dumpdata (or tests!) and am trying to diagnose the source of the problem by dumping various combinations of models to see which ones throw errors. When I explicitly declare every model except for two, it works: python manage.py dumpdata app1.ActionItem app1.ActivityLog app1.Aim app1.Bank app1.BenchmarkCategory app1.BenchmarkValue app1.Benchmark app1.Citation app1.City app1.Client app1.ComplaintStage app1.ComplaintSubscription app1.Complaint app1.Contact app1.Country app1.DocumentCategory app1.Document app1.ExplanationCategory app1.Explanation app1.FAQ app1.GoalUpdate app1.Goal app1.Group app1.IAM app1.IFISupport app1.Investment app1.Issue app1.KeyDateCategory app1.KeyDate app1.KeyTerm app1.Language app1.NCP app1.NoteCategory app1.Note app1.OrgType app1.Organization app1.Outcome app1.Region app1.ResearchRequest app1.Sector app1.Source app1.SubGoal app1.SupportItem app1.Tag app1.Team app1.TimePeriod app1.UserProfile app1.Workplan app2 app3 app4 --natural-primary --natural-foreign --output='data_dump.json' -v=3 --indent=4 --traceback But when I try dumpdata by excluding those two models, it throws the same dependency error: python manage.py dumpdata -e=app1.project -e=app1.case --natural-primary --natural-foreign --output='complaint_dump.json' -v=3 --indent=4 --traceback RuntimeError: Can't resolve dependencies for app1.ActionItem, app1.ActivityLog, app2.AnnualEvaluation, app1.Case, app1.Citation, app2.Commitment, app1.Complaint, app1.ComplaintStage, app1.ComplaintSubscription, app1.Contact, app1.Document, app2.Feedback, app1.Goal, app2.Goal, app1.GoalUpdate, app1.Investment, app1.KeyDate, app1.Note, app3.OCR, app1.Project, app2.QuarterlyUpdate, app1.ResearchRequest, app1.Source, app1.SubGoal, app4.Subscription, app1.SupportItem, app3.Survey, app2.Tactic, app1.UserProfile, app1.Workplan in serialized app list. Note that even the excluded models are showing up in the error. Am I running the exclude incorrectly somehow? -
Django 2.2 - checking user permission (perms.blog.change_blogpost) not working
So I've been stuck on this for days, not kidding. I've looked at over 20 different websites, all about Django user permissions. I cannot get the code to work not matter what I do. I've tried EVERYTHING! See below. Here is the code: models.py from django.db import models from django.conf import settings from django.utils import timezone from django.db.models import Q User = settings.AUTH_USER_MODEL class BlogPostQuerySet(models.QuerySet): def published(self): now = timezone.now() return self.filter(publish_date__lte=now) def search(self, query): lookup = ( Q(title__icontains=query) | Q(content__icontains=query) | Q(slug__icontains=query) | Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) | Q(user__username__icontains=query) | Q(user__email__icontains=query) | Q(image__icontains=query) ) return self.filter(lookup) class BlogPostManager(models.Manager): def get_queryset(self): return BlogPostQuerySet(self.model, using=self._db) def published(self): return self.get_queryset().published() def search(self, query=None): if query is None: return self.get_queryset().none() return self.get_queryset().published().search(query) class BlogPost(models.Model): # blogpost_set -> queryset user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) image = models.ImageField(upload_to='image/', blank=True, null=True) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) # Example: "hello world" -> hello-world content = models.TextField(null=True, blank=True) publish_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = BlogPostManager() class Meta: ordering = ['-publish_date','-updated','-timestamp'] def get_absolute_url(self): return f"/blog/{self.slug}" def get_edit_url(self): return f"{self.get_absolute_url()}/edit" def get_delete_url(self): return f"{self.get_absolute_url()}/delete" views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404 from .models import BlogPost from .forms import … -
Accessing an api running in a docker host from a different docker host
I have two docker projects each with their own docker-compose.yml files. One project holds a django api with docker host for that, while the other project is for open edx which running on another docker host. If I try to access my django api from one of these docker containers of the second docker host using docker exec -it edx.devstack.studio curl http://localhost:8000/number/, I get an error curl: (7) Failed to connect to localhost port 8000: Connection refused. I'm by no means a docker expert so there's something I'm probably doing wrong. I tried adding all the docker services in both projects to the same network but it still failed, probably I'm doing it wrong. Any help will be much appreciated. Below are the two docker compose files. Django project docker compose file version: "3" services: db: image: mysql:5.7 container_name: db env_file: - .env ports: - '3307:3307' expose: - '3307' volumes: - my-db:/var/lib/mysql django: build: context: . container_name: web env_file: - .env command: python src/manage.py runserver 0.0.0.0:8000 depends_on: - db ports: - "8000:8000" volumes: - .:/app networks: - okay networks: okay: external: true volumes: my-db: Open edx docker compose file # This file contains all of the services for an edX … -
annotate: whether a given value exists in m2m field
I have a query that retrieve an object like this: { "id": 1, "tags": [1, 2, 3] } I want to check whether a given tag (say, 1) exists in the tags field of the object, and annotate the result of the check as a field of the object: { "id": 1, "tagged": true } This is what I came up with annotate( tagged=Exists( Articles.tag_set.through.objects.filter( article_id=OuterRef("pk"), tag_id=tag.id ) ) ) Since the relation tags is already loaded by the primary query, having a secondary query seems redundant to me. Is there an easier way to structure this query? Something close to the filter syntax tags__contains=tag. -
Getting sqlite3.OperationalError: no such column: REFERRED.id when i'm trying to migrate
I just added new imageField to my Item model. Then run the command makemigrations, after migrate command i started to get "sqlite3.OperationalError: no such column: REFERRED.id". Then i deleted changes and try to migrate and still have the same error. i tried all the same discussions before, but nothing changes. still have the same error. So i can not add any field becouse of this error class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length = 2) label = models.CharField(choices=LABEL_CHOICES, max_length = 1) slug = models.SlugField() description = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('core:''product', kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse('core:''add-to-cart', kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse('core:''remove-from-cart', kwargs={ 'slug': self.slug }) This is traceback: (env) PS C:\Users\User\desktop\dj-projects\django_project_boilerplate> python manage.py migrate Operations to perform: Apply all migrations: account, admin, auth, contenttypes, core, sessions, sites, socialaccount Running migrations: Applying core.0013_auto_20191119_2152...Traceback (most recent call last): File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 381, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such column: REFERRED.id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) … -
Read a Django UploadedFile into a pandas DataFrame
I am attempting to read a .csv file uploaded to Django into a DataFrame. I am following the instructions and the Django REST Framework page for uploading files. When I PUT a .csv file to a defined endpoint I end up with a Django UploadedFile object, in particular, a TemporaryUploadedFile. I am trying to read this object into a pandas Dataframe using read_csv, however, there is additional formatting around the temporary uploaded file. I am wondering how to read the original .csv file that was uploaded. According to the DRF docs, I have assigned: file_obj = request.data['file'] Inside of a Python debugging console, I see: ipdb> file_obj <TemporaryUploadedFile: foobar.csv (multipart/form-data; boundary=--------------------------044608164241682586561733)> Things I've tried so far. With the original file path, I can read it into pandas like this. dataframe = pd.read_csv(open("foobar.csv", "rb")) However, the original file has additional metadata added by Django during the upload process. ipdb> pd.read_csv(open(file_obj.temporary_file_path(), "rb")) *** pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 5, saw 32 If I try to use the UploadedFile.read() method, I run into the following issue. ipdb> dataframe = pd.read_csv(file_obj.read()) *** OSError: Expected file path name or file-like object, got <class 'bytes'> type Thanks! -
DJango - Custom parameters to formset forms
forms.py class InsereIdioma(forms.ModelForm): class Meta: model = Idioma fields = '__all__' exclude = ['usuario'] labels = { 'idioma': 'Idioma', 'fluencia': 'Fluencia', } widgets={ 'idioma': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Idioma'}), 'fluencia': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Fluencia'}) } def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(InsereIdioma, self).__init__(*args, **kwargs) def save(self, commit=True): obj = super(InsereIdioma, self).save(commit=False) obj.usuario = self.user if commit: obj.save() return obj InsereIdiomaFormset = modelformset_factory( Idioma, fields=('idioma', 'fluencia', ), extra=1, widgets={ 'idioma': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Idioma'}), 'fluencia': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Fluencia'}), } ) views.py def cadastro_curriculo(request): if request.method == 'GET': formset = InsereIdiomaFormset(queryset=Idioma.objects.none()) elif request.method == 'POST': formset = InsereIdiomaFormset(request.POST, user=request.user) if formset.is_valid(): for form in formset: if form.cleaned_data.get('idioma'): form.save() return redirect('vagas') return render(request, "personal/curriculo.html", { 'formset': formset, }) How do I pass my custom parameters in my form to the formset so I can use it in my view? I tried to read the documentations but didn't understand as well. https://docs.djangoproject.com/en/2.2/topics/forms/formsets/#passing-custom-parameters-to-formset-forms -
Django PostgreSQL existing database does not exist
I have a table tablename with schema sub in PostgreSQL that definitely exists--it has been created, it has had data added to it, and when I run SELECT * FROM sub.tablename in pgAdmin 4, it returns results without issue. When I try to then access that same table in my Django application, it produces error psycopg2.OperationalError: FATAL: database "main.sub.tablename" does not exist. I attempted making the table name sub.tablename and tablename but it still claims the table does not exist. I am the owner of sub and it is my credentials used to access the table. I have confirmed that the host name and the port are what they should be. I'm at a loss as to how to fix this since, as far as I can tell, this error only shows up when people haven't actually created the table yet or misspell something. Below is my relevant code blurb in settings.py where the table/database info appears. settings.py DATABASES = { 'default': { 'NAME': 'tablename', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '1234', } } Traceback Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File … -
I want to know which <a> Tab was clicked and get the value of that in my View and write a logic with that
Search.py {% block search %} <form action="#" method="post"> <div class="container"> <br> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" name="bankname" type="submit" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Name </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for key , value in data_dict.items %} <a class="dropdown-item" value={{key}} name={{key}} href="{% url 'details' %}">{{ key}} </a> {% endfor %} </div> </div> </form> {%endblock%} the number of items in data_dict is not always same , so some times it has 2 or 3 or even 10 different names which leads to 10 items in the drop down. I need to show details of the name clicked in the drop down in details .html Views.py def bankdetails(request, **kwargs): value1 = None data_dict = request.session.get("data_dict") for key, value in data_dict.items(): key1 = request.GET.get("key") if key1 == key: value1 = value context = {"data_dict" : data_dict , "value1":value1} return render(request , "details.html", context ) i want the value of the tab clicked in the drop-down in my view so i can display the details accordingly from my data_dict -
Django Relations with Models
I try to figure a clever way out for my models. I have two models where i want the Legend to have 4 different skills(Skill Model), but I cant seem to get the fitting model relation for it class Skill(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) title = models.CharField(max_length=100) description = models.CharField(max_length=300) image = models.ImageField(upload_to='skills/', blank=True, null=True) class Legend(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) title = models.CharField(max_length=100) description = models.CharField(max_length=1000) image = models.ImageField(upload_to='legends/%Y/', blank=True, null=True) skill_1 = models.(Skill, on_delete=models.SET_NULL, null=True) skill_2 = models.OneToOneField(Skill, on_delete=models.SET_NULL, null=True) skill_3 = models.OneToOneField(Skill, on_delete=models.SET_NULL, null=True) skill_4 = models.OneToOneField(Skill, on_delete=models.SET_NULL, null=True) The problem is I cant rly make a OneToOneField because it want´s a related_name for each, which would make No sense here, since they are all skills and I dont want to call for the owner (Legend) of the skill in 4 different ways I also tried to make a legend field in the Skill model with a foreignkey on the Legend, but that didnt turned out how i wanted it to be. thanks for the help ^.^ -
Validate across nested serializers with django rest framework
If you were to have a nested serializer, but required a certain parameter in the parent depending on a value in the child, how could you enforce the logical requirement when necessary? For example: class ChildSerializer(serializers.ModelSerializer): foobar_attribute = serializers.ChoiceField( required=True, choices=foobar_choices, ) class ParentSerializer(serializers.ModelSerializer): child = ChildSerializer(required=True) optional_attribute = serializers.CharField( required=False, ) optional_attribute should be required only when foobar_attribute is a certain choice, but optional for all else. Throwing a validate function on ParentSerializer or ChildSerializer only exposes attributes for that serializer, and none else. How can I perform validation across nested serializers without creating rows ( as would occur if validation was performed in perform_create )? -
Deploy Machine learning Models with Django
I'm following Piotr Płoński's guide on Deploying ML models with Django Currently where I am in the Guide: https://www.deploymachinelearning.com/#algorithms-registry (Just above this section) I got this point but my server doesn't want to run when I type in python manage.py test apps.ml.tests as the guide says in the guide. The error of that I am getting OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap> Have any of you had this error before? and what's the fix? Some searches I did say its a path or URL error but I don't see any URLs or paths in the code (Might be mistaken) I saw that Piotr Płoński is on Stackoverflow @pplonski wonder if I can hear from the man himself :D If anyone could assist or point me in the right direction that would be appreciated. Kind Regards,