Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to make connection of Djnago with Mongoeninge(Using MLAB service)
I am not able to make a connection of Djnago code with MongoDB. I am using Mlab as the service. When I connect the code to localhost, it is working completely fine. The error I am getting : (python3.5env) D:\django_tutorial\mankind>py manage.py runserver Traceback (most recent call last): File "D:\python3.5env\lib\site-packages\pymongo\mongo_client.py", line 375, in __init__ self._ensure_connected(True) File "D:\python3.5env\lib\site-packages\pymongo\mongo_client.py", line 940, in _ensure_connected self.__ensure_member() File "D:\python3.5env\lib\site-packages\pymongo\mongo_client.py", line 814, in __ensure_member member, nodes = self.__find_node() File "D:\python3.5env\lib\site-packages\pymongo\mongo_client.py", line 905, in __find_node raise AutoReconnect(', '.join(errors)) pymongo.errors.AutoReconnect: [Errno 11002] getaddrinfo failed During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\python3.5env\lib\site-packages\mongoengine\connection.py", line 125, in get_connection _connections[alias] = connection if connection else connection_class(**conn_settings) File "D:\python3.5env\lib\site-packages\pymongo\mongo_client.py", line 378, in __init__ raise ConnectionFailure(str(e)) pymongo.errors.ConnectionFailure: [Errno 11002] getaddrinfo failed During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "D:\python3.5env\lib\site-packages\django\core\management\__init__.py", line 350, in execute_from_command_line utility.execute() File "D:\python3.5env\lib\site-packages\django\core\management\__init__.py", line 302, in execute settings.INSTALLED_APPS File "D:\python3.5env\lib\site-packages\django\conf\__init__.py", line 55, in __getattr__ self._setup(name) File "D:\python3.5env\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "D:\python3.5env\lib\site-packages\django\conf\__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "D:\python3.5env\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, … -
how to import data to database using django
i am trying to import data from excel sheet to database using django but its not working. excel file is consist of 2 columns headers. id - name i tried the import_export module. models.py from django.db import models # Create your models here. class criminal_type(models.Model): criminal_typeID = models.AutoField(primary_key=True) name = models.CharField(max_length=10) def __str__(self): return str(self.name) resources.py from import_export import resources from .models import criminal_type # from .models import Mouhafazat class criminal_type_resource(resources.ModelResource): class Meta: model = criminal_type admin.py from import_export.admin import ImportExportModelAdmin from django.contrib import admin from .models import criminal_type @admin.register(criminal_type) class CriminalTypeAdmin(ImportExportModelAdmin): pass views.py from django.shortcuts import render from tablib import Dataset # Create your views here. def simple_uploadCriminalType(request): if request.method == 'POST': criminalType = criminal_type_resource() dataset = Dataset() newCriminalType = request.FILES['myfile'] imported_data = dataset.load(newCriminalType.read(),format="xlsx") result = criminalType.import_data(dataset, dry_run=True) # Test the data import if not result.has_errors(): criminalType.import_data(dataset, dry_run=False) # Actually import now return render(request, 'core/simple_upload.html') -
How to limit the model objects based on the attribute in django
I have two models Guest, Room. Guest having the attributes fname(CharField), lname(CharField),room(ForeignKey), mobile_no(IntegerField), address(TextField), doj(DateField), contact_person(CharField). Room having the attributes room_no(IntegerField), room_limit(IntegerField). Now the case is if room_limit(IntegerField)=2, then Need to add the two Guests not more than two Guests. If room_limit(IntegerField)=1 then only can able to add two Guests. How to do it in admin panel in django? -
Python Web Frameworks For Production Level
I have been using Flask for Building REST API on the development level. I want to create REST API at Production Level. So which Python web framework would be Best? These frameworks I saw while searching: CherryPy Flask Django Pyramid TurboGears Pylons Web2py Falcon Bottle Etc. -
Saleor migration faild
I tried to install Saleor but during ./manage.py migrate i get i made superuser but it doesn't work. Traceback (most recent call last): File "./manage.py", line 10, in execute_from_command_line(sys.argv) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 203, in handle fake_initial=fake_initial, File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/contrib/postgres/operations.py", line 19, in database_forwards schema_editor.execute("CREATE EXTENSION IF NOT EXISTS %s" % schema_editor.quote_name(self.name)) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 133, in execute cursor.execute(sql, params) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/db/utils.py", line 89, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/honza/projects/saleor/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in … -
How to integrate my Hyperledger network with my django project?
I am currently creating a django web application that basically involves the use of hyperledger as a blockchain network. I would like to know how can I integrate my hyperledger composer with my django web application? -
How can I get current user in ModelForm init()?
I want to show different contents for each user with different privilege, I'm trying to get current user from init() function in ModelForm class, but failed the code below is my current init() in ModelForm def __init__(self, *args, **kwargs): self.user = kwargs.pop('user',None) super(MyForm, self).__init__(*args, **kwargs) but self.user only works after the form has been sent, like in is_valid() function or in clean_data() function I always get "None" value of self.user in init() Should I keep trying to get current user in ModelForm init(), or maybe there is a better way to implement that funtionality? -
Django - RuntimeError: populate() isn't reentrant in server
I am getting error on server . What can be cause to this error ? I think this error Target WSGI script '/home/demo/wsgi.py' cannot be loaded as Python module is the problem ,but not sure wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") application = get_wsgi_application() Error: mod_wsgi (pid=2698): Target WSGI script '/home/demo/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=2698): Exception occurred processing WSGI script '/home/demo/wsgi.py'. Traceback (most recent call last): File "/home/demo/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/demo/demoenv/lib/python3.4/site- packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/home/demo/demoenv/lib/python3.4/site- packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/demo/demoenv/lib/python3.4/site- packages/django/apps/registry.py", line 78, in populate raise RuntimeError("populate() isn't reentrant") Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace. Not Found: /some/lookbook/1358251721.jpg Not Found: /some/lookbook/ Not Found: /favicon.ico Can anyone help me to solve this error ? What can be the problem ? -
how to add ads.txt in django project?
I have one django project and want to add the ads.txt to the host root of the domain. I tried the following steps and not sure if my operation is right. Can any one confirm? Thx! In the template file, I added the ads.txt and in the view.py and url.py file, I added the following: def adstxt(request): return render (request, "xxx/ads.txt") urlpatterns = [ path("ads.txt/", views.adstxt, name="ads.txt"), ] -
Password Reset Custom Validation Message
I am using In-built reset password of django. Now the problem is that when i enter a email which does not exists in database, It does not give error that email does not exist. How can i give Validation In Django Reset Password. If email does not exist in auth_table # Reset Password path('password-reset/', auth_views.PasswordResetView.as_view( template_name='commons/password_reset/password_reset.html' ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='commons/password_reset/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='commons/password_reset/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( template_name='commons/password_reset/password_reset_complete.html' ), name='password_reset_complete'), -
Best time to install third-party packages in a web application?
During development, what is the best time to install third-party packages (like Rails Devise or Django AllAuth) in a web application? What is the best time to integrate the web application with external services (like Twilio, Mailgun and so on)? When developing web applications (Ruby on Rails and Django in my case) I normally try to install third-party packages (like Raild Devise, Django AllAuth, etc.) and integrate my app with external services (like Twilio and MailGun) as soon as possible (mainly to check that everything is working fine). I noticed that most of these thirdy-party packages and services get "muted" during development (by mocking the actual services) and can actually be ignored until the app is ready for staging so I wonder if it could be better to delay this part of my work until I actually need it. How do you deal with this topic? Do you install third-party packages and integrate external services as soon as possible or as late as possible? Is there any specific reason to prefer a way over the other? Is there any accepted "best practice" regarding this topic? -
django authenticate return none at occasionally and check_password return false at occasionally too
On the way to learning django, I encountered a problem. When Django uses authenticate to authenticate users, occasional failures occur. The same username and password can sometimes succeed, sometimes fail, but not always fail. So I feel very troubled. When I debug locally, everything is normal and deployed to the server. Later, after reading the relevant articles, I rewrote authenticate, trying to use check_password to judge whether the account is legitimate, but it still fails occasionally. The same set of account passwords, check_password occasionally returns false, and then I looked through the data to see that make_password can be fixed to generate a password, I tried to generate a fixed password, and then through. After encryption, the password is directly compared with the password in the database to get the user's legitimate data. However, it fails again. Make_password is normal for debugging on my local machine, and the output on the server is different after each password is encrypted. This may also be the reason why authenticate and check_password can not be used. Most importantly, everything is normal for me locally. Doubt is my server reason, I do not know if I have encountered the same problem, the server is … -
zappa manage command with create superuser not working
I have a Django app I just deploy on lambda with Zappa and also added the vpc setting and changes my database in django setting but when i try to create superuser with zappa its not working here my django setting: i am usin aws rds with postgres:: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'singup', 'user': 'rcrahul60', 'password':'rcrahul60', 'host':'singup.chye0chzxgzg.ap-south-1.rds.amazonaws.com', 'port':'5432' } } here my error when running: zappa manage dev createsuper or any manage command [START] RequestId: db269143-0cca-4241-a495-7451b2bd5953 Version: $LATEST [DEBUG] 2019-02-11T08:13:55.173Z db269143-0cca-4241- a495-7451b2bd5953 Zappa event: {'manage': 'createsuperuser'} could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? : OperationalError -
How to check the default cache? Django 1.11
I have the following algorithm. Need to implement it. But I can't do it, because I have never worked with a cache before. When you click on the button Get users data in the admin panel creates a file user_data.xlsx in the root of project. Check if the data is forming? __Yes: we redirect the admin on the page with the words 'Data is forming, try in 10 minutes.' __No: ____ Are the data is formed? ______ Yes: return lines '..........' ______ No: write in cache (for 1 hour) that 'the data are formed'; run asynchronously get_user_data (), at the end of the execution we write in the cache (1 hour.) that `the data is formed` and we remove from the cache the key `the data are formed` I tried to implement it, but it works incorrectly( views.py def get_light_cache(request): cache1 = cache['default'] cache1.set('my_key', "Data is forming") #Check if data is forming? if cache1.get('my_key'): #Yes. we redirect the admin on the page with the words "Data is forming, try in 10 minutes." return HttpResponse("Data is forming, try in 10 minutes.") if cache1.get('my_key', None) == None: #No. if cache1: # Is the data formed? Yes. #return these lines filename = 'user_data.xlsx' … -
Conditional bulk update in Django using grouping
Suppose I have a list of transactions with the following model definition: class Transaction(models.Model): amount = models.FloatField() client = models.ForeignKey(Client) date = models.DateField() description = models.CharField() invoice = models.ForeignKey(Invoice, null=True) Now I want to create invoices for each client at the end of the month. The invoice model looks like this: class Invoice(models.Model): client = models.ForeignKey(Client) invoice_date = models.DateField() invoice_number = models.ChareField(unique=True) def amount_due(self): return self.transaction_set.aggregate(Sum('amount')) def create_invoices(invoice_date): for client in Client.objects.all(): transactions = Transaction.objects.filter(client=client) if transactions.exists(): invoice = Invoice(client=client, number=get_invoice_number(), date=invoice_date) invoice.save() transactions.update(invoice=invoice) I know I can create all the invoices with a bulk create in 1 query with bulk create, but I would still have to the set the invoice field in the transaction model individually. Is it possible to set the invoice field of all the Transaction models with a single query after I've created all the invoices? Preferably in using the ORM but happy to use raw SQL if required. I know I can also use group by client on the transaction list to get the total per client, but then the individual entries are not linked to the invoice. -
Postgres TrigramDistance search with error : django.db.utils.ProgrammingError: operator does not exist: text <-> unknown
Could someone help me on this ? What I would like is to run TrigramDistance search on the 'name ' field of my model. I am running this script in my view: Profile.objects.annotate(distance=TrigramDistance('name', test),).filter(distance__lte=0.7).order_by('distance') The model: class Profile(models.Model): ID = models.IntegerField(unique=True, primary_key=True) name = models.CharField(max_length=200) sfid = models.CharField(max_length=200) hasArticle = models.CharField(max_length=3) gender_guessed = models.CharField(max_length=5) age = models.CharField(max_length=5) email = models.CharField(max_length=100) profile = models.TextField() def __str__(self): return "{}".format(self.name) But I am getting this Error message: django.db.utils.ProgrammingError: operator does not exist: text <-> unknown LINE 1: ...profile"."profile", ("landingpage_profile"."name" <-> 'kerry... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. Thank you! -
Sitemap Generation: Update lastmod/last_published_at of Page Manually
I have a PublicationsPage and a PublicationPage class. The PublicationsPage shows a list of its direct children and renders them in a short preview list at http://mysite/publications. class PublicationsPage(Page): # ... def get_context(self, request): context = super().get_context(request) publications = PublicationPage.objects.child_of(self).live() context['publications'] = publications return context This means whenever a new PublicationPage is added/deleted/modified the list updates accordingly. But since I am not updating the PublicationsPage the lastmod/last_published_at attribute of the /publications location never changes. Wouldn't this be missleading for a search engine? A really hacky attempt could be to update the last_published_at date of the parent page every time I touch a child entry. class PublicationPage(Page): # ... def save(self, *args, **kwargs): result = super().save(*args, **kwargs) from datetime import datetime parent_page = self.get_parent() parent_page.last_published_at = datetime.now() parent_page.save() return result Any other suggestions? -
Converting JSON response observable to angular (typescript) object array
I have a service API that pulls data from Django-REST. The returned JSON looks like: [ { "manufacturer": "Mfg", "model": "Model", }, { "manufacturer": "Mfg2", "model": "Model2", } ] The service API function getData returns: return this.httpClient.get(`${this.apiURL}/data/`); Note I am using ListAPIView in Django, and I have verified that the above URL returns the JSON object shown above (though I have to add ?format=json to get the raw data outside of Django's APIView). I then have an angular component that calls the service API function to convert the observable to an array of objects: export class Data implements OnInit { private records = Array<object> = []; ... constructor(private apiService: ApiService) {} ngOnInit() { this.getData(); } public getData() { this.apiService.getData().subscribe((data: Array<object>) => {this.records = data}); There are no error or warnings, but in the component's HTML file when I try to access the record array it always has a length of 0. For example, the following will print "0" and an empty table. <P> {{ records.length }}</P> <table> <tr> <th>Manufacturer</th> </tr> <tr *ngFor="let record of records"> <td> {{ record.manufacturer }} </td> </tr> </table> What am I missing? -
How to get google-site-verification meta tag in google through CLI or Python Script Without UI?
How can I create google-site-verification meta tag and get the id of it through python script or cli without using any UI ? -
CANNOT connect to SQL Server from Django on Heroku
My website will just load an existing table (brand) from SQL server and display to index page. I'm able to run the website on my machine without any problem, but it seems like the table doesn't exist when I deploy the project to Heroku. (The deploy is working normally if the website doesn't connect to the SQL Server.) These are my settings: runtime.txt python-3.7.0 Procfile web: gunicorn avarin_heroku.wsgi --log-file - settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': DB_DEFAULT_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'HOST': DB_HOST, 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'unicode_results': True, } } } models.py class Brand(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=60) class Meta: managed = False db_table = 'brand' views.py from .models import Brand def index(request): brand = list(Brand.objects.all().values()) context = { 'brand': brand } return render(request, 'index.html', context) I added 2 build packs on Heroku https://github.com/heroku/heroku-buildpack-apt heroku/python In my Aptfile unixodbc unixodbc-dev python-pyodbc libsqliteodbc In my requirements.txt django pyodbc gunicorn django-heroku django-pyodbc-azure The package has been built successfully, but the website give this error ProgrammingError at / relation "brand" does not exist LINE 1: SELECT "brand"."id", "brand"."name" FROM "brand" Please help! Thanks!! -
fix error KeyError: 'id' in import_export django package while importing excel file
i am trying to import excel file into sqlite 3 database using import_export package in django. excel file consiste of 2 columns : id:(empty values) name:(contains values) its not working and display the below error: Errors Line number: 1 - 'id' None, smugling Traceback (most recent call last): File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\resources.py", line 492, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\resources.py", line 269, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\resources.py", line 263, in get_instance return instance_loader.get_instance(row) File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\instance_loaders.py", line 31, in get_instance field = self.resource.fields[key] KeyError: 'id' Line number: 2 - 'id' None, kidnap Traceback (most recent call last): File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\resources.py", line 492, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\resources.py", line 269, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\resources.py", line 263, in get_instance return instance_loader.get_instance(row) File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\instance_loaders.py", line 31, in get_instance field = self.resource.fields[key] KeyError: 'id' i follow these steps : create class in models.py create resources in resources.py create class admin in admin.py create function in views.py models.py from django.db import models # Create your models here. class criminal_type(models.Model): criminal_typeID = models.AutoField(primary_key=True) name = models.CharField(max_length=10) def __str__(self): return str(self.name) resources.py from import_export import resources from .models import criminal_type class criminal_type_resource(resources.ModelResource): class Meta: model = criminal_type … -
How to generate Bills with barcode or QRCode in Django using random numbers?
I would like to know how to generate bills with barcode or qrcode using random numbers. Thus, I have the models Orders, Order_lines and product. Notice Orders in linked to Customer model. -
Internal Server Error due to empty_like method already has a docstring
Currently I am facing a problem. Ok let me share it. I have deployed this project into server (apache2) which is working fine as well as all operation work successfully. But suddenly it's getting Internal server error basically when login. When I have downloaded the log it shows me RuntimeError: empty_like method already has a docstring. When I again restart my server it's again work smoothly. But I think this need a permanent solution. I also like to share the full trace of the log. Internal Server Error: / Traceback (most recent call last): File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response resolver_match = resolver.resolve(request.path_info) File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/urls/resolvers.py", line 498, in resolve for pattern in self.url_patterns: File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/urls/resolvers.py", line 540, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/urls/resolvers.py", line 533, in urlconf_module return import_module(self.urlconf_name) File "/opt/python/ai_rest_env/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in … -
Django with Mod_WSGI on ubuntu 18.04 with Apache2 Permission denied for media/
I'm trying to deploy my Django(1.10) project on Ubuntu 18.04 with Apache2 using Mode_WSGI I have set up my project folder inside home as Fetchors directory and add permissions to it as: total 40 drwxr-xr-x 6 abdul abdul 4096 Feb 10 15:48 . drwxr-xr-x 5 root root 4096 Feb 11 04:40 .. -rw------- 1 abdul abdul 3930 Feb 11 02:14 .bash_history -rw-r--r-- 1 abdul abdul 220 Apr 4 2018 .bash_logout -rw-r--r-- 1 abdul abdul 3771 Apr 4 2018 .bashrc drwx------ 3 abdul abdul 4096 Feb 10 15:37 .cache drwx------ 3 abdul abdul 4096 Feb 10 15:34 .gnupg -rw-r--r-- 1 abdul abdul 807 Apr 4 2018 .profile drwx------ 2 abdul abdul 4096 Feb 10 15:34 .ssh drwxrwxr-x 9 abdul www-data 4096 Feb 11 06:27 Fetchors And here are the permissions inside media directory: total 16 drwxrwxr-x 4 abdul www-data 4096 Feb 10 15:37 . drwxrwxr-x 9 abdul www-data 4096 Feb 11 06:27 .. drwxrwxr-x 2 abdul www-data 4096 Feb 10 15:37 driver_image drwxrwxr-x 2 abdul www-data 4096 Feb 10 15:46 product_image I'm creating a proudct object which need to save the product image inside product_image folder but it says: [Errno 13] Permission denied: 'media/product_image' How can I fix this issue? Thanks … -
One to one class not updating in django
I am relatively new to Django and have been kinda struggling. These are my three models below: class Site(models.Model): siteID = models.CharField(max_length=255, primary_key=True) class EndDevice(models.Model): class Meta: unique_together = ("edevID", "siteID") edevID = models.CharField(max_length=255) siteID = models.ForeignKey(Site, on_delete=models.CASCADE) deviceCategory = models.BigIntegerField() class ThirdCombi(models.Model): siteID = models.OneToOneField(Site, on_delete=models.CASCADE, primary_key=True) endDevice = models.TextField() I am trying to make a table where one siteID displays all the edevID, which is the third model here. This does work using the following serializers.py class CombiSerializer(serializers.ModelSerializer): class Meta: model = ThirdCombi fields = ("siteID", "endDevice") def serialize(devices): d_list = [] fields = ['edevID', 'siteID', 'deviceCategory'] for device in devices: d_list.append(model_to_dict(device, fields=fields)) return d_list And the views.py as follow: class CombiView(generics.RetrieveUpdateDestroyAPIView): queryset = ThirdCombi.objects.all() serializer_class = CombiSerializer def get(self, request, *args, **kwargs): try: s1 = Site.objects.get(siteID=kwargs["pk"]) devices = EndDevice.objects.filter(siteID=s1) a_site, created = ThirdCombi.objects.get_or_create(siteID=s1, endDevice=CombiSerializer.serialize(devices)) return Response(CombiSerializer(a_site).data) except Site.DoesNotExist: return Response( data={ "message": "Site with id: {} does not exist".format(kwargs["pk"])}, status=status.HTTP_404_NOT_FOUND) But once there is an update in EndDevice and I reload the page it gives me an integrity error and if I put an exception to integrity error, I cannot see the changes made in EndDevice reflected in ThirdCombi. Any help will be appreciated in order to …