Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to setup Single Sign-On on different domains using python3-saml and G Suite?
I have two django based applications on two different domains–both are using G Suite as their identity provider (configured as SAML Apps). I want a user that is authenticated in one domain to automatically be authenticated in the other domain without having to log in again. How do I do it with python3-saml and G Suite? -
Django Permission
Hi i am having trouble with Django User object. I have created a group named 'Admin' and this group have the following permission 'can_change_name','can_update_name'. A user 'falcon' belong to group 'Admin' i did this by performing the following query user.groups.add(Group.objects.get(name='Admin)) When i perform the following query i am getting False instead of True. user.has_perm('can_change_name') The above query give me False, i have a doubt why i am getting False even after adding the user into the appropriate group. -
How to install the Django-Simple-Blog package into an existing Django project?
I found a similar question, with this reply: "...django-simple-blog is an app, meaning you install it within an existing project." But I need more explanation. Can someone explain to me how to "install" an app within an existing Django project? And what it means to do so? (I use Pycharm). -
How to get JS file to pull data from database
I am new to Django and am working on a simple project that involves having a form that a user submits and then a dashboard page that gives some nice visual charts summarising the data input by the user. I am using a free template for the dashboard page. It is called black-dashboard by creative tim. In my HTML template there is the following <canvas id="chartBig1"></canvas> this I believe references information in a JS file about the chart to display below is a snippet of the JS file that I think the html references var myChart = new Chart(ctxGreen, { type: 'line', data: data, options: gradientChartOptionsConfigurationWithTooltipGreen }); var chart_labels = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']; var chart_data = [100, 70, 90, 70, 85, 60, 75, 60, 90, 80, 110, 100]; var ctx = document.getElementById("chartBig1").getContext('2d'); The data is static. What is the best way to display these graphs using data that I have saved using models.py . Can I pull the data straight into the JS file? Thank you -
Building ManyToMany Relationship to Custom User Model
I have a blog project. I created custom user model and made a few profile pages to my project. I want to create M2M relationship between user's posts and user for showing at user's page. For example, If I edit a user's profile on admin panel, I should choose this user's post in post list. But why should I do this? They're already related, aren't they? How should I do making relationship? If I can do this I can create following system like Twitter. Because I think It's using ManyToMany relationship. I am using SQLite3 for db. I read a lot of documentation but I couldn't figurate out. post/models.py class Post(models.Model): author = models.ForeignKey("auth.User", on_delete=models.CASCADE, verbose_name="Author") category = models.ForeignKey("Category", on_delete=models.CASCADE, verbose_name="Category Name") sub_category = models.ForeignKey("SubCategory", on_delete=models.CASCADE, verbose_name="Sub-Category Name", related_name="sub_category") title = models.CharField(max_length=50, verbose_name="Story Title") slug = models.SlugField(max_length=55, blank=True, null=True) description = RichTextField(max_length=100000, null=False) image = models.ImageField(upload_to='story_images/', null=True, blank=True, default='') created_date = models.DateTimeField(auto_now_add=True, verbose_name="Created Date") verified_date = models.DateTimeField(auto_now_add=True, verbose_name="Verified Date") active_post = models.BooleanField(default=True) tag = models.ManyToManyField(SubCategory) customUser/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) slug = models.SlugField(max_length=55, blank=True, null=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) country = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) job = … -
Django admin multiple querysets on one page
How to have multiple tables(queryset) on one page in django admin. For example: When i go to the company page, i can see the list of departments in the company, i can also see the list of employees in the company. -
Context Not Printing Django
I'm aware my issue may be to lack of Django knowledge, but I'm trying to pass user input from one form in a view, to another view which will then render that view's HTML page with the given input. I'm redirected fine, but the data is not being displayed. I believe it has something to do with the contexts not being passed properly, but I do not understand what is wrong or how to fix it. views.py def home_view(request, *args, **kwargs): print(args, kwargs) print(request.user) if request.method == 'POST': form2 = PostForm(request.POST) if form2.is_valid(): post = form2.save(commit=False) post.poster = request.user post.content = form2.cleaned_data.get('content') post.title = form2.cleaned_data.get('title') post.syntax = form2.cleaned_data.get('syntax') post.public = form2.cleaned_data.get('public') rand = str(uuid.uuid4())[:6] while Paste.objects.filter(generated_url=rand): rand = str(uuid.uuid4())[:6] post.generated_url = rand form2.save() context = { "poster_name": post.poster, "paste_contents": post.content, "paste_title": post.title, "paste_syntax": post.syntax, "paste_visible": post.public } return HttpResponseRedirect(reverse('details', args=(post.generated_url,)), context) else: form2 = PostForm() return render(request, "home.html", {'form2': form2}) def detail_view(request, *args, **kwargs): if request.user.is_authenticated: if request.method=='POST': form3 = PostForm(request.POST) url = form3.generated_url your_posts = Paste.objects.get(url) context = { 'form3': form3 } return render(request, "page_detail.html", context) return render(request, "paste_detail.html", {'form3': form3}) home.html {% extends "base.html" %} {% block content %} <h1>Your user is {{ request.user }}</h1> <div class="submit_form"> <form … -
Django DeleteView with GET request
I've seen this Q&A: Django DeleteView without confirmation template and this one: Django CSRF token won't show but that doesn't address the built-in intended functionality of the DeleteViewm CBV when issued a GET. From the docs (emphasis mine): https://docs.djangoproject.com/en/2.1/ref/class-based-views/generic-editing/#django.views.generic.edit.DeleteView "If this view is fetched via GET, it will display a confirmation page that should contain a form that POSTs to the same URL." The problem is that as I understand it, the rendered template in response to a GET will not included the RequestContext necessary to include the {% csrf_token %} in the mentioned POST form. I worked around it for the time being by overriding the get() method so that it uses render() to return the page, since it automatically includes the appropriate context. How do I maximally leverage the DeleteView? What am I doing wrong that I need to implement the following code in my view? def get(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) return render(self.request,'mainapp/template_confirm_delete.html') -
DRF: AttributeError: 'str' object has no attribute 'pk'
I am using Django Rest Framework. I have a model TestSuite which has Foreign key relations to the model Team and EmailTemplates. When I do a post() to Test Suite through postman, the data is inserted in the TestSuite table and request works successfully. However, when I do a get() or try to click on the url link from localhost to access TestSuite, it throws below error AttributeError at /dqf_api/test_suite/ 'str' object has no attribute 'pk' error traceback File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.6/contextlib.py" in inner 52. return func(*args, **kwds) File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/rest_framework/viewsets.py" in view 116. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch 495. response = self.handle_exception(exc) File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in handle_exception 455. self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch 492. response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in list 48. return Response(serializer.data) File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in data 768. ret = super(ListSerializer, self).data File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in data 262. self._data = self.to_representation(self.instance) File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in to_representation 686. self.child.to_representation(item) for item in iterable File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in <listcomp> 686. self.child.to_representation(item) for item in iterable File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" … -
Getting files from FormData array in django backend
I try to send POST request. I try to post data (FormData) from javascript which contains array of images The print(request.data) command in my console shows this: <QueryDict: {'title': ['testTitle'], 'text': ['testText'], 'images': [<InMemoryUploadedFile: 486217.jpg (image/jpeg)>, <InMemoryUploadedFile: 344611.jpg (image/jpeg)>, <InMemoryUploadedFile: default.png (image/png)>] }> code in django :models.py class Article(models.Model): title = models.CharField(max_length=120) text = models.TextField() create_time = models.DateTimeField(default=datetime.utcnow, blank=True, null=True) def __str__(self): return self.title class ArticleImage(models.Model): article = models.ForeignKey(Article, related_name='images', on_delete=models.CASCADE) img = models.ImageField(upload_to='article_images/') is_main = models.BooleanField(default=False,blank=True,null=True) create_time = models.DateTimeField(default=datetime.utcnow, blank=True, null=True) def __str__(self): return self.article.title views.py class ArticleMixinView(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin, ...) serializer_class = ArticleSerializer queryset = Article.objects.all() lookup_field = 'id' def post(self, request): print(request.data) new_article = Article.objects.create(title=request.data.get('title'), text=request.data.get('text')) new_article.save() for img in request.data.get('images'): # article_img = ArticleImage(article=new_article,img=File(img), # is_main=False ) # article_img.save() return Response({ 'article': ArticleSerializer(new_article, context=self.get_serializer_context()).data }) Creation of Article object works fine, but I got some problems with this array. What is wrong, or how I can get images from InMemoryUploadedFile objects ???? Please any help. Thank you in forward) -
In a form use a formset, which parent model that is not the form main model, and connect all three models on submit
I have the following models: class Owner(models.Model): name = models.CharField(max_length=255) .... class Contact(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) email = models.EmailField(max_length=255, unique=True) class Entity(models.Model): name = models.CharField(max_length=255) account = models.OneToOneField(Account on_delete=models.CASCADE) .... class Item(models.Model): ... contact = models.ManyToManyField(Contact) entity = models.ForeignKey(Entity, on_delete=models.CASCADE) An Owner has multiple Contact(s). An Item can have multiple Contact(s), and a Contact can have multiple Item(s), basically the Contact is used by multiple Item(s) The Owner is not connected directly to the Item, but thru and Entity, the Entity owns the Item(foreign key). When an user(Owner) add an Item, in the Item form the user/person can add also one or more Contact(s) (email). If the Contact(email) already exist, just add the link between 'Item' and 'Contact', if it doesn't exist create it and create also the connection to the Account. My approach to add the Contact to Item form is to use a formset. class ContactForm(forms.ModelForm): class Meta: model = AccountContact fields = ['email'] ContactFormSet = forms.inlineformset_factory(parent_model=Account, model=Contact, form=ContactForm, max_num=3) class ItemModelForm(forms.ModelForm): .... def __init__(self, *args, **kwargs): self.contact = ContactFormSet( instance=self.instance, prefix='contact', data=self.data if self.is_bound else None, files=self.files if self.is_bound else None, auto_id=False) def save(self, commit=True): # self.contact.save(commit=commit) - the base one I don't know how to … -
Character encoding causing RSA key recognition failure with Django/Docker/GoogleAuth/pythonRSA
I have a persistent error, in this case, when trying to run Django unit tests inside a container. test_1 | Traceback (most recent call last): test_1 | File "/usr/local/bin/django-admin", line 11, in <module> test_1 | sys.exit(execute_from_command_line()) test_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line test_1 | utility.execute() test_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 317, in execute test_1 | settings.INSTALLED_APPS test_1 | File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ test_1 | self._setup(name) test_1 | File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup test_1 | self._wrapped = Settings(settings_module) test_1 | File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ test_1 | mod = importlib.import_module(self.SETTINGS_MODULE) test_1 | File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module test_1 | return _bootstrap._gcd_import(name[level:], package, level) test_1 | File "<frozen importlib._bootstrap>", line 994, in _gcd_import test_1 | File "<frozen importlib._bootstrap>", line 971, in _find_and_load test_1 | File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked test_1 | File "<frozen importlib._bootstrap>", line 665, in _load_unlocked test_1 | File "<frozen importlib._bootstrap_external>", line 678, in exec_module test_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed test_1 | File "/advocate/advocate/settings/test-microservice.py", line 1, in <module> test_1 | from .base import * test_1 | File "/advocate/advocate/settings/base.py", line 378, in <module> test_1 | 'client_x509_cert_url': 'https://www.googleapis.com/robot/v1/metadata/x509/{}'.format(get_env_setting('GS_CLIENT_EMAIL')).replace('@', '%40'), test_1 | File "/usr/local/lib/python3.6/site-packages/google/oauth2/service_account.py", line 193, in from_service_account_info test_1 | … -
Unable to connect to server url from browser django apache
I am deploying a django app with mod_wsgi and apache from my Centos 7 server. I was able to access the ip address for a bit and then when i changed my settings.py in my django app and added ALLOWED_HOSTS = ['<ip address>'] it stopped working and now it's saying unable to connect. This happens as well when i use the actual url in the browser and add that to ALLOWED_HOSTS, and it is also unable to connect. i've tried reverting it back but that doesn't work either. Why is it all the sudden not being able to connect? How do i configure this to accept the url name? I temporarily disabled firewalld and iptables and still unable to connect -
Python Django Import data to Postgres
I am new to Django and wondering how to insert the data from a excel/csv/txt file into Postgres using Django. I was able to successfully connect to database and create a table but ca you guys help me with how to import and export data using Django models -
Why doesn't my volley receive json from django rest api?
So heres my android code and the url should be working but not sure. Did not find any tutorial in this subject so I got stuck! PS im only noob here just trying to get started! private void fetchingJSON() { StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://192.168.43.97/languages", new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("strrrrr", ">>" + response); try { JSONArray array = new JSONArray(response); //traversing through all the object for (int i = 0; i < array.length(); i++) { //getting product object from json array JSONObject product = array.getJSONObject(i); //adding the product to product list dataModelArrayList.add(new testmodel( product.getInt("id"), product.getString("url"), product.getString("name"), product.getString("paradigm") )); setupRecycler(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //displaying the error in toast if occurrs Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); // request queue RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } -
Setup internationalization i18n Django
Following stackoverflow posts and a lot of tutorials to implement i18n internationalization in Django Admin I founded this steps: Command line Install (in the right ENV) Using PIP: pip install python-gettext (I tried this) Using Conda: conda install gettext settings.py MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', #right place 'django.middleware.common.CommonMiddleware', ... ] ...'context_processors': [ ... 'django.template.context_processors.i18n', # Indifferent place ... ] ... TIME_ZONE = 'UTC' # America/Sao_Paulo USE_I18N = True USE_L10N = True USE_TZ = True ugettext = lambda s: s LANGUAGES = ( ( 'en-us', ugettext( 'English' )), ( 'pt-br', ugettext( 'Portuguese' )), ( 'es', ugettext( 'Spanish' )), ) LANGUAGE_CODE = 'en-us' #default ... SITE_ROOT = os.path.dirname( os.path.realpath( __file__ ) ) PROJECT_PATH = os.path.abspath( os.path.dirname( __name__ ) ) LOCALE_PATHS = ( os.path.join( SITE_ROOT, 'locale' ), ) # translation files will be created into 'locale' folder from root project folder urls.py admin.autodiscover() urlpatterns = [ url( r'^favicon.ico$', RedirectView.as_view( url = staticfiles_storage.url( 'images/favicon.png' ), ), ), ... ] <b>urlpatterns += i18n_patterns</b>( path( r'admin/', admin.site.urls ), ... ) urlpatterns += static( settings.STATIC_URL, document_root = settings.STATIC_ROOT ) \ + static( settings.MEDIA_URL, document_root = settings.MEDIA_ROOT ) models.py (any) from django.core.validators import RegexValidator from django.db import models from django.utils.translation import ugettext as _ ... class BussinesType(models.Model): … -
How to use PATCH in DRF's UpdateAPIView?
I've looked in a lot of places, but am having a pretty difficult time finding a simple example of how one might use PATCH in Django Rest Framework's Update API View. I know this is a fairly simple problem. Here's the deal: I have a checkbox input. When it's checked, if the user unchecks said checkbox, the associated model's date value should be set to None and the resulting JSON response should be a serialization of the model w/ its date field updated. If the box is unchecked, then checking it should set the associated model's date value to timzone.now(), and the resulting JSON respone should again be a serialization of the model w/ its date field updated. The function that sends the request is simple: updateThing(pk, mark){ const url = `${API_URL}/api/goals/${pk}/${mark}`; return axios.patch(url); } Which corresponds to this entry in my urls.py: ... path('/<int:pk>/<str:mark>', views.ThingUpdate.as_view()), ... This thread talks about overriding the partial_update method. So I tried (in accordance w/ the thread): class ThingUpdate(generics.UpdateAPIView): serializer_class = ModelSerializer def get_queryset(self): return get_object_or_404(Thing, pk=self.kwargs['pk']) def partial_update(self, request, *args, **kwargs): model = self.get_object() if mark == 'completed': model.created_on = timezone.now() model.save() elif mark == 'uncompleted': model.created_on = None model.save() kwargs['partial'] = True … -
Is using Django's ListView and get_queryset secure?
I'm using the class based ListView and get_queryset to populate a list of objects assigned to an organization. This code is working well and limits users to only see matters belonging to their organization. My question is whether there are any security flaws in creating the list like this? Specifically, should I be populating the list differently? matters.views: class MatterListView(LoginRequiredMixin, ListView): model = Matters template_name = 'matters/matters.html' context_object_name = 'matters' ordering = ['-start_date'] def get_queryset(self): return self.model.objects.filter(organization=self.request.user.organization) -
Accessing objects by name from dict
Users can have multiple lists and I have DataItem objects attached to lists, these DataItem objects have number values and now I would need to retrieve all values by list name and insert them to chart.js My view looks like this: @login_required def app(request): form = list_form form2 = data_form(user=request.user) user = request.user.pk user_lists = List.objects.filter(user=user) #Here I have lists in dict but I have no idea how to call them in template. list_data = {} for list in user_lists: list_data[list.name] = DataItem.objects.filter(list=list) context = {'user_lists': user_lists, 'form': form, 'form2': form2, 'list_data': list_data} return render(request, 'app/app.html', context) Template: this is the chart.js datasets part in html page and it displays the list names properly how do I call the values that are connected to those names? {% for list in user_lists %} { label: '{{ list.name }}', data: [?????????], }, {% endfor %} Models if needed class List(models.Model): name = models.CharField(max_length=100, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists') def __str__(self): return self.name class Meta: unique_together = ['name', 'user'] class DataItem(models.Model): data = models.IntegerField(default=0) list = models.ForeignKey(List, on_delete=models.CASCADE, related_name='data_items') -
Abstract Base User not logging in
I can't log in as a superuser and can't work out why this is the case. My project compiles and runs with no errors or warnings, but I just get your username or password isn't correct. I have even created a completely new project and just to see if it was an issue with the setup, however, the issue is still persistent. In the new project, I have removed none vital parts to see if it was an issue with another are of my program, but nothing is obvious. I believe there could be something missing I'm not sure to what that maybe. If you have any ideas to why this is the case. Please let me know. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class editorManager(BaseUserManager): def create_editor(self, username, full_name, password): if not username: raise ValueError('editors must have an username') if not full_name: raise ValueError('editors must have a full name') if not password: raise ValueError('editors must have a password') editor = self.model() editor.full_name = full_name editor.set_password(password) editor.save(using = self._db) return editor def create_superuser(self, username, full_name, password = None): admin = self.create_editor( username = username, password = password, full_name = full_name, ) admin.is_staff = True admin.is_superuser … -
QueryCanceledError in psycopg2
I am in the middle of migrating an App from an old deployment to a new server with a new database instance running Postgresql 9.5.15. The app is written using python & Django. The problem is one operation I am trying to run using the DB involves writing the contents of a large CSV file to a table. This function works correctly on both the old deployment and testing it locally. In the new deployment however, I get an error at this step: <class 'psycopg2.extensions.QueryCanceledError'> returned a result with an error set Now, reading up on this error, it seems to suggest that a timeout during the attempt to copy over the CSV is the issue. No matter what I have tried so far, I cannot seem to get around this. The specific code at the moment is as follows: SQL_STATEMENT = """ SET statement_timeout = 0; COPY table_in_question FROM STDIN WITH CSV HEADER DELIMITER AS ',' """ file_object = open('file.csv') cursor = conn.cursor() cursor.copy_expert(sql=SQL_STATEMENT, file=file_object) conn.commit() cursor.close() Am I setting the timeout incorrectly? I believe setting it to zero prevents the timeout from occurring. -
Django - Model id in Detail View URL, 1st id not working
I have a model, Position, which I have created a detail view to view each individual position. views.py def position_detail_view(request, id=None): position = get_object_or_404(Position, id=id) context= { 'object': position, } return render(request, 'positions/position_detail.html', context) positions/urls.py from django.urls import path, include from .views import position_list_view, position_detail_view urlpatterns = [ path('', position_list_view), path('<int:id>', position_detail_view, name='detail') ] When I go to http://localhost:8000/apply/1/, where the id=1, I get a Page Not Found 404 Error. However, with any other id, the page loads just fine. Any ideas on why the first id in the model gives a 404 error? -
which framework best for pagination for websites?
i want to use pagination in our portal but i am confuse which framework is best for pagination. -
How do I route my API call to gather all objects with a ForeignKey connected to a specific model instance?
The goal I am trying to achieve is querying for all of a specific Model that has a ForeignKey relationship with an individual instance of another Model. I'm curious what the proper way of routing an API call would look like. The thought/hope is that it will look similar to: '/api/v1/devices/<id>/breadcrumbs' I am new to Django Rest Framework and am unsure of what to do here. I have created basic Viewsets like below: class DeviceViewSet(viewsets.ModelViewSet): queryset = Device.objects.all() serializer_class = DeviceSerializer class BreadcrumbViewSet(viewsets.ModelViewSet): queryset = Breadcrumb.objects.all() serializer_class = BreadcrumbSerializer As well as the basic routes: router.register(r'devices', DeviceViewSet) router.register(r'breadcrumbs', BreadcrumbViewSet) And the Breadcrumb model: class Breadcrumb(models.Model): timestamp = models.DateTimeField( auto_now_add=True, editable=False, null=False, blank=False ) device = models.ForeignKey( Device, on_delete=models.CASCADE ) But don't know how to extend this to the logic I am looking to achieve. -
ModuleNotFoundError: No module named 'new' error with django deployment using apache
Using versions: Centos 7---django 2.1.7---Apache 2.4.6---Python 3.6 I get this error when trying to access the url of server: [wsgi:error] mod_wsgi (pid=9020): Failed to exec Python script file '/home/user/project/new/wsgi.py'. [wsgi:error] mod_wsgi (pid=9020): Exception occurred processing WSGI script '/home/conner.johnson/ek/new/wsgi.py'. [wsgi:error] Traceback (most recent call last): [wsgi:error] File "/home/user/project/new/wsgi.py", line 19, in <module> [wsgi:error] application = get_wsgi_application() [wsgi:error] File "/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [wsgi:error] django.setup(set_prefix=False) [wsgi:error] File "/lib/python3.6/site-packages/django/__init__.py", line 19, in setup [wsgi:error] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [wsgi:error] File "/lib/python3.6/site-packages/django/conf/__init__.py", line 57, in __getattr__ [wsgi:error] self._setup(name) [wsgi:error] File "/lib/python3.6/site-packages/django/conf/__init__.py", line 44, in _setup [wsgi:error] self._wrapped = Settings(settings_module) [wsgi:error] File "/lib/python3.6/site-packages/django/conf/__init__.py", line 107, in __init__ [wsgi:error] mod = importlib.import_module(self.SETTINGS_MODULE) [wsgi:error] File "/lib64/python3.6/importlib/__init__.py", line 126, in import_module [wsgi:error] return _bootstrap._gcd_import(name[level:], package, level) [wsgi:error] File "<frozen importlib._bootstrap>", line 994, in _gcd_import [wsgi:error] File "<frozen importlib._bootstrap>", line 971, in _find_and_load [wsgi:error] File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked [wsgi:error] File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed [wsgi:error] File "<frozen importlib._bootstrap>", line 994, in _gcd_import [wsgi:error] File "<frozen importlib._bootstrap>", line 971, in _find_and_load [wsgi:error] File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked [wsgi:error] ModuleNotFoundError: No module named 'new' my file structure(2 apps, but one app 'new' only houses the settings, wsgi.py, and the urls.py points to the second app) …