Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter results from ansible tower api query
Using postman, I need to only show results where name=TestWorkflow Here are results returned for my query: Get http://ansible-awx.pxdtools.io:8000/api/v2/workflow_job_template_nodes/ { "results": [ { "id": 1323, "summary_fields": { "workflow_job_template": { "id": 121, "name": "TestWorkflow", } } }, { "id": 29, "summary_fields": { "workflow_job_template": { "id": 61, "name": "Livraison en TEST", }, } } ] } i already tried many of these filters : https://docs.ansible.com/ansible-tower/latest/html/towerapi/filtering.html This query does not work because name is inside results/summary_fields Get http://ansible-awx.pxdtools.io:8000/api/v2/workflow_job_template_nodes/?name=TestWorkflow { "detail": "WorkflowJobTemplateNode has no field named 'name'" } the expected results i want will be { "results": [ { "id": 1323, "summary_fields": { "workflow_job_template": { "id": 121, "name": "TestWorkflow", } } } ] } -
What should I do to render profile.html with form have information of 2 tables in database?
I had a extended table from User model in Django is userinfo. I created form with list of field: 'first_name', 'last_name', 'date_of_birth', 'gender', 'address', 'phone_number', 'email'. And I had a trouble with model in Meta class in forms.py UserInfo Model class UserInfor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) date_of_birth = models.DateField() gender = models.CharField(max_length=10) address = models.CharField(max_length=255) phone_number = models.CharField(max_length=10) avatar = models.ImageField(upload_to='profile-image', blank=True) def __str__(self): return self.user.username forms.py from django import forms from django.forms import ModelForm from .models import UserInfor, User class ProfileForm(ModelForm): class Meta: model = User, UserInfor fields = ['first_name', 'last_name', 'date_of_birth', 'gender', 'address', 'phone_number', 'email'] widgets = { 'first_name': forms.TextInput(attrs={'type': 'text', 'placeholder': 'First Name', 'class': 'form-control input-md'}), 'last_name': forms.TextInput(attrs={'type': 'text', 'placeholder': 'Last Name', 'class': ' form-control input-md'}), 'date_of_birth': forms.DateInput(attrs={'placeholder': 'Date of Birth', 'class': 'form-control input-md'}), 'gender': forms.RadioSelect(choices=[('nam', 'Nam'), ('nữ', 'Nữ'), ('khác', 'Khác')]), 'address': forms.TextInput(attrs={'type': 'text', 'placeholder': 'Address', 'class': 'form-control input-md'}), 'phone_number': forms.TextInput(attrs={'placeholder': 'Phone Number', 'class': 'form-control input-md'}), 'email': forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control input-md'}), } labels = { 'first_name': "Họ", 'last_name': "Tên", 'date_of_birth': "Ngày sinh", 'gender': "Giới tính", 'address': "Địa chỉ", 'phone_number': "Số điện thoại", 'email': "Email", } -
Django: .annotate gives back unexpected results
Currently, I have these two query sets: ( Event.objects.filter(organizer=1) .values('pk', 'organizer') .annotate( sold_tickets=Count('attendees', filter=Q(attendees__canceled=False)) ) .order_by('organizer') ) ( Event.objects.filter(organizer=1) .values('pk', 'organizer') .annotate(available_tickets=Coalesce(Sum('tickets__quantity'), 0)) .order_by('organizer') ) Results are: <EventQuerySet [{'pk': 6, 'organizer': 1, 'sold_tickets': 1}, {'pk': 1, 'organizer': 1, 'sold_tickets': 529}, {'pk': 5, 'organizer': 1, 'sold_tickets': 1}, {'pk': 4, 'organizer': 1, 'sold_tickets': 2}]> <EventQuerySet [{'pk': 1, 'organizer': 1, 'available_tickets': 1721}, {'pk': 4, 'organizer': 1, 'available_tickets': 30}, {'pk': 5, 'organizer': 1, 'available_tickets': 10}, {'pk': 6, 'organizer': 1, 'available_tickets': 20}]> Now my idea was to combine these. However, I always get unexpected and wrong numbers in my query: ( Event.objects.filter(organizer=1) .values('pk', 'organizer') .annotate( available_tickets=Coalesce(Sum('tickets__quantity'), 0), sold_tickets=Count('attendees', filter=Q(attendees__canceled=False)) ) .order_by('organizer') ) Here the result <EventQuerySet [{'pk': 6, 'organizer': 1, 'available_tickets': 20, 'sold_tickets': 2}, {'pk': 1, 'organizer': 1, 'available_tickets': 1765746, 'sold_tickets': 2116}, {'pk': 5, 'organizer': 1, 'available_tickets': 10, 'sold_tickets': 1}, {'pk': 4, 'organizer': 1, 'available_tickets': 60, 'sold_tickets': 4}]> Is there something about .annotate that I don't understand? -
django - primary key in search_fields?
I have thousands of objects for a django model in my database and I want to be able to search by primary key. I know I can just go to /admin/my_app/my_model/pk/ to enter into the admin for that particular object, but I want to be able to see it in the search results, to see all the display fields. When I add 'pk' or 'id' to the search_fields, I get this error: Cannot resolve keyword 'pk' into field. Choices are: ... So I'm guessing it's not possible straight away but wonder if there is a workaround? -
Error during template rendering: __str__ returned non-string (type NoneType)
I have a problem I can have the rendering of all the pages with my database empty. But when I introduce data I have a problem: Error during rendering template str returned non-string (type NoneType). below one of the codes that generate this type of error at line of render. Thank you in advance. models.py class Filiere(models.Model): departement=models.ForeignKey( "Departement", verbose_name="Département", on_delete=models.CASCADE) code_filiere=models.CharField("Code de la filière", max_length=10, unique=True) libelle_filiere=models.CharField("Libellé de la filière", max_length=100) def __str__(self): self.libelle_filiere #Description d'une option class Option(models.Model): filiere=models.ForeignKey("Filiere", on_delete=models.CASCADE, verbose_name='Filière') niveau=models.ManyToManyField("niveau", through='Posseder_Niveau') code_option=models.CharField("Code de l'option", max_length=6,unique=True,) libelle_option= models.CharField("Libelle de l'option", max_length=100) effectif=models.IntegerField("Effectif", default=0, validators=[ MinValueValidator(limit_value=0 , message=" Attention votre option a un effectif négatif"), ]) def __str__(self): return self.libelle_option class Posseder_Niveau(models.Model): niveau=models.ForeignKey("Niveau", on_delete=models.CASCADE) option=models.ForeignKey("Option", on_delete=models.CASCADE) class Niveau(models.Model): libelle_niveau=models.CharField("Libellé du niveau", max_length=25, unique=True) semestre=models.ManyToManyField("Semestre", through="Posseder_Semestre") cursus=models.ForeignKey('Cursus', on_delete=models.CASCADE) def __str__(self): self.libelle_niveau forms.py class Option_Form(forms.ModelForm): class Meta: model=Option # exclude=("niveau",) fields='__all__' def __init__(self, *args,**kwargs): super().__init__(*args, **kwargs) for _, value in self.fields.items(): value.widget.attrs['placeholder']=value.label value.widget.attrs['class'] = 'form-control required' views.py def option(request): # import ipdb; ipdb.set_trace() f=Option_Form() if request.method=="POST": f=Option_Form(request.POST) if f.is_valid(): f.save() else: return render(request, 'configuration/ajout_option.html', {'f': f}) traceback C:\Program Files\Python37\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars … -
In Django model, how to save DateTime for two different timezones at the same time when saving one field with auto_now_add = True option?
I am a Django model which has an auto current time saving DateTime field. I want to add another DateTime field for another timezone which time difference with the previous DateTime field is exact time difference between two time zones. This is how I have done. I think there should be better way to get it done. It's Django, right? class IcecreamManager(models.Manager): def create_icecream(self, name=None, qty=None): icecream = self.create(name=name, qty=qty) icecream.create_date_kr = buy.create_date + datetime.timedelta(hours=9) icecream.save() return iceream class Icecream(models.Model): name = models.CharField(max_length=100) qty = models.IntegerField(default=0) create_date = models.DateTimeField(auto_now_add=True) create_date_kr = models.DateTimeField(null=True) objects = BuyFourManager() >>> Icecream.objects.create_icecream(name='Vanila', qty=3) -
Django: Check multiple conditions before save model
This is my models.py: class Department(models.Model): name = models.CharField(max_length=20, blank=False, null=False, verbose_name='Department') def __str__(self): return '{}'.format(self.name) class Users(models.Model): name = models.CharField(max_length=20, blank=False, null=False, verbose_name='Name') last_name = models.CharField(max_length=20, blank=False, null=False, verbose_name='Last Name') department = models.ForeignKey(Department, related_name='user_department', on_delete=models.CASCADE) def __str__(self): return '{} {} - {}'.format(self.name, self.last_name, self.department) class WeeklyCheck(models.Model): department = models.ForeignKey(Department, related_name='weeklycheck_department', on_delete=models.CASCADE) start_date = models.DateField(blank=False, null=True, verbose_name='Start date') end_date = models.DateField(blank=False, null=True, verbose_name='End Date') active = models.BooleanField(default=True, verbose_name='Active?') def __str__(self): return '{} / {} to {} - {}'.format(self.department, self.start_date, self.end_date, self.active) class Attendance(models.Model): user = models.ForeignKey(Users, related_name='attendance_user', on_delete=models.CASCADE) date = models.DateField(blank=False, null=True, verbose_name='Date') check = models.BooleanField(default=True, verbose_name='Check') def __str__(self): return '{} / {} / {}'.format(self.user, self.date, self.check) def clean(self): qs = WeeklyCheck.objects.filter(start_date__lte=self.date, end_date__gte=self.date, active=True) department_a = Users.objects.filter(department__name='Department A') if not qs and department_a: qs = WeeklyCheck.objects.filter(start_date__lte=self.date, end_date__gte=self.date, active=True) department_b = Users.objects.filter(department__name='Department B') if not qs and department_b: qs = WeeklyCheck.objects.filter(start_date__lte=self.date, end_date__gte=self.date, active=True) department_c = Users.objects.filter(department__name='Department C') if not qs and department_c: raise ValidationError('You can not check! The week is not active.') I have departments (Department) that have users (Users). Each department marks weeks (WeeklyCheck) that have a start date and end date and may or may not be active. Each user checks on a certain date (Attendance). What I want … -
re.findall() returning empty tuples [duplicate]
This question already has an answer here: re.findall behaves weird 2 answers I have a regex '[-][0-9],\s*[0-9]*(?!(km)|(Km)|(metres?)|(miles?)|(m)|(mi))'. When I use this on regexr.com it matches '558,21' and other patterns. but if I am using re.findall() in python re.findall( '[-]*[0-9]*,\s*[0-9]*(?!(km)|(Km)|(metres?)|(miles?)|(m)|(mi))' , text) it is returning me this as the output even though '558,21' is present in text variable: [('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', '')] What might be the reason for it? -
Specify media type in post request in Django rest (tests)
I'm writing some tests for my REST API and I have some struggles with POST requests I have this data to send : data = { "patient": 34, "measure_cat": 52, "measure_type": "1", "date": "2019-06-11", "value": '', "unit": '', "nnu_value": "3" } I've built my header and POST request the following way : headers = {'Authorization': 'Token '+ self.token.key, 'content_type':'application/json', 'Accept-Language' : 'en'} response = requests.post('http://127.0.0.1:8000/saveMeasure/', json.dumps(data), headers=headers) And the test is a simple 201 assert : self.assertEqual(response.status_code, 201) The server answers with a HTTP status 415 Unsupported Media Type : Unsupported Media Type: /saveMeasure/ [21/Jun/2019 09:29:47] "POST /saveMeasure/ HTTP/1.1" 415 62 Have I missed a configuration step or something else? I don't know if it is relevant or not but I'm using fixtures as a test database. And this is all the imports I have : import json import requests from rest_framework.authtoken.models import Token from rest_framework.test import APIRequestFactory, APITestCase, APIClient -
Retrieve json web data in python
For my website with Django, is it possible in python to connect to a database on the internet and retrieve measurements. This is my internet database: Thank you for your feedback -
Compare string alphabetically django db
I have a following model: class Page(Model): book = ForeignKey(Book, on_delete=CASCADE) page = IntegerField() start = CharField(max_length=350, db_index=True) end = CharField(max_length=350, db_index=True) How do I query db in order to get pages that "contain" a given word? page1 = Page.objects.create(start='beaver', end='brother') page2 = Page.objects.create(start='boy', end='brother') Page.objects.filter("breast" between start and end) should return page1 and page2. Page.objects.filter("beast" between start and end) should return nothing. Page.objects.filter("block" between start and end) should return only page1, since block is alphabetically after beaver and before brother. Search should be case-insensitive. -
Postgresql truncate table with foreign key constraint
Currently I am trying to truncate tables which have foreign key constraint on Postgresql 11.3. I tried doing this BEGIN; SET CONSTRAINTS ALL DEFERRED; TRUNCATE tableA; COMMIT; but received error ERROR: cannot truncate a table referenced in a foreign key constraint DETAIL: Table "xxx" references "tableA". HINT: Truncate table "xxx" at the same time, or use TRUNCATE ... CASCADE. Doesn't SET CONSTRAINTS ALL DEFERRED would turn off the foreign key constraint check? Are there anyway to truncate a table without triggering foreign key constraint check and not involving CASCADE? -
How to call periodic Celery function from python code with passing runtime args to function?
I have Django project. When it start I need to save periodically some data to file. I can get this data only when the program starts. Now I start thread with this function and pass args to function threading.Thread(target=save_data, args=(dp, conv_handler)).start() But this thread don't die when main process dies. I heard that de-facto solution for such tasks is CeleryBeat, but can't figure out how to pass args to function that runs in celery worker. How can I solve such problem? -
Prefetch 3 level hierarchy of objects
I have the following model structure. If i want to prefetch the objects of ModelC containing the objects of ModelB i do ModelC.objects.prefetch_related('ModelB'). But how can i fetch the objects of ModelA contained in ModelB as well. I trided something like ModelC.objects.prefetch_related('ModelB')..prefetch_related('ModelA'). but does not work class ModelA: class ModelB: ModelA = models.ForeignKey( ModelA, on_delete=models.CASCADE, db_constraint=False) class modelC: ModelB = models.ManyToManyField('ModelB', blank=True) -
WebSocket opening handshake timed out in https
WebSocket connection to 'wss://ip_address:8008/ws/events?subscribe-broadcast' failed: WebSocket opening handshake timed out its timed out only when open UI in HTTPS, in HTTP its working... I have generated the certificate using OpenSSL in ubuntu my uwsgi configuration is socket = /tmp/uwsgi.sock chmod-socket = 666 socket-timeout = 60 chdir = <django path> wsgi-file = <django_path>/wsgi.py virtualenv = <path_to_virtualenv> vacuum = true enable-threads = true threads=500 startup-timeout = 15 graceful-timeout = 15 http-socket=<my_ip>:8008 http-websockets=true my nginx configuration is server { listen <ip>:80 default; listen <ip>:443 ssl http2 default_server; ssl_certificate <path>/generate_crt.crt; ssl_certificate_key <path>/generated_key.key; client_body_buffer_size 500M; client_body_timeout 300s; keepalive_timeout 5000; client_max_body_size 700M; access_log syslog:server=unix:/dev/log; root /tmp/MVM_APPS/angularjs/dist; index index.html index.htm; server_name localhost; location /api { uwsgi_pass unix:///tmp/uwsgi.sock; include uwsgi_params; uwsgi_read_timeout 120; uwsgi_send_timeout 1000; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection upgrade; proxy_pass http://<ip>:8008; proxy_read_timeout 86400; } location /static { alias /<path>/static; } location / { try_files $uri $uri/ /index.html; } } I am using Django with WS4redis package. -
How to use dynamic variable (variable.variable.variable) in jinja2 with django
"I want to display a name instead of an ID in my template. I am using jinja2 and django2.2.1 with python3. I want to use a dynamic variable in my template. I have a dictionary of id and name and I want to display name of related ID in my template view. name_dict = { 1 : 'name 1' 2 : 'name 2' } return name_dict "In my template, I have another object which is table_data, Now in my view, I want to do Like This" table_data = object with another table data {% for data in table_data %} #This does not gives any error but not printing name name_dict.data.id #It gives an error name_dict[data.id] {% endfor %} "What should I do to display name which is in 'name_dict' " Thanks in advance -
AuthCanceled Exception Raised on google-oauth2 JWT pair
Am using rest_social_auth package for social auth in django. while creating jwt pair key from google-oauth2 code it is raising AuthCanceled Exeception with error text : "Authentication process canceled". It is showing this exception from postman but it works fine with Vuejs vue-authenticate package. Am not getting why it is working with vuejs but not working with postman I expect the jwt pair key , but the output is AuthCanceled Exception with text "Authentication process canceled" -
Error in saving an array of images sent from front-end to Django backend
I am facing a problem while trying to send an array of images from the frontend(ReactJS) to the backend(Django). An object instance is not being saved at the backend because of the mandatory ArrayField in the Django Model. I am using PostgreSQL with Django. That's why I am able to use ArrayField. I have already tried using a built-in (to_internal_value) method in the serializer to try to save the data I receive from the frontend. https://www.django-rest-framework.org/api-guide/fields/ The following is a portion of the Django Model I have made: ... lot_location_market = models.CharField(max_length=30, null=True, blank=False) quality = models.CharField(max_length=250, null=True, blank=True) remarks = models.CharField(max_length=250, null=True, blank=True) layer_image = models.ArrayField(models.FileField(upload_to=get_file_path, null=False, blank=False)) I am using a Model Serializer. Serializer Code: class FooSerializer(serializers.ModelSerializer): product_name = serializers.CharField(source='product.name', read_only=True) class Meta: model = Foo fields = ( ... 'lot_location_market', 'remarks', 'quality', 'layer_image', ) I am using CreateAPIView (it extends CreateModelMixin and GenericAPIView) The following is View for creating an instance of Foo from the API class Foo(generics.CreateAPIView): permission_classes = (permissions.IsAuthenticated,) lookup_field = 'id' serializer_class = FooSerializer def get_queryset(self): return Foo.objects.all() def perform_create(self, serializer): serializer.save() -
Unable to send Email attachement through Django EmailMultiAlternatives
I have to send Email to client(s) by using Django EmailMultiAlternatives, Email could have an attachment with it. But when i attach the file it does not show up in the receiving inbox or sent box of the email host. Though I am able to successfully send the email. Below is the code views.py def send_email(request, in_id, pr_id): invite_data = Invite.objects.get(id=in_id) person_data = PersonData.objects.get(id=pr_id) context = {'invite_data': invite_data, 'person_data': person_data} subject = "Come Join us" # email subject email_from = settings.EMAIL_HOST_USER # email from attch = invite_data.invite_attachment # attch = invite_data.invite_attachment to_email = [person_data.person_email] # email to msg = EmailMultiAlternatives() msg.from_email = email_from msg.to = to_email msg.subject = subject msg.body = invite_data.invite_msg attach = request.FILES.get(invite_data.invite_attachment) # try: msg.attach_file=attch, # except Exception as ex: # # logging.error('Send mail failed: %s', ex) # msg.attach_file = attch, html_body = render_to_string("userfiles\email.html") html_template = get_template("userfiles\email.html") plaintext = get_template('userfiles\email.txt') text_content = plaintext.render(context) html_content = html_template.render(context) msg.attach_alternative(html_content, "text/html") # msg.attach_alternative(html_body, "text/html") msg.send() messages.success(request, ("Email Sent !!")) # return redirect("InviteList") return render(request, 'userfiles/email.html', context) email.html <div class='container'> Dear, <h4><u>{{person_data.person_first_name}} {{person_data.person_last_name}}</u></h4><br><br> I am happy to invite you to this event.<br> <h5>Perosnal Message:</h5>{{invite_data.invite_msg}} <br><h5>Event date:</h5> {{invite_data.event_date}} <br><br> {{invite_data.invite_attachment}} <br> <h6>Looking forward to seeing you there</h4> <h4>Have a great day</h4> <br> … -
Get the file size of the uploaded file in Django app
I would like show in the template the size of a file that the user have uploaded. I've see that the file object has the attribute size but, because I'm newbie with Python and the development field, I've been trouble to understand how I can use it. After some test I've developed this script(filesize) to add at the end of the model with which you can upload the file: class FileUpload(models.Model): name = models.CharField( max_length=50, ) description = models.TextField( max_length=200, blank=True, ) file = models.FileField( upload_to='blog/%Y/%m/%d' ) def __str__(self): return self.name @property def filesize(self): x = self.file.size y = 512000 if x < y: value = round(x/1000, 2) ext = ' kb' elif x < y*1000: value = round(x/1000000, 2) ext = ' Mb' else: value = round(x/1000000000, 2) ext = ' Gb' return str(value)+ext Is simple now to call the size of the file. I share this because I hope that is usefull for someone. What I ask is this: there is a better solution? -
Access @property annotation in model
If I have a property like this in my models.py @property def count_card_holders(self): count = 0 for branch in self.branches.all(): count = count + branch.card_holders.count() return count How would I use the count_card_holders() function in my views.py? I can access it just fine in my template by using {{cardholder_detail.branch.count_card_holders}} -
Create multipage pdf file with Python and Django
I have code as follows: for lead_id in lead_ids: language = settings.DEFAULT_CULTURE_MAJOR car = map_lead(lead_id, 0) s_template = 'manager/seller/templates/pdf/windscreen.html' path = "{}".format(settings.STATICFILES_DIRS[0]) context = {'car': car} file_name = "windscreen.pdf" splitted_path = path.split('/') destination_url = "/{0}/{1}/Downloads".format(splitted_path[1], splitted_path[2]) try: html_template = render_to_string(s_template, context) html = HTML(string=html_template, base_url=settings.BASE_DIR) html.write_pdf(stylesheets=[CSS(string='@page { size: A4 landscape; margin: 0.2cm }'), CSS(car["header_css"])], target="{0}/{1}".format(destination_url, file_name)) print("PDF file for lead id {0} created at {1}/{2}. ".format(lead_id, destination_url, file_name)) except Exception as e: print("Something went wrong for lead id {0}. {1}".format(lead_id, str(e))) I want to create one pdf file of many others. The function that I have creates pdf from django template and saves it on download folder. But that is done for every loop iteration, thus if I have 20 iterations there are 20 pdf files created. I dont want that. I want to create only one pdf file and for every iteration I want to create new page on that pdf file. Thus for 20 iterations I would have one file with 20 pages. Any idea how to do that? -
Web API hosting: Python, Django & GDAL." OSError: [WinError 126] The specified module could not be found"
I am trying to host a web API which was written using Python Django. I am facing some issues and I have gone through some of the links like: GeoDjango on Windows: "Could not find the GDAL library" / "OSError: [WinError 126] The specified module could not be found" "[WinError 126]" when runing python manage.py makemigrations Tools used: Windows10- 64 bit; Postgres 10, PostGIS 2, Python 3.5. Downloaded and installed OSGEOW4-64bit. Even I added the path: in settings.py GDAL_LIBRARY_PATH = "C:\OSGeo4W64\bin" I was running this on a virtual environment. Set up the requirements accordingly in that env. File "\myvenv\lib\site-packages\django\contrib\gis\gdal\prototypes\ds.py", line 9, in <module> from django.contrib.gis.gdal.libgdal import GDAL_VERSION, lgdal File "\myvenv\lib\site-packages\django\contrib\gis\gdal\libgdal.py", line 49, in <module> lgdal = CDLL(lib_path) File "\myvenv\lib\ctypes\__init__.py", line 351, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module could not be found -
How to make changes to database(sqlite) after first migration in Django?
I'm new to Django development and I'm currently following a tutorial to make a blog app. During the tutorial, there is a step to create a function to allow new user use deafult.jpg as their avatar. However, I had a typo there. Instead of typing 'default.jpg', I typed 'default.jpb'. Then I migrated into the database. Therefore, when I run the server and try it out, new users who have not set their avatar is using "default.jpb" instead of "default.jpg". Now, how can I change the database to use the right definition? After I found the problem, I corrected my typo in my model and then used the following command: python3 manage.py makemigrations (no changes detected) python3 manage.py migrate (no migrations to apply) then, I decided to delete the migrations in my project then makemigrations again, and I realized that I couldn't make changes that already inside my database. from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' I expect new users who have not set their avatar is using default.jpg that located in my project. -
Execution/Access of deployed django(python) web application on server is not working
I am newbie to django/python, I have developed django application and uploaded it on linux server, after uploading i have successfully deployed the app on server, there are no errors in deployment, Now i want to access that application through web browser but it is not working. It says "This site can’t be reached, it took so long to respond", I don't understand where i am wrong, where the problem is. Please suggest some solution. Thanks. Python 3.5 and django 2.2 i have used for app development, i have used nginx and uWSGI with deployment python3 manage.py check --deploy to deploy the app and it is successfully deployed I am expecting to access that application on web browser but I got "This site can’t be reached 206.81.11.228 took too long to respond. Try: Checking the connection Checking the proxy and the firewall Running Windows Network Diagnostics ERR_CONNECTION_TIMED_OUT"