Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use {{ form }] in bootstrap 4?
I'm trying to add contact form on my web site. I have model.py class ContactMe(models.Model): email = models.EmailField(_("Your Email")) name = models.CharField(_("Name"), max_length=255) message = models.CharField(_("Message"), max_length=255) def __str__(self): return self.name Form.py from django.forms import ModelForm from .models import ContactMe class ContactMeForm(ModelForm): class Meta: model = ContactMe fields = ('email', 'name', 'message') View.py from django.views.generic.edit import FormView from django.shortcuts import redirect from .forms import ContactMeForm class ContactView(FormView): template_name = 'contacts/contact.html' form_class = ContactMeForm success_url = '../' def form_valid(self, form): form.save() return redirect(self.success_url) So, I want to add this form to templates. <div class="i-am-centered"> <form method="POST"> {% csrf_token %} <div class="form-group form-group-lg"> <label>Email</label> {{ form.email }} </div> <div class="form-group form-group-lg"> <label>Name</label> {{ form.name }} </div> <div class="form-group form-group-lg"> <label>Message</label> <textarea class="form-control" id="id_message" rows="5" value="{{ form.message }} </textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> I want users to write me a message and it will be safe in database so I can see it as admin. Unfortunately, I don't know how to add style in templates. -
DJANGO: Multiple ListView on 1 html page (class based views)
I have a page (onboarding.html) where i would like each listview to be displayed, in the same page. The scenario, if you imagine a user uploading address details, and then bank details, and then ID etc. Currently I can get the user to upload address and bank, which insert into the DB - however, pulling them back is an issue-i get one or the other. I'm assuming it's got something to do with my URLS.py. I am using class based views urls.py Literally lookin at AddressListView and BankListView (their name is both 'onboarding', i didn't think this would be an issue being seperate listviewshomepage page with multiple listviews required from django.urls import path from django.contrib import admin from django.views.generic.list import ListView from .views import ( PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView, AddressListView, AddressDeleteView, BankListView, ) from . import views urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('admin/', admin.site.urls, name='admin'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('onboarding/', AddressListView.as_view(), name='onboarding'), path('onboarding/', BankListView.as_view(), name='bank-onboarding'), path('onboarding/upload', views.upload_address, name='upload_address'), path('onboarding/upload/bank', views.upload_bank, name='upload_bank'), path('onboarding/<int:pk>/delete/', AddressDeleteView.as_view(), name='delete_address'), path('books/', views.book_list, name='book_list'), path('books/<int:pk>', views.delete_book, name='delete_book'), path('books/upload/', views.upload_book, name='upload_book'), ] models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import … -
How to create Mapbox Vector Tiles with Django ORM and Postgis
I would like to create a mapbox vector tile in Django, using the ORM. In sql (Postgresql, Postgis) the sql query looks like this for the tile with zoom=8, x=137, y=83: SELECT ST_AsMVT(tile) FROM (SELECT id, ST_AsMVTGeom(geometry, ST_TileEnvelope(8, 137, 83)) AS "mvt_geom" FROM geomodel WHERE ST_Intersects(geometry, ST_TileEnvelope(8, 137, 83)) ) AS tile; ST_AsMVT aggregates all rows and the output is a binary Field (bytea) which can be send as reponse. As geodjango does not include the specific postgis functions I created custom functions for them: class TileEnvelope(Func): function = "ST_TileEnvelope" arity = 3 output_field = models.GeometryField() class AsMVTGeom(GeoFunc): function = "ST_AsMVTGeom" arity = 2 output_field = models.GeometryField() I managed to create the inner Subquery and it works: tile_envelope = TileEnvelope(8, 137, 83) tile_geometries = GeoModel.objects.filter(geometry__intersects=tile_envelope) tile_geometries_mvt = tile_geometries.annotate(mvt_geom=AsMVTGeom("geometry", tile_envelope)) tile_geometries_mvt = tile_geometries_mvt.values("id", "mvt_geom") print(tile_geometrries_mvt) >> <QuerySet [{'id': 165, 'mvt_geom': <Point object at 0x7f552f9d3490>}, {'id': 166, 'mvt_geom': <Point object at 0x7f552f9d3590>},...> Now the last part is missing. I would like run ST_AsMVT on tile_geometries_mvt: SELECT ST_AsMVT(tile) FROM 'tile_geometries_mvt' AS tile; I tried to create a custom Aggregate function for ST_AsMVT, but was not successful. Normally aggregate function like "MAX" for example expect one column as input, whereas ST_AsMVT expects a "anyelement … -
Django CSRFToken middleware appends to URL and shows up after making a “PUT” request to the server. (AJAX issue)
I’m working on a Django Python/Javascript project. The PUT request is done through the client and sent back to the server. After sending the request successfully, the page makes a refresh which is causing the exposure of the csrf token middleware in the URL. I already implemented AJAX, returning false, added an event.preventDefault(), passed a cookie through the header of the fetch, used async functions, and added a try and catch syntax. And I can’t figure out why it is not affecting the resubmission. Hopefully, someone can let me know what I’m not seeing here. Thanks! // Set global variables to use in form submission var id, upt_prodName, upt_prodPrice, upt_prodDescpt; // Block to populate textarea that allows the user to update product info. const editProd_view = (response) => { let prod_id = response.id; let edit_name = response.name; let edit_price = response.price; let edit_descpt = response.description; let prod_idUpt = (document.querySelector("#prod_idUpt").innerHTML = prod_id); let new_name = (document.querySelector( "#editProdName" ).innerHTML = edit_name); let new_price = (document.querySelector( "#editProdPrice" ).innerHTML = edit_price); let new_textarea = (document.querySelector( "#editProdDescpt" ).innerHTML = edit_descpt); id = prod_id; //On submit, send product info to update the product. const edit_prod = (document.querySelector( "#editProd_form").onsubmit = async () => { try { // … -
Django IntegrityError: UNIQUE constraint failed
I'm trying to prevent a certain Insert on a condtion where a product can have only one base_image as True but as many as we want when base_image=Fasle. I've implemented it with django.db.models.UniqueConstraint, EVERYTHING WORKS FINE but in django admin panel instead of getting a red alert in adding view, I'm getting IntegrityError. here is my model (media.py): from django.db import models from apiv1.models.products import Product class Media(models.Model): """ Media table, contains images file names """ product = models.ForeignKey(Product, related_name='media', on_delete=models.CASCADE, blank=False) file_name = models.CharField(max_length=191, blank=False, unique=True) base_image = models.BooleanField(blank=False) class Meta: constraints = [ models.UniqueConstraint( fields=[ 'product', ], condition=models.Q(base_image=True), name='unique_base_image' ), ] def __str__(self): return self.file_name and this is the error: IntegrityError at /admin/apiv1/media/add/ UNIQUE constraint failed: apiv1_media.product_id Request Method: POST Request URL: http://127.0.0.1:8000/admin/apiv1/media/add/ Django Version: 3.1.4 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: apiv1_media.product_id Exception Location: /Users/sal/devel/artiashco_tipnety_cbir/env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py, line 413, in execute Python Executable: /Users/sal/devel/artiashco_tipnety_cbir/env/bin/python Python Version: 3.7.3 Python Path: ['/Users/sal/devel/artiashco_tipnety_cbir', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python37.zip', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/sal/devel/artiashco_tipnety_cbir/env/lib/python3.7/site-packages'] Server time: Wed, 30 Dec 2020 12:58:16 +0000 Expectation: red bootstrap alert in django admin panel -
disable some of django formfield after user enter category
I have a model that it must get some value from user input, but every category has different fields how can i handel this on one form and with every category disable some other fields? -
Django: show the sum of related Items in a template
I want to get the sum of all values from items related to a certain object. In concrete, I have invoices with one or many items. Each item has a price and I want to calculate the sum of the prices for all the items of one invoice. These are the essential parts of my models.py: from django.db import models from django.db.models import Sum class Invoice(models.Model): @property def price(self): return self.item_set.aggregate(Sum('price')) class Item(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2) The view.py is simple: class InvoiceDetailView(DetailView): model = Invoice In my template invoice_detail.html, {{ invoice.price }} delivers something like {'price__sum': Decimal('282.400000000000')} So I added get('price__sum') to the price property of the Invoice Model like that: return self.item_set.aggregate(Sum('price')).get('price__sum') The result actually is fine now, i.e. the template shows something like 282.400000000000 (which I still could style a bit), but I wonder, if that's the way to do something like that or if there is a better way? -
Can I use prometheus to count all emails sent by django server in one day?
Actually this is the question. How could I implement this? django-prometheus 2.1.0 prometheus-client 0.8.0 django 2.2.17 -
same tablename in multiple schemas in postgres legacy database
I have legacy postgres db which have same table names in different schemas. when i create models, only one class is created for tablenames which has same tablenames. Settings.py 'rulestore': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS' : { 'options': '-c search_path=adherence,classification,clinicalrules,clinicalvariables,clinicalvariablesrealization,dbo,demographics,deprecated,dosage,druginstance,druglistdefinition,druglistrealization,drugsubstitutiondefinition,drugsubstitutionrealization,incidenceduration,lab,logicalcombination,medicalconditiondefinition,medicalconditionrealization,resultcheck' }, 'NAME': 'SQLOPS_CREF_Rulestore', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', } table called drug is available in multiple schemas. Is there any way to get models for tables which has same tablename -
Django SearchVector
Django SearchVector is giving ok results in command line but it is not working on my localhost:8000. Here's how I put it. def post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query= form.cleaned_data['query'] results = Post.objects.annotate(search=SearchVector('title', 'body', 'slug')).filter(search='query') context = { 'form' : form, 'query' : query, 'results' : results } return render(request, 'blog/search.html', context) -
UniqueViolation (celery-beat) and DuplicateTable (celery) errors with django_migrations using django/postgresql/celery/celery-beat with DOCKER
I develop a Django app and try to implement asynchronous task for dbbackup stack: django/postgresql/celery/celery-beat and DOCKER (only postgresql is not in a container) I am new with celery and celery-beat When run my project, I have 2 errors with celery and celery-beat I do not understand traces: ... celery-beat_1 | psycopg2.errors.UniqueViolation: ERREUR: la valeur d'une clé dupliquée rompt la contrainte unique « pg_type_typname_nsp_index » celery-beat_1 | DETAIL: La clé « (typname, typnamespace)=(django_migrations_id_seq, 2200) » existe déjà. ... celery_1 | psycopg2.errors.DuplicateTable: ERREUR: la relation « django_migrations » existe déjà celery-beat_1 | django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ERREUR: la valeur d'une clé dupliquée rompt la contrainte unique « pg_type_typname_nsp_index » celery-beat_1 | DETAIL: La clé « (typname, typnamespace)=(django_migrations_id_seq, 2200) » existe déjà. but all migrations seems to be running correctly for django web app container I try to drop postgresql database before building and running containers so I do not understand how django_migrations table could already exist probably dependencies between containers I set all containers depending of redis version: '3.7' services: web: restart: always container_name: web build: context: ./app dockerfile: Dockerfile.dev restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app:/usr/src/app ports: - 8000:8000 env_file: - ./.env.dev depends_on: - … -
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed; TensorFlow
I'm trying to make an ai that detects object with the help of this(https://gilberttanner.com/blog/tensorflow-object-detection-with-tensorflow-2-creating-a-custom-model) link and I ran into a problem when I finished the installation and was checking for errors using the code python object_detection/builders/model_builder_tf2_test.py My system: Windows 10 Python 3.7.0 TensorFlow 2.4.0 Output: Traceback (most recent call last): File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 64, in <module> from tensorflow.python._pywrap_tensorflow_internal import * ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "object_detection/builders/model_builder_tf2_test.py", line 21, in <module> import tensorflow.compat.v1 as tf File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\__init__.py", line 41, in <module> from tensorflow.python.tools import module_util as _module_util File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\__init__.py", line 39, in <module> from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 83, in <module> raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 64, in <module> from tensorflow.python._pywrap_tensorflow_internal import * ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. -
best way to implement ManyToManyField check?
Want to create a Song object. How do I check if this Song object is in a particular user's UserProfile to avoid repetition? tried this but threw me an error argument of type 'QuerySet' is not iterable; songs_available = user.userprofile.liked_songs.all() if not song in songs_available: user.userprofile.liked_songs.add(song) models.py class Song(models.Model): track_name = models.CharField(max_length=250) artiste_name= models.CharField( max_length=200) album = models.ForeignKey(Album, on_delete= models.CASCADE, null=True, default=None, related_name = "songs") class Meta: db_table="Song" def __str__(self): return self.track_name class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None , null= True) liked_songs = models.ManyToManyField("Song", null=True , default=None, related_name="users_that_liked_me") class Meta: db_table = "UserProfile" def __str__(self): return self.user.username views.py (part of it) song, created = Song.objects.get_or_create(track_name = track, artiste_name = artist, album = album) wanted to try if created but that only checks for the song model as many users could have the same song, it doesnt really help -
“ProgrammingError at / relation ”posts_post“ does not exist LINE 1: …evious_post_id”, “posts_post”.“next_post_id” FROM “posts_pos…”
I just finished writing a blog app with django which works perfectly locally but on deploying, I'm getting this error "OperationalError at / no such table: posts_post". After installing postgres, the error message changed to "ProgrammingError at / relation "posts_post" does not exist LINE 1: ...evious_post_id", "posts_post"."next_post_id" FROM "posts_pos..." Please what can I do? -
How do I load a youtube video iframe for every video in my django template?
When I load the youtube iframe as seen below, it loads every video: {% for topic in topics %} <div id="video_player" class="col-lg-4 col-md-6 mb-4" style="float: left;"> <div id="player" > <iframe width="100%" height="300px" src="https://www.youtube-nocookie.com/embed/{{ topic.video_id }}?enablejsapi=1&controls=1" frameborder="0"></iframe> </div> <div class="container"> <a href="{% url 'blog:topic' topic.id %}"><h5 class="border-bottom mb-1">{{topic.title}} </h5> </a> <small><h5 class="border-bottom mb-1">{{ topic.category }}</h5> | {{ topic.date_created}}</small> <p>{{ topic.content|safe|slice:"0:80" }}...</p> </div> </div> {% endfor %} But when I use the Youtube Iframe API as seen below, it only loads the first video and does not load the rest: <script> // 2. This code loads the IFrame Player API code asynchronously. var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // 3. This function creates an <iframe> (and YouTube player) // after the API code downloads. var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { height: '300', width: '100%', videoId: '{{ topic.video_id }}', events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); } // 4. The API will call this function when the video player is ready. function onPlayerReady(event) { event.target.playVideo(); } // 5. The API calls this function when the player's state changes. // The function indicates that when playing a video (state=1), // the player … -
Not able to change values in hidden fields
I created a ModelForm in Django and I am having an issue in adjusting the values in some hidden fields. The basic process goes: User fills out form The View looks at the Boolean values and if one is True, then a value is placed in the corresponding field before saving. or, that is what SHOULD be happening. What is happening is that it seems that I am not writing to the hidden fields when the Boolean fields are True in the views.py file. Here is my models.py file information: class ruck_logs(models.Model): date_performed = models.DateField(auto_now=False,auto_now_add=False) rucker_name = models.CharField(max_length=30) ruck_miles = models.PositiveIntegerField() coupon = models.BooleanField() pt = models.BooleanField() ruck_WO_only = models.BooleanField() coupon_multiplyer = models.PositiveIntegerField(default=0) pt_multiplyer = models.PositiveIntegerField(default=0) ruck_workout_multiplyer = models.PositiveIntegerField(default=0) Here is my forms.py information: from django.forms import ModelForm from datalogger.models import ruck_logs from django import forms class DateInput(forms.DateInput): input_type = 'date' class RuckLogsModelForm(ModelForm): class Meta: model = ruck_logs widgets = {'date_performed' : DateInput(), 'coupon_multiplyer' : forms.HiddenInput(), 'pt_multiplyer' : forms.HiddenInput(), 'ruck_workout_multiplyer' : forms.HiddenInput()} fields = ['date_performed', 'rucker_name', 'ruck_miles', 'coupon', 'pt', 'ruck_WO_only', 'coupon_multiplyer', 'pt_multiplyer', 'ruck_workout_multiplyer'] Here is my views.py file information: def rucklogs(request): if request.method == 'POST': form = RuckLogsModelForm(request.POST) if form.is_valid(): ruck_miles = form.cleaned_data.get("ruck_miles") coupon = form.cleaned_data.get("coupon") pt = form.cleaned_data.get("pt") ruck_WO_only … -
Django ORM annotate performance
I'm using Django and Django REST Framework at work and we've been having some performance issues with couple endpoints lately. We started by making sure that the SQL part is optimized, no unnesecary N+1 queries, indexes where possible, etc. Looking at the database part itself, it seems to be very fast (3 SQL queries total, under a second), even with larger datasets, but the API endpoint still took >5 seconds to return. I started profiling the Python code using couple different tools and the majority of time is always spent inside the annotate and set_group_by functions in Django. I tried Googling about annotate and performance, looking at Django docs, but there's no mention of it being a 'costly' operation, especially when used with the F function. The annotate part of the code looks something like this: qs = qs.annotate( foo_name=models.F("foo__core__name"), foo_birth_date=models.F("foo__core__birth_date"), bar_name=models.F("bar__core__name"), spam_id=models.F("baz__spam_id"), spam_name=models.F("baz__spam__core__name"), spam_start_date=models.F("baz__spam__core__start_date"), eggs_id=models.F("baz__spam__core___eggs_id"), eggs_name=models.F("baz__spam__eggs__core___name"), ) qs = ( qs.order_by("foo_id", "eggs_id", "-spam_start_date", "bar_name") .values( "foo_name", "foo_birth_date", "bar_name", "spam_id", "spam_name", "eggs_id", "eggs_name", ) .distinct() ) The query is quite big, spans multiple relatonships, so I was sure that the problem is database related, but it doesn't seem to be. All the select_related and prefetch_related are there, indexes too. I … -
Where to store media files of Django app in order to save them after docker container updating?
I have a Django app where media files are uploading to the my_project_directory/media/images/ (so nothing special, just a common approach). The problem raised after dockerizing my app. Every time i need to update my container after pulling latest docker image, old container is removed(including, of course media files) and the new, empty one is built. So the question is - how to make my Django app stateless and where/how to store media files? Is it possible to store them in a special docker container? If yes, how? if no, what could you suggest? -
DJANGO: How to Render swagger-codegen model objects instead of database model object
I have an existing Django project in which I am trying to separate the backend and frontend of an existing webapp. The idea is to expose the backend functions as a rest api and then also build a webapp that allows users to interact with the api functionality in a graphical way. The api exposes a swagger/openapi document and I have used swagger codegen to generate a client to intereact with that. as a proof of concept I am trying to reimplement a view that used database object directly with one that calls the api to do the same functionality here is the original view def load_mapping_metadata_only_operations(request): mapping_operation_list = MappingOperation.objects.using('metadata') print(mapping_operation_list[1]) context = { 'mapping_operation_list': mapping_operation_list, 'transformation_list': [], 'source_table_list': [], 'destination_table_list': [], } x = render(request, 'migration_core/migation_tool.html', context) print(x.content) return x and here is the view that I am now trying to replace it with. def load_mapping_metadata_only_operations(request): try: mapping_operation_response = api_instance.find_models_by_name() except ApiException as e: print("Exception when calling MappingApi->find_models_by_name: %s\n" % e) print(mapping_operation_response[1]) api_response_dict = context = { 'mapping_operation_list': mapping_operation_response, 'transformation_list': [], 'source_table_list': [], 'destination_table_list': [], } x = render(request, 'migration_core/migation_tool.html', context) print(x.content) return x this is the template that the list is sent to: <li class="nav-item"> <select class="selectpicker mr-sm-2" … -
Why do all fieldset objects have "collapse" class in django admin?
I have a fieldset defined in django admin and it looks as following fieldsets = ( (_('order'), { 'classes': ('col',), 'fields': ('ManualName', ) }), (_('Payment'), { 'classes': ('col',), 'fields': ('name',), }), (_('Delivery'), { 'classes': ('col',), 'fields': ( 'partnumber', 'ean',), }), (_('Gift'), { 'classes': ('col',), 'fields': ('GiftShortDescString', ), }), ) for some reason, instead of displaying in blocks next to each other (as they do in admin for another model) these still display as if they had 'classes': ('collapse',), . The behaviour is the same even if they have no classes eg fieldsets = ( (_('order'), { 'fields': ('ManualName', ) }), would still display collapsed. It behaves like there was the collapse class added by default which moreover overrides all the other specified classes which blows my mind. I hard reloaded the page and tried different browsers. Any hint would be much appreciated -
Django REST Framework API schema generation with same URL prefix
I'm documenting my Django application using get_schema_view() method, but when I open the Swagger UI all the URLs are placed under the same group. My urls.py look like: router = routers.DefaultRouter() router.register(r'stores', StoreViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), path('api/register/', UserRegistrationView.as_view(), name='register'), path('api/login/', views.obtain_auth_token, name='login'), # Documentation path('openapi/', get_schema_view( title='Title API', description='Some description goes here...', version='v0.1' ), name='openapi-schema'), path('docs/', TemplateView.as_view( template_name='documentation.html', extra_context={'schema_url': 'openapi-schema'} ), name='docs') ] All the endpoints are placed under a group called api in the Swagger UI. How can I specify the api/ prefix while generating the schema in order to group the endpoints by model? Thanks. -
How to Query data from MySQL database after updating Django model field in Django
After updating posts model field in MySQL database using using Django framework, I'm unable to query posts from the Database. Whenever I run the command python manage.py runserver, all seems to be well with the server. However, when enter the post url to display the list of posts I uploaded on the database before updating the model field, I get 1054, "Uknown column 'start_post.author_id' in the 'field list' I have spent a couple of hours try to figure out why I'm getting the error but I still don't get it. In model.py I had: title = models.CharField () preamble: models.Charfield () body = models.TextField() •••• I updated the above model to: title = models CharField () author = models.ForeignKey(User, on_delete=models.CASCADE) introduction = models.charfield () body = models.TextField() •••• Before updating it everything was working appropriately. But after updating it I'm unable to access the list of posts on browser, from the url start\ as well as the post detail page. I didn't have the author field in the first model but I added it to the updated model. What can I do to solve this problem? -
How to store bitcoin and USD on the same django models field?
To store USD I am using DecimalField: amount = models.DecimalField( max_digits=12, decimal_places=2, ) But what if I want to store bitcoins? Bitcoin's minimal thing is satoshi. One bitcoin = million satoshi. I have 2 options: using DecimalField with decimal_places=6 or using an IntegerField. But I do not want to have a sepperate field for storing this. Is there any way to organize storing bitcoin and USD in the same field? -
how to add a field to models
I have a question of how to inherit a field from the model and display it in the admin panel (and manage it). I am using django-avatar app. Also i have a profile model(not relevant to django-avatar): class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) def __str__(self): return f'{self.user.username} Profile' How can I add an avatar field to the profile model so that in the admin panel in the user's 'profile' section, I can see the avatar for this user? I would be grateful for any help -
probelm at installing channels(django), and importing it's inner packages(channels.layout)
I have the same problem. pyhton(3.9.1). using virtual environmnet (venv). installed django. updated: setuptools: pip install --upgrade setuptools, pip(20.3.3): py -m pip install --upgrade pip wheel: python -m pip install --upgrade pip setuptools wheel (latesed version for today(30/12/20)). Tried to use: python -m pip install -U channels. installed "Microsoft Visual C++ Build Tools" Tried the self installing twisted: https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted All done, but still not working. Also tried pip install: pip install pytype pip install django-channels. The django-channels, but when runnig on PyCharm, it recognize channels but not: channels.layers. Can anyone help?