Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save coordinates from Folium map to Django
I want to make a web application that let user create notes about different places. Is there a way to save coordinates from the folium map to the Django database, SQLite 3 for example? -
Django: Slow query set to retrieve the order in which the specified tags are mostly included
I would like to get the so-called similar posts, but for some reason the following query set is For some reason, the following query set takes a long time. (500-1000ms) What we are doing below is trying to filter by tags associated with a particular object and retrieve articles in order of the number of tags included. Removing annotate and order_by improves the speed but still takes about 200ms. tag_pks = Video.objects.get(pk=video_pk).tags.values_list("pk") Video.objects.annotate(n=Count("pk")) .exclude(pk=video_pk) .filter(tags__in=tag_pks) .order_by("-n") QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Limit (cost=1059.82..1059.87 rows=20 width=24) (actual time=461.401..461.407 rows=20 loops=1) -> Sort (cost=1059.82..1063.43 rows=1444 width=24) (actual time=461.400..461.404 rows=20 loops=1) Sort Key: (count(videos_video.id)) DESC Sort Method: top-N heapsort Memory: 26kB -> HashAggregate (cost=1006.95..1021.39 rows=1444 width=24) (actual time=385.859..445.844 rows=144784 loops=1) Group Key: videos_video.id Batches: 5 Memory Usage: 4145kB Disk Usage: 7000kB -> Nested Loop (cost=39.20..999.73 rows=1444 width=16) (actual time=0.076..330.037 rows=150442 loops=1) -> Nested Loop (cost=38.78..354.85 rows=1444 width=16) (actual time=0.059..48.867 rows=150445 loops=1) -> HashAggregate (cost=38.35..38.41 rows=6 width=32) (actual time=0.041..0.046 rows=3 loops=1) Group Key: u0.id Batches: 1 Memory Usage: 24kB -> Nested Loop (cost=0.71..38.33 rows=6 width=32) (actual time=0.032..0.039 rows=3 loops=1) -> Index Only Scan using videos_video_tags_video_id_tag_id_f8d6ba70_uniq on videos_video_tags u1 (cost=0.43..4.53 rows=6 width=16) (actual time=0.015..0.016 rows=3 loops=1) Index Cond: (video_id = '9af2f701-6272-4714-b99f-afe5e4deb741'::uuid) Heap Fetches: 0 -> Index Only … -
django 4.0 - can't login with registered user
Here is the django shell output: >>> for user in User.objects.all(): ... print(user.username, user.password, len(user.password)) ... ll_admin pbkdf2_sha256$320000$zm6RcAswZJR6B7uXaCVNVd$hRs9nZKWBPpfemhC2yL16XE0wLCRa4Z0dlbUATywleA= 88 ams 1243 4 who 1243 4 whos 1243 4 whosa 1243 4 maksd 1243 4 1243 1243 4 abcde 12345 5 ids 1243 4 amsfd 1234567 7 cancal 1111 4 >>> Here is the login view code: def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse('homepage:index')) else: message = "User doesn't exist or password is incorrect." + "( " + username + ", " + password + " )" else: message = '' form = UserForm() context = {"form": form, "message": message} return render(request, 'users/login.html', context) I sign in with ams, 1243 for example, it shows: https://imgur.com/a/XmJr1Aj I checked the password and username and they match. So kind of feel confused right now. Thanks for your help! -
How do I create , test (and if possible deploy) a django project using only an android 10 device?
How do I create,test(and if possible deploy) a django project using only an android 10 device? -
expected str, bytes or os.PathLike object, not tuple django media file upload
I created a model and add a filefield in it and trying to add this model from admin panel but when I save it it shows me this error. This is emergency pls help me. Thanks -
Django Unit Test not executed
I'm still struggling with tests in Django. Now i've rewrite a test, but it's not executed, so i see no results when i run the test command. Is it because of the wrong test or i'm missing something? Thank you once again :) Models: class Lab(models.Model): lab_name = models.CharField(max_length=200) category = models.ForeignKey(Category, unique=True, null=True, on_delete=models.PROTECT) pub_date = models.DateTimeField('date published') lab_theory = models.TextField() def __str__(self): return self.lab_name class QuestionMultipleChoice(models.Model): lab = models.ForeignKey(Lab, on_delete=models.CASCADE) type = QuestionType.multiplechoice question = models.CharField(max_length=200,null=True) option1 = models.CharField(max_length=200,null=True) option2 = models.CharField(max_length=200,null=True) option3 = models.CharField(max_length=200,null=True) option4 = models.CharField(max_length=200,null=True) answer = models.IntegerField(max_length=200,null=True) def __str__(self): return self.question @property def html_name(self): return "q_mc_{}".format(self.pk) @property def correct_answer(self): correct_answer_number = int(self.answer) correct_answer = getattr(self, "option{}".format(correct_answer_number)) return correct_answer def check_answer(self, given): return self.correct_answer == given Test: def test_past_question(self): """ Questions with a pub_date in the past are displayed on the index page. """ past_date = date(1997, 3, 2) lab2 = Lab.objects.create(lab_name="test lab past question", pub_date=past_date, lab_theory="test lab past question") past_question = QuestionMultipleChoice.objects.create(lab=lab2, question='This is a test question', option1='1', option2='2', option3='3', option4='4', answer='1') response = self.client.get(reverse('labs:index')) print (response) self.assertEqual(str(past_question),'This is a test question') -
How to make reverse nested serialization when we have ManytoMany field in relation? using DRF
my data model is like ''' class Rack(models.Model): rack_id = models.CharField(primary_key=True,max_length=30, verbose_name="Rack Id") rack_set = models.ForeignKey(RackSet, on_delete=models.CASCADE, related_name='wh_rack_set', verbose_name="Rack Set") class Meta: db_table = "rw_rack" def __str__(self): return self.rack_name class RackBay(models.Model): bay_id = models.CharField(primary_key=True,max_length=30, verbose_name="Bay Id") rack = models.ForeignKey(Rack, on_delete=models.CASCADE, related_name='wh_rack', verbose_name="Rack") class Meta: db_table = "rw_bay" def __str__(self): return self.bay_name class RackShelf(models.Model): shelf_id = models.CharField(primary_key=True,max_length=50, verbose_name="Shelf Id") bay = models.ForeignKey(RackBay, on_delete=models.CASCADE, related_name='wh_rack_bay', verbose_name="Bay") class Meta: db_table ="rw_shelf" def __str__(self): return self.shelf_name class RackBin(models.Model): bin_id = models.CharField(primary_key=True,max_length=50, verbose_name="Bin Id") class Meta: db_table = "rw_bin" def __str__(self): return self.bin_name class CargoWarehouseSurvey(models.Model): job_id = models.ForeignKey(WarehouseJob, on_delete=models.CASCADE, null=True, related_name='inputted_job_order', verbose_name="Job Id") warehouse_locations = models.ManyToManyField(WarehouseCell, help_text='Assigned warehouse locations for current survey job.', related_name='warehouse_locations_set') rack_bin_locations = models.ManyToManyField(RackBin, help_text='Assigned rack_bin locations for current survey job.', related_name='rack_bin_locations_set') def __str__(self): return self.id class Meta: db_table = 'warehouses_survey' ordering = ['id'] ''' This is my data model, in CargoWarehouseSurvey has bins relation what ever the selected, i need to get bin belogs to which rack, bay, shelf, bin. like expected Response is "allotted_bins": [ { "rack_id": "A-1", "bays": [ { "bay_id": "B-1", "shelves": [ { "shelf_id": "S1", "bin_ids": [ "12343", "21232" ] }, { "shelf_id": "S2", "bin_ids": [ "43234", "42354" ] }, ] } ] } ] } -
how to fix You are trying to change the nullable field to non-nullable without a default?
i've tried to add a comment section to my blog app add I just added this section to my models: class Comments(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(default = timezone.now) body = models.TextField(max_length = 600, default='') def __str__(self): return self.body then when i tried to makemigtations it gave me this : You are trying to change the nullable field 'user' on profile to non-nullable without a default; we can't do that (the database needs something to populate existing rows). which is related to this model; i didnt change anything on that and it has migrated long time ago without any problem class Profile(models.Model): user = OneToOneField(User, on_delete = models.CASCADE) bio = models.TextField(blank=True) profile_pic = models.ImageField(blank=True, upload_to ='uplodes/profiles', default='uplodes/profiles/default-profile-pic.jpg' ) instagram_url = models.CharField(max_length=350, blank=True, null=True) twitter_url = models.CharField(max_length=350, blank=True, null=True) linkedin_url = models.CharField(max_length=350, blank=True, null=True) website_url = models.CharField(max_length=350, blank=True, null=True) then to solve this problem i've added a defalt=none to user field on Profile, after that makemigrations worked but when i run migrate command this error comes up NOT NULL constraint failed: new__Blog_profile.user_id i have no idea why this happening because this model was created long time ago and worked just fine and now when i … -
ssl.SSLCertVerificationError When connecting to heroku redis with django-channels
I'm making chat. I have a need to use WebSocket and deploy my app to Heroku. I use free heroku-redis and django-channels In my settings py: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [os.environ.get('REDIS_TLS_URL')], }, }, } I tried to use REDIS_URL but I was getting another error "ConnectionResetError: [Errno 104] Connection reset by peer when" Then I switched to REDIS_TLS_URL. Both errors were raised from consumers.py at "await self.channel_layer.group_add()" class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name print('==================================') print('==================================') print(self.room_name) print(self.room_group_name) print('==================================') print('==================================') await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() ......... Here is logs 2021-12-25T08:59:56.469939+00:00 app[web.1]: 2021-12-25 08:59:56,469 DEBUG Upgraded connection ['10.1.3.218', 11273] to WebSocket 2021-12-25T08:59:56.859805+00:00 app[web.1]: 2021-12-25 08:59:56,859 INFO ================================== 2021-12-25T08:59:56.859921+00:00 app[web.1]: 2021-12-25 08:59:56,859 INFO ================================== 2021-12-25T08:59:56.860015+00:00 app[web.1]: 2021-12-25 08:59:56,859 INFO FIRST 2021-12-25T08:59:56.860107+00:00 app[web.1]: 2021-12-25 08:59:56,860 INFO chat_FIRST 2021-12-25T08:59:56.860196+00:00 app[web.1]: 2021-12-25 08:59:56,860 INFO ================================== 2021-12-25T08:59:56.860287+00:00 app[web.1]: 2021-12-25 08:59:56,860 INFO ================================== 2021-12-25T08:59:56.860674+00:00 app[web.1]: 2021-12-25 08:59:56,860 DEBUG Creating tcp connection to ('ec2-34-241-115-34.eu-west-1.compute.amazonaws.com', 29080) 2021-12-25T08:59:56.861684+00:00 app[web.1]: 2021-12-25 08:59:56,861 DEBUG Creating tcp connection to ('ec2-34-241-115-34.eu-west-1.compute.amazonaws.com', 29080) 2021-12-25T08:59:56.872570+00:00 app[web.1]: 2021-12-25 08:59:56,872 DEBUG Closed 0 connection(s) 2021-12-25T08:59:57.708867+00:00 app[web.1]: 2021-12-25 08:59:57,706 ERROR Exception inside application: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129) … -
Understand `basic_fields` attribute of django.form model
while walking through the source code of django.forms.forms.py, I am stuck in below line: self.fields = copy.deepcopy(self.base_fields) Q: In regards to self.basic_fields, can anyone please explain where does it come from ? Why it was introduced in the first place? It seems to me that it is originated from class DeclarativeFieldsMetaclass(MediaDefiningClass):, but class BaseForm does not inherit from it. -
Stylized HTML fields in Django admin
I Have TextField to store HTML text. I want to colorize HTML tags. I use TinyMCE but didn't need an HTML editor like WordPress just simple to colorize like IDE, Search a lot but didn't find anything useful, So if you can help I appreciate it. My field: I want output like this but changeable: -
django API view for javascript Ajax request
Let's say I have a Chart demo class Chart(models.Model): data = models.TextField() I store and load data in format of JSON, manipulate data and tries to render a chart on frontend. User case can be: user use app interface to generate data, upload it data is uploaded to backend and stored within an Chart instance use detail view and a redirect url to illustrate the result def chartDetailView(request, pk): chart = Chart.objects.get(pk=pk) return render(request, 'chart/chart.html', {'data': chart.data}) there are many website that allows costume JS request, for example, Web: how to redirect to a CodePen or JsFiddle with information filled?. since the static page only requires a data context to perform functionality, is there a way I can build an Ajax for javascript to open a new tab for the view? I mean, to code a view which can be requested by anchor link, form, Ajax or fetch with data passed in by JS, and return a static page. (no Chart instance stored) sorry the question may seems ignorant to you, I have learned little about rest framework. I will be very grateful for any suggestion you make. any source to look at. -
How to default language - error in changing it - Django
I have been struggling for quite a while with translation in django. I want to set a default language that is being set everytime user access the website (in a new session). I have studied django documentation, and I found the following algorithm: First, it looks for the language prefix in the requested URL. This is only performed when you are using the i18n_patterns function in your root URLconf. See Internationalization: in URL patterns for more information about the language prefix and how to internationalize URL patterns. Failing that, it looks for a cookie. The name of the cookie used is set by the LANGUAGE_COOKIE_NAME setting. (The default name is django_language.) Failing that, it looks at the Accept-Language HTTP header. This header is sent by your browser and tells the server which language(s) you prefer, in order by priority. Django tries each language in the header until it finds one with available translations. Failing that, it uses the global LANGUAGE_CODE setting. So I am trying to set the language prefix in the requested URL. I have configured my app as follows: settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'crm.middleware.RequestMiddleware', ] .... EXTRA_LANG_INFO = { 'md': … -
How to store static file on Google cloud storages using heroku deployment?
I used whitenoise to save static files, but now I want to save them to Google cloude storage. So I reset dyno and set it as follows, but the static folder is not created in storage. I'm not sure what I'm missing. google_credential is working well. The upload file is well stored. The level is also done without problems. However, static files are not generated in GCS. settings.py configuration if DEBUG is False : ALLOWED_HOSTS = ["cineacca.herokuapp.com", 'cineacca.com',] GOOGLE_APPLICATION_CREDENTIALS = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS") DEFAULT_FILE_STORAGE = "config.custom_storages.UploadStorage" STATICFILES_STORAGE = "config.custom_storages.StaticStorage" STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') GS_DEFAULT_ACL = "publicReadWrite" GS_BUCKET_NAME = "cineacca_bucket" GS_PROJECT_ID = os.environ.get("GS_PROJECT_ID") MEDIA_URL = "/media/" STATIC_URL = "/static/" django_heroku.settings(locals()) custom_storages.py from storages.backends.gcloud import GoogleCloudStorage from storages.utils import setting class StaticStorage(GoogleCloudStorage): bucket_name = setting('GS_BUCKET_NAME') location = "static/" class UploadStorage(GoogleCloudStorage): bucket_name = setting('GS_BUCKET_NAME') location = "uploads/" -
Button type "submit" doesn't let bootstrap modal to open but type="button" doesn't fulfill my need
I have a web page in which there is an input field. And below is an edit button. When I enter some text in the input field and press the edit button, a modal pops up and there is an input field in it also. I want to pass the text from the first input field to the input field in the modal window. But then a problem arises. The modal window only opens when the edit button has type="button". But this type="button" doesn't submit the text input to the backend when I click the edit button. It submits the text to the backend when I use button type="submit", but then the modal doesn't open because the page reloads. Here's my HTML code: <div class="container"> <div class="row manage-groups"> <div class="row g-0 login_form justify-content-center" id="contactForm" novalidate="novalidate"> <form method="POST"> {% csrf_token %} <div class="col-md-12 form-group"> <input type="text" class="login-inpt" id="name" name="type-groups" placeholder="type in the group name"> </div> <div class="row g-0 justify-content-center group-action"> <div class="col-sm-4 submit-group"> <div> <button type="submit" data-bs-toggle="modal" data-bs-target="#ModalAddGroups" class="button-box">Add</button> </div> </div> <div class="col-sm-4 submit-group"> <button type="button" onclick="form_submit()" data-bs-toggle="modal" data-bs-target="#ModalEditGroups" class="button-box">Edit</button> </div> <div class="col-sm-4 submit-group"> <button type="submit" data-bs-toggle="modal" data-bs-target="#ModalDeleteGroups" class="button-box">Delete</button> </div> </div> </form> </div> </div> </div> <!-- Modal window for Edit button … -
Django - Create random dummy data for testing that doesn't break the test suite
I'm trying to think of a way to create random test data of a certain model type for running python manage.py test. So for example if I have a model Post like below. model.py class Post(models.Model): uuid = models.UUIDField(primary_key=True) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)]) some sort of library that'll generate this with random body, random creator from user table would be nice. I tried factory boy, but when the test DB rolls back the DB after a test function it seems to rollback factory boy created dummy data as well even if it's declared in setUpTestData function. This rollback process causes a constrain error since the original data no longer exists. What's a good library or way to create dummy data for Django testing that doesn't break the test suite? dummy_factory.py class PostFactory(DjangoModelFactory): class Meta: model = Post creator = factory.Iterator(User.objects.all()) body = factory.Faker('text') Note: Another option is to just create a function let's say make_dummy_post that uses Post.objects.create() and randomly samples a User and users factory boy to generate body, but I feel like there's a better way to do it … -
Bootstrap toast messages showing for the first card in loop element in a Django project
I want to toast messages for all those cards. but it is showing for the first card only. I have attached a view of my page where I want to add a toast message to view the details of the card if a user is not logged in. Here is a view of my page. document.getElementById("toastbtn").onclick = function() { var toastElList = [].slice.call(document.querySelectorAll('.toast')) var toastList = toastElList.map(function(toastEl) { return new bootstrap.Toast(toastEl) }) toastList.forEach(toast => toast.show()) } <section class="details-card"> <div class="container"> <div class="row"> {% for homes in home %} <div class="col-md-4 mb-4"> <div class="card-content"> <div class="card-img"> <img src="{{ homes.coverImg.url }}" alt="Cover Image"> <span><h4>{{ homes.pricePerMonth }}Taka</h4></span> </div> <div class="card-desc"> <p class="small mb-1"> <i class="fas fa-map-marker-alt mr-2"></i>{{homes.address}}</p> <h3>{{ homes.title}}</h3> {% if request.user.is_authenticated %} <a href="{% url 'HomeDetails' homes.id %}" class="btn btn-md btn-primary hover-top">Details</a> {% else %} <button type="button" class="btn btn-primary" id="toastbtn">XDetails</button> {% endif %} </div> </div> </div> {% endfor %} </div> </div> </section> <!-- Alert Message Popup--> <!--bottom-0 end-0 p-3--> <div class="position-fixed top-50 start-50 translate-middle p-3" style="z-index: 11"> <div id="liveToast" class="toast hide" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <img src="({% static 'img/icon.png' %})" class="rounded me-2" alt="..."> <strong class="me-auto">My Second Home</strong> <small>0.1s ago</small> <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button> </div> <div class="toast-body"> Hello!<br>You need to login … -
Pytest-xdist does not honour settings.DATABASES (or I am doing something wrong)
I am trying to use pytest-xdist for running parallel tests. It works and I see improved performance. To improve further more, I wanted to provide it multiple databases by using django_db_modify_db_settings_xdist_suffix I override that functions in my conftest.py. Since I have four workers, I created four databases manually. Then I use conftest to modify the settings.DATABASES to test for DBNAME against DBNAME_ I verified that my settings.DATABASES has changed and is correct. But the queries are still going to old db DBNAME (which is no longer in my settings.DATABASES) What could be going wrong? Do I need to make any other change? Or change in conftest.py fixture is enough? Thanks in advance for any help or direction. -
DJANGO PARENT AND CHILD CLASS DEFINITION
I actually defined a child class that would inherit the same attributes from the parent class. I also registered the models because I needed to work with them through the admin site just to ensure they work as intended. On accessing the child class at the Django's admin site, the error message displayed; Exception Type: TypeError Exception Value: init() missing 3 required positional arguments: 'content', 'topic', and 'date_added' This was my syntax: class Topic_SON(Topic_SHIM): """A class that models research topics related to Nursing Sciences (NS).""" def __init__(self, topics, date_added): """Initializes attributes from the parent class""" super().__init__(topics, date_added) class Content_SON(Content_SHIM): """A class that models research topic contents related to NS.""" def __init__(self, content, topic, date_added): """Initializes attributes from the parent class""" super().__init__(content, topic, date_added) I feel my approach to defining the child class isn't good enough. Please how do I resolve this? -
what's the value type of the value of request.POST in djagno?
This is from print(request.POST) <QueryDict: {'csrfmiddlewaretoken': ['2Tg4HgJ07qksb3hPUDWSQYueYOjYOkQcmzll9fnjbJ0GZHkWHdM8DtYqZB4uv3Fv'], 'username': ['boycececil'], 'password': ['sunescafe..']}> This is from print(request.POST.get('username')) boycececil So as you can see, list -> string, that's magic!Isn't it? So, somebody know what's going on? -
python selenium chromedriver high CPU usage on parallel execution
I need to run multiple (i.e. 100) scans parallelly using selenium but because of the high CPU usage, my server is getting crushed very quickly. I'd like to know how can I significantly decrease high CPU usage because even if I run 5 scans at a time the CPU usage still hits more than 50%? Should I use another webdriver or can I somehow slow down the scan time but save CPU power(i.e. apply limits)? I've applied some options to decrease the CPU utilization but it didn't help. Below is the chrome options def get_chrome_options(): options = webdriver.ChromeOptions() options.add_argument('headless') options.add_argument('window-size=1200x600') options.page_load_strategy = 'normal' options.add_argument('--no-sandbox') options.add_argument("--disable-setuid-sandbox") options.add_argument("--disable-dev-shm-usage") options.add_argument('--disable-gpu') options.add_argument("--disable-extensions") options.add_argument('--ignore-certificate-errors') options.add_argument("--FontRenderHinting[none]") return options I need to create and run a web driver from my web app (Django) so I have to create a new webdriver each time I make an HTTP request and I can't reuse the same webdriver. Below is the example. def run_scan(request, url): driver = webdriver.Chrome(executable_path=settings.CHROME_DRIVER, options=get_chrome_options()) driver.get(url) print(driver.page_source) Below info describes my current environment Python - 3.9.7 Selenium - 3.141.0 Chromedriver - 93.0.4577.82 OS - alpine linux -
Docker Postgres volume erasing on container restart
Every time I kill my containers and restart them, the data within the db tables is no longer there. docker-compose.yml: version: "3.8" services: db: image: postgres:13-alpine env_file: - .env.dev volumes: - pgdata:/var/lib/postgresql/data backend: build: context: ./backend command: python manage.py runserver 0.0.0.0:8000 expose: - 8000 env_file: - .env.dev volumes: - ./backend:/backend depends_on: - db frontend: build: context: ./frontend dockerfile: Dockerfile volumes: - ./frontend:/frontend - frontend_build:/frontend/build environment: CHOKIDAR_USEPOLLING: "true" depends_on: - backend nginx: build: context: ./nginx ports: - 80:80 volumes: - frontend_build:/var/www/frontend depends_on: - backend - frontend - db volumes: backend_vol: pgdata: frontend_build: .env.dev: POSTGRES_ENGINE='django.db.backends.postgresql' POSTGRES_DB=test-db POSTGRES_USER=dev-user POSTGRES_PASSWORD=dev-pw POSTGRES_HOST='db' POSTGRES_PORT=5432 Any thoughts on why this is happening would be appreciated... -
Django Admin page outdated? showing nonexistent model
My django admin page is still showing a model I used to have. I have deleted this model in the code, Then I updated the imports / serializers and registered the new model I made to admin: admin.site.register(watcher_item_tracker_db) and then ran python .\manage.py makemigrations python .\manage.py migrate I have also tried: python manage.py migrate --run-syncdb However, when I go to the admin page for django I can still see the old model I used to have, and I cannot see the new model. Whenever I click on the old model that should not be there, I get this error: OperationalError at /admin/jobs/selenium_watcher_item_db/ no such table: jobs_selenium_watcher_item_db Request Method: GET Request URL: http://10.0.0.233:8000/admin/jobs/selenium_watcher_item_db/ Django Version: 3.1.1 Exception Type: OperationalError Exception Value: no such table: jobs_selenium_watcher_item_db There is no mention of "selenium_watcher_item_db" in my code anywhere after I replaced it with the new item, I tried everything I could think of other than restarting. -
I keep getting this error when i want to query data from a model in mysql database : AttributeError: 'str' object has no attribute 'utcoffset'
This is the code from my Django shell from Inec_results.models import PollingUnit, Lga local = Lga.objects.all() print(local) And I get this error all the time I try to query that model. I'm new to Django please help me out Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\db\models\query.py", line 256, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\db\models\query.py", line 262, in __len__ self._fetch_all() File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\db\models\query.py", line 1354, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\db\models\query.py", line 68, in __iter__ for row in compiler.results_iter(results): File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\db\models\sql\compiler.py", line 1149, in apply_converters value = converter(value, expression, connection) File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\db\backends\mysql\operations.py", line 311, in convert_datetimefield_value value = timezone.make_aware(value, self.connection.timezone) File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\utils\timezone.py", line 262, in make_aware if is_aware(value): File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\utils\timezone.py", line 228, in is_aware return value.utcoffset() is not None AttributeError: 'str' object has no attribute 'utcoffset' -
Django pip freeze > requirements.txt not getting the exact packages installed in the virtual env
Django pip freeze > requirements.txt not getting the exact packages installed in the virtual env rather it's getting all the packages i have ever installed and it's kinda not what i exactly wants, let me show some image of whats happening there are still more packages below, please what can i do