Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Can't import Bootstrap scss files in Django project
I'm trying to integrate bootstrap into my Django project and want to overwrite some BS classes as per the documentation. Now in my custom base.scss I got # base.scss @import "bootstrap/scss/bootstrap.scss"; and it doesn't find the dir, why? Do I have to work with npm? (never worked with scss before) # settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ['static'] -
How to delete all the values of one particular column Django
I want to delete of all values of one particular column. I tried this way , now i can not do runserver application = models.CharField(null=True, editable=False ) -
my token sends user_id How I can get it by localStorage in Angular?
I need help trying to figure it out, i am using django as backend and Angular as frontend. My django backend pass a token so it can be acessed in frontend by login. login.ts onLogin() { this.service.loginUser(this.input).subscribe( response => { console.log(response) this.jwttoken.setToken(response['token']); this.jwttoken.getItem(response); this.router.navigate(['dashboard']); }, error => { console.log('error', error); } i save it in a localstorage that can be acessed on my service jwttoken service jwtToken : string decodedToken: {[key: string]: string} public storage: Storage; constructor() { this.storage = window.localStorage; } setToken(token: string){ if (token) { this.jwtToken = token; } } getItem(key: string) { if(this.storage){ localStorage.setItem('token',(key)); } return null; } i need to have my user id that i can see on my web browser console. {"token":"[object Object]","d34330659cba7cf64e8414f83aa6522f55b0f978":"d34330659cba7cf64e8414f83aa6522f55b0f978","[object Object]":"{"token":"d34330659cba7cf64e8414f83aa6522f55b0f978","user_id":1,"email":"admin@admin.com"}"} this is where i need to access my user id, so i can send it to my html file export class RegularComponent implements OnInit { patient_code: any; number_tumor: any; tumor_size: any; tumor_volume: any; biopsy_date: any; hp_lote_number: any; closeResult: string; userlists: any; user_id: any; constructor(private service: SharedService, private modalService: NgbModal, private jwtstorage: JWTTokenServiceService) { } localstorage = JSON.stringify(this.jwtstorage.storage).replace(/\\/g, ""); ngOnInit() { // this.getUserlist(); console.log(this.localstorage); } // getUserlist() { // let observable = this.service.getUsersList(); // observable.subscribe((data) => { this.userlists = data; console.log(data); … -
Filtering duplicates in queryset based on UUIDField
I'm running into some problems when pulling a specific list of objects from my db. I'm picking up python/django after quite a bit of time off and feeling pretty rusty. As an exercise I am building an app that allows a group of friends to 'draft' season tickets, eg. take turns selecting which games you want to attend until all the tickets are distributed. The way I've chosen to go about this is to have one db model that contains a dump of all games for an entire season (SportSeason) and a db that contains draft information (TicketDraft). As there will be many rows (to track ticket/game selection) for each draft session, I've created a UUID field for logically grouping the rows that belong to the same draft. models.py class SportSeason(models.Model): year = models.IntegerField(default=None) sport = models.CharField(max_length=10, default=None) home = models.CharField(max_length=10) visitor = models.CharField(max_length=10) date = models.DateTimeField(auto_now=False) class Meta: app_label = 'ticket_draft' class TicketDraft(models.Model): tt_group = models.IntegerField() tt_status = models.CharField(max_length=10) # available, selected tt_owner = models.CharField(max_length=30) gm_date = models.DateTimeField(auto_now=False, null=True) team_home = models.CharField(max_length=10) team_visitor = models.CharField(max_length=10) draft_year = models.IntegerField() ssn_create = models.DateTimeField(auto_now=True) ssn_owner = models.CharField(max_length=30) ssn_status = models.CharField(max_length=10) # active, cancelled, complete ssn_ident = models.UUIDField(default=uuid.uuid4, editable=False) On the home page … -
argument after ** must be a mapping, not str error, using celery but not without using it
I have a simple send_email_task() function. @shared_task def send_email_task(subject, message, email_from, recipient_list): print("Email Sent", f"{subject, message, email_from, recipient_list}") send_mail(subject, message, email_from, recipient_list) return None I'm calling it in the views like : send_email_task.apply_async( subject, message, email_from, recipient_list) But I'm facing this error, I don;t understand what it is, I tried reading other answers on stack overflow but not able to find how to handle this problem. -
Dynamically updating models in Django (Javascript, HTML and Python)
am trying to dynamically update a file for a django model but am having difficulty figuring it out: here is the code I have so far: Detail.html <table class="cert-table"> <tr> <th>Dpt:</th> <th>Licence:</th> <th>Exp. Date:</th> <th>Upload Date:</th> <th>File:</th> <th></th> <th></th> <th></th> </tr> <tr> {% for cert in list_of_certs %} <td>{{ cert.department }}</td> <td>{{ cert.licence }}</td> <td>{{ cert.exp }}</td> <td>{{ cert.ul_date }}</td> <td>{{ cert.file }}</td> <div class="upload-tds"> <td> <button class="btn sitebtn{{cert.id}}" id="sitebtn{{cert.id}}" onclick="openUpdateCert()">Update File</button> </td> <td> <div class="upload-tds-hidden" id="form-update-cert-js"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ cert.file }} <button type="submit">Create</button> </form> </div> </td> </div> </div> </tr> {% endfor %} </table> main.js: function openUpdateCert() { var x = document.getElementById("form-update-cert-js"); var z = document.getElementById("sitebtn{{cert.id}}"); if (x.style.display === "block") { x.style.display = "none"; z.style.display = "block"; } else { x.style.display = "block"; z.style.display = "none"; } } models.py from django.db import models from django_resized import ResizedImageField class Site(models.Model): name = models.CharField(max_length=25) picture = ResizedImageField(size=[319, 305], upload_to='images/', blank=True, null=True) location = models.CharField(max_length=20) def __str__(self): return self.name class Certificate(models.Model): site = models.ForeignKey(Site, on_delete=models.CASCADE, blank=True, null=True, editable=False) department = models.CharField(max_length=4) licence = models.CharField(max_length=50) exp = models.DateField() ul_date = models.DateField(auto_now_add=True) file = models.FileField(blank=True, null=True) def __str__(self): return self.licence forms.py from django.contrib.auth.forms import AuthenticationForm, UsernameField from .models import Site, Certificate …