Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django cant connect to tablespace
I want to make a website with the help of which it will be possible to change, watch, add entries to an already made database. I chose django for this. Previously i successfully connected to this tablespace Error application: django.db.utils.ProgrammingError: ERROR: tablespace "AAA" does not exist Frist models.py class svod_lic(models.Model): bot=models.CharField(max_length=255) def __str__(self): return {self.bot} class Meta: db_table='prim' db_tablespace="AAA" settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'AAA': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'AAA', 'USER': '****', 'PASSWORD': '****', 'HOST': '192.168.0.30', 'PORT': '5432', } } Second models.py with error class ksg_npp(models.Model): id=models.IntegerField(), name=models.CharField(max_length=1000), c_prof=models.IntegerField(), smj_prof=ArrayField( models.IntegerField() ) KSG=models.CharField(max_length=1000) class Meta: db_tablespace = "AAA" db_table = 'ksg_npp' honeslty i dnot even know why it`s happening pls help i am desperate -
Any benefit breaking down fields into their own tables?
These are my models: class Organism(models.Model): genbank = models.CharField(max_length = 10, primary_key=True, unique=True) genus = models.CharField(max_length = 50) species = models.CharField(max_length = 50) strain = models.CharField(max_length = 50) organism_sequence = models.TextField() created_at = models.DateTimeField(auto_now_add = True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.SET_NULL, null=True) class Motif(models.Model): organism = models.ForeignKey( 'Organism', on_delete = models.CASCADE, related_name= "motifs", ) region_name = models.CharField(max_length = 15, choices = MOTIF_CHOICES) motif_sequence = models.CharField(max_length = 600) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.SET_NULL, null=True, ) created_at = models.DateTimeField(auto_now_add = True) It's basically a library. Each Organism has motifs as child objects. Would I benefit from making Genus, Strain and Species their own table? The reason I ask is because I saw something similar in an MDN tutorial of a library where language and genre were broken down into their own tables. If I were to follow the same logic for my project, I would break down the Genus, Species and Strain fields into their own tables. Does this help later with filtering or something like that? Thanks -
Can I use the same backend of a website to build a mobile application?
I am developing a website using Python (Django) and JavaScript to back-end. In the future I am thinking of using this same backend to build a mobile application. I would like to know what technologies I can apply to use the backend of my website to make a mobile application. -
Templates only displaying related objects
I am only able to view the related fields of the model objects in my templates. I was trying my hands on having templates in the root directory and had thought that was the issue, but the challenge still persists when I move my templates directory into apps folder Here's a sample of an object I am trying to access in my templates class Apartment(models.Model): rent = models.PositiveSmallIntegerField() address = models.ForeignKey('Address', on_delete=models.CASCADE) occupied = models.BooleanField() ... settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates', '../../lib/site-packages/django/contrib/admin/templates' ], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] views.py class ApartmentDetailView(DetailView): model = Apartment context_object_name = 'apartment' sample template: Apartment-detail.html {% extends '../base.html' %} {% block title %} {{ apartment.address }} {% endblock %} {% block content %} <div> {{ apartment.address }} </div> <section> {{ apartment.address }} <p><em>Number of rent</em> : {{ apartment.rent }}</p> <p><em>Number of occupied</em> : {{ apartment.occupied }}</p> ... </section> {% endblock %} for the template above, I am able to see {{apartment.address}} but neither {{apartment.rent}} nor {{apartment.occupied}} I checked the page source to be double sure I am not making any mistakes with my templating and have tried without success to replicate … -
How do Django migrations works with updated code?
I'm currently changing a field on the model for which I want to add an intermideary model. For example, I have a Game model which I get from a 3rd party API and I keep their ID on my model as well. However I would want to extend this to get the data from other APIs as well. Current State: class Game(models.Model) api_id = models.IntegerField() Updated State: class Provider(models.Model): api_id = models.IntegerField() class Game(models.Model) provider = models.OneToOne... @property def api_id(self): return ... However, everywhere in my code I reference api_id on my Game model so I've also added a property that retrieves it from the Provider model. I've created the necessay migration and the migration command, however, my question is: Will the migration take the field api_id from the Game model even though it won't be present there once or would it take the newest property I've created? -
How do I retrieve data from a Django DB before sending off Celery task to remote worker?
I have a celery shared_task that is scheduled to run at certain intervals. Every time this task is run, it needs to first retrieve data from the Django DB in order to complete the calculation. This task may or may not be sent to a celery worker that is on a separate machine, so in the celery task I can't make any queries to a local celery database. So far I have tried using signals to accomplish it, since I know that functions with the wrapper @before_task_publish are executed before the task is even published in the message queue. However, I don't know how I can actually get the data to the task. @shared_task def run_computation(data): perform_computation(data) @before_task_publish.connect def receiver_before_task_publish(sender=None, headers=None, body=None, **kwargs): data = create_data() # How do I get the data to the task from here? Is this the right way to approach this in the first place? Or would I be better off making an API route that the celery task can get to retrieve the data? -
Ngrok Falied to complete Tunnel connection
I am working on my first Django project. Trying to connect to the auto-grader for my course through ngrok.I ran python manage.py runserver. I can see the website at http://127.0.0.1/8000 and it is working. I tried the command ngrok http 80 and got a forwarding URL. When I try to see the Http://xxxxxxxngrok.io/127.0.0.1/8000 I get the following error: "The connection to http://444e-2600-1700-5egb-70c0-c843-879c-12ad-2b03.ngrok.io was successfully tunneled to your ngrok client, but the client failed to establish a connection to the local address localhost:80. Make sure that a web service is running on localhost:80 and that it is a valid address. The error encountered was: dial tcp [::1]:80: connectex: No connection could be made because the target machine actively refused it. I typed netstat after running the runserver command. It shows 127.0.0.1/8000 with a state "listening" How can I resolve this?" -
Firebase private key set as a config variable in Heroku not recognised - Django app
this is driving me mad. I have .env set up in my Django project and my firebase private key in the .env file. It works fine locally but when I move it to Heroku, set the config variable it does not recognise the key start -----BEGIN PRIVATE KEY----- I have tried loads of different solutions suggested on here, adding "", stringify the os.env variable but nothing works. Im bored now does anyone have an answer? -
how to edit/update multiple images in django rest framework?
I am writing an api in which array of ids are passed in query string and multiple images are passed in formdata like this screenshot now my goal is to map ids passed in array with the images selected and send them to serializer or directly to object to update them into database below is my code: @api_view(["PUT"]) def updateImages(request): newmedia = request.FILES.getlist("media") query = request.query_params.getlist("imageID") d = ProductsImages.objects.filter(id__in=[1,2,3]) print(d) # dd = ProuctsImagesSerialzer(data=list(image_data),many=True) # print(dd.is_valid()) # print(dd.errors) # image_data.media = newmedia # image_data.save() return JsonResponse({"message":"image updated"}) my serializer: class ProuctsImagesSerialzer(serializers.ModelSerializer): class Meta: model = ProductsImages fields = ("id","media",) image model class ProductsImages(models.Model): media = models.ImageField(upload_to="images") -
Can render_to_string() work with sekizai?
All: I just want to know if render_to_string() work with sekizai ? When I use render_to_string(), I always got the error: django.template.exceptions.TemplateSyntaxError: You must enable the 'sekizai.context_processors.sekizai' template context processor or use 'sekizai.context.SekizaiContext' to render your templates. Even though I've added sekizai context processor, 'sekizai.context_processors.sekizai'. Just wonder if there is anything special I need to do to make render_to_string() works with sekizai ? -
DRF filterset_class dependent on nested serializers
I've got a model that has two ForeignKeys to polymorphic models, each with their own child models. How can I filter through the fields of these child models from a single view? class Shape(PolymorphicModel): dimensions = ... class CircularShape(Shape): radius = ... class TriangularShape(Shape): arm_length = ... class Color(PolymorphicModel): alpha = ... color RGBColor(Color): r, g, b = ... class CMYKColor(Color): c, m, y, k = ... class PhysicalObject(Model): shape = ForeignKey(Shape) color = ForeignKey(Color) class PhysicalObjectViewSet(ModelViewSet): # it should allow me to filter through both Shape and Color subclasses' fields # for example color__r__gte=127&shape__radius__gte=5 filterset_class = ... -
Django form not showing when importing it to html
Trying to import a Django form into an html template, but it's not showing up, and nothing on here is working. I feel like i've exhausted every solution on this site and nothing. Any ideas? views.py def saveFileUpload(request): context = {} if request.method == 'POST': capturedForm = UploadFileForm(request.POST or None, request.FILES or None) if capturedForm.is_valid(): capturedForm.save() else: capturedForm = UploadFileForm() context['form'] = capturedForm return render(request, 'fileupload.html', context) forms.py class UploadFileForm(forms.ModelForm): class Meta: model = Project fields = "__all__" fileupload.html <html> <body> <form enctype="multipart/form-data" action="" method="post">{% csrf_token %} {{ form.as_table }} <input type="submit" value="Save"> </form> </body> </html> -
Django: Serialization of custom model field with relation
Context I am developing a version control system similar to git based on django on a postgres database. In my concept, I have the following data structures: AbstractDataModel I have different types of data models, that are based on that AbstractDataModel type, which provides the necessary meta data to manage the versioning. One instance of AbstractDataModel is similar to a single file inside a git repository. AbstractDataBaseline In this data model, I want to store baselines over all data instances. Like a single commit in git. For certian reason, a single version in that system consists of a ProjectBaseline, that points to multiple baselines like TypeABaseline, TypeBBaseline, TypeCBaseline, ... and each baseline points to multiple instances of data. My implementation: # app1/models/abstract_data_model.py from django.db import models class AbstractDataModel(models.Model): class Meta: abstract = True constraints = [ models.UniqueConstraint(fields=['object_id', 'version'], name='...') ] object_id = models.IntegerField() version = models.CharField(max_length=64) The object_id should be used to keep track of an instance between multiple versions and the version is just an incremented number, separated with points to represent a simplified branching. e.g. v1 -> v2 -> v3 -> v4 -> v5 -> ... \-> v3.1 -> v3.2 -> 3.3 -> ... # app1/models/abstract_data_baseline.py from django.db … -
how can i add every number i insert in a django database
I want an amount to add to an already exiting amount each time I make a put request to it keep track of the sum in Django rest framework but I am finding it difficult I can only add to it once. -
Django project - How to make separate virtual environments for different devices but for the same project (i.e PC and Laptop)
I have a Django project that I'm using for university, and it uses a virtual environment following the tutorial that VSCode provides on Python and Django on their website. As I use multiple devices (PC/Laptop), I share the code with myself via Google Drive. On my PC everything works fine, but when I try to run the local server on my laptop, I get an issue where there is "No python found", which is supposedly due to the pyvenv.cfg having the Python path set to the path where my Python is on my PC, which is obviously not the same as my laptop. I've been unable to find the answer so far, so how can I have 2 separate virtual environments using VSCode where I can easily switch between working on my PC and Laptop? -
'tuple' object has no attribute 'get' Django, how i can fix this?
view.py from django.views.generic import ListView from .models import post # Create your views here. class HomePageView(ListView): model = post template_name = 'home.html' context_object_name = 'all_posts_list' i'm beginner, just start learning django framework -
Custom name for key in queryset
I have an Invoice query set. The invoice has an appointment object, that has a patient object that has a name attribute. I am trying to annotate so I can get the name of the patient as well. The rest of the fields return data okay. But the patient name doesn't. I have tried - F("appointment__patient__name") and also "appointment__patient__name". What am I missing here ? def get_corporate_invoices( start_date: date, end_date: date, corporate_uuid: str ) -> QuerySet[Invoice]: return ( Invoice.objects.annotate( entry_date=F("appointment_date"), payment_method=Value("--", output_field=models.TextField()), debit_amount=Round("amount", precision=2), running_balance=Value(0.00, output_field=models.FloatField()), patient_name=F("appointment__patient__name"), ) .filter( corporate_uuid=corporate_uuid, appointment_date__gte=start_date, appointment_date__lte=end_date, isdeleted=False, status="Cleared", corporate_uuid__isnull=False, ) .order_by("appointment_date", "concierge_rct_id") .values( "entry_date", "payment_method", "debit_amount", "running_balance", "patient_name" ) ) -
How to stop a "latent" Python Django cursor execute exception with SQLite
I am trying to automate a complete application schema rebuild in Django. Basically, drop all the old tables, delete the migration and cache file(s), delete the migration history, and then makemigrations and migrate. I understand this will have some scratching their heads but I like to configuration control my test data and load what I need from csv files and "starting from scratch" is much simpler with this model. I'm hopeful the automation will work against all the different Django-supported databases so trying to come up with an approach that's generic (although some gaps and brute-force). As noted above, the first step is to drop all the existing tables. Under the assumption that most model changes aren't deletes, I'm doing some class introspection to identify all the models and then attempting to discern if the related tables exist: app_models = get_all_app_models(models.Model, app_label) # Loop through and remove models that no longer exist by doing a count, which should # work no matter the SQL DBMS. with connection.cursor() as cursor: for app_model in app_models[:]: try: cursor.execute (f'select count (*) from {app_model._meta.db_table}') except OperationalError: app_models.remove(app_model) <lots more code, doing cursor and other stuff that works OK> Once the above completes, app_models contains … -
Docker volumes + django
i have Dockerfile with python FROM python:3.8 ENV PYTHONBUFFERED 1 WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . EXPOSE 8000 COPY --from=node /app/src/barbook_app/static /app/src/barbook_app/static RUN python src/manage.py collectstatic --noinput CMD python3 -m spacy download en && python3 src/manage.py migrate && python3 src/manage.py initadmin && \ gunicorn barbook_project.wsgi --chdir src --bind 0.0.0.0 --preload --log-file - And docker-compose app: &app build: context: . dockerfile: deploy/python/Dockerfile restart: always ports: - 8000:8000 expose: - 8000 depends_on: - postgres - redis environment: DB_NAME: barbook_django DB_USER: root DB_PASSWORD: root DB_HOST: postgres DB_PORT: 5432 REDIS_CONNECTION: redis://redis:6379/0 volumes: - ./static:/app/static/ - ./img_source:/app/img_source the problem is when i do docker-copose like this. no static-files appeared but when i map like this static:/app/static/ everything is fine. What's the problem ? -
Context not showing all variable in the dictionary in HTML in django and the server doesnot reloads
Every time i add a new variable to the dictionary it does not show in the HTML. Does Django reload its server itself or is there any other way to reload the server. If I close the server then run it again the variable is showing in the HTML. Also, I notice that the server link stays the same [23/Mar/2022 21:30:43] "GET / HTTP/1.1" 200 81 [23/Mar/2022 21:34:01] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:02] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:02] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:02] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:03] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:03] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:03] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:04] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:04] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:04] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:04] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:05] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:05] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:16] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:29] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:30] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:30] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:30] "GET / HTTP/1.1" 200 101 [23/Mar/2022 21:34:30] "GET / HTTP/1.1" 200 101 [23/Mar/2022 … -
I encountered terminal process error why trying to run python script?
i'm currently trying to run my python script for my django project, but i encounter this error in my vscode IDE. how can i resolve this? How can i also locate legacy on my cmd.exe windows 7enter image description here -
Writting Unnittest Test for Django Model
I've written a test for the get_rendered_text() method in my django app as seen in the Model below. But when i run a coverage report, it still says i haven't tested this particular method meanwhile to the best of my understanding,the test i've written shoul cover this method. class Cross(models.Model): text = CharField(max_length=200) def get_rendered_text(self, carnage): template = Template(self.text) context = Context({'carnage': carnage}) return template.render(context) Here is the test i've written for the above method def test_rendered(self): string_factory = StringFactory() context = Context({'my_title': 'my_title'}) template_to_render = Template( string_factory.text ) rendered_template = template_to_render.render(context) # import pdb; pdb.set_trace() self.assertInHTML('my_title', rendered_template) self.assertIn('my_title', rendered_template) The above test passes just fine. but on my coverage report,it still says i haven't tested this method. So what i'm trying to figure out is why exactly doesn't coverage,mark this test as successful. Thanks -
Django serializer does not print datetime with timezone
I'm trying to print my datetime fields with the time zone i.e like this 2022-03-28T00:00:00+05:30 My serializer like this class ChallengeReadSerializer(serializers.ModelSerializer): start_date = serializers.DateTimeField(format='iso-8601') class Meta: model = models.Challenge fields = [ "start_date", ] Prints this 2022-03-23T03:16:00Z When I modify the serializer like this class ChallengeReadSerializer(serializers.ModelSerializer): start_date = serializers.SerializerMethodField() class Meta: model = models.Challenge fields = [ "start_date", ] def get_start_date(self, obj): return obj.start_date.isoformat() It prints 2022-03-28T00:00:00+05:30, which is what I want. I don't understand how this is happening, and couldn't find any information except it being two formats -
Is it possible to create migration for a model that has a foreign key to an unmanaged model?
I have two models: Model unmanaged class Item(models.Model): name = models.CharField(max_length=50, blank=False, null=False) class Meta: managed = False db_table = 'item' app_label = 'default' New model in the project. I want to create migration for this model class Environment(models.Model): type = models.ForeignKey(Item, on_delete=models.PROTECT) When I run the makemigrations command to create the migration, I get this error: Environment.type: (fields.E300) Field defines a relation with model 'Item', which is either not installed, or is abstract. I know that models with managed = False do not create migrations, but I want to create the migration of the model Environment that will be managed by Django. I'm using Postgres. -
Django JSON not being saved in sqlite database
I am just testing some stuff to figure out how Django works in general. Now I have these small code chunks here which are giving me some problems. Here is a chunk of my models.py file class Recipes(models.Model): name = models.CharField(max_length=120, default='') pub_date = models.DateTimeField('date published') style = models.CharField(max_length=200, default='') brewer = models.CharField(max_length=100, default='') type = models.CharField(max_length=20, default='All Grain') version = models.CharField(max_length=20, default='1') batch_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_time = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) efficiency = models.DecimalField(decimal_places=1, max_digits=4, default=75.0) ibu = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) abv = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) notes = models.TextField(default='') carbonation = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) primary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) secondary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) __fermentables = [] @classmethod def create(cls,attr): recipe = cls() # do something with the book for k in Recipes._meta.fields: if k.name in attr: setattr(recipe,k.name,attr[k.name]) return recipe Here is the part of views.py which is giving me trouble def saveRecipe(request): try: data=json.loads(request.read()) print("printing values") print(data["name"]) #prints here works recipe = Recipes.create(attr=data) recipe.name = data["name"] recipe.save() recipe.addYeast(items=data["yeast"]) recipe.addFermentables(items=data["fermentables"]) recipe.addHops(items=data["hops"]) recipe.addMashStep(items=data["mash"]) return HttpResponse(serialize('json', [recipe]), content_type='application/json') except: return HttpResponse("error") Basically I have a button which parses JSON from filled forms and when …