Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How convert SQL to Django ORM
Need help to convert from SQL(PostgreSQL) to Django ORM SELECT task.lesson_id, task.name, task.content, task.max_score, MIN (log.action_time) AS created_at, MAX (log.action_time) AS modified_at FROM main_task task, django_admin_log log WHERE log.content_type_id=11 and task.id=CAST(log.object_id AS INTEGER) GROUP BY task.id, log.object_id ORDER BY modified_at DESC LIMIT 10 Thanks! -
Django - Log User Activity (Query - GET/FILTER/UPDATE/DELETE) To Database
I'm building a HIPAA compliant application and I would like to log every user action to the database. That includes when a user calls a get, filter, or delete object method on a model. I would like to add this functionality to a pre-existing application. _ = ModelA.objects.get(id=1) _ = ModelA.objects.filter(age__gt=10) _ = ModelA.objects.filter(age__lt=5).delete() I want to log every database operation. Django Activity Stream does not work for get method. How do I implement this functionality? -
Only top 5 objects in django admin Inline
I want to make only the last 5 consumptions of inventory visible in inline so I tried inlines=[Consumed_InventoryInline[:5]] as seen in the below code but that does not work. How can I do it? models.py class Consumed_Inventory(models.Model): qty=models.IntegerField(default=0) time_consumed=models.DateTimeField(default=timezone.now()) item=models.ForeignKey(Inventory_Checklist,on_delete=models.SET_NULL, null=True) class Meta: verbose_name_plural="Consumed" ordering=['-time_consumed'] admin.py: class Inventory_Checklist_admin(admin.ModelAdmin): list_display=('item','quantity') #list_filter=(('From,DateRangeFilter),'cadence','categories') #list_display_links=('title','comments') #list_editable=('quantity',) #date_hierarchy='From' inlines=[Consumed_InventoryInline[:5]] #search_fields=('title','c1') def save_model(self, request, obj, form, change): #obj.user = request.user p1=Purchased_Inventory.objects.filter(item=obj).aggregate(Sum('qty'))['qty__sum'] con1=Consumed_Inventory.objects.filter(item=obj).aggregate(Sum('qty'))['qty__sum'] pc=p1-con1 obj.quantity=pc #obj.save() super().save_model(request, obj, form, change) -
Favorite system in Django
Image $(document).ready(function(){ $(".like").click(function(){ $(this).toggleClass("heart"); }); }); .like { padding-right: 6px; color: #00000030; font-size: 1.6em; padding-top: 5px; animation: like 0.5s linear; } .heart { color: #FF0000; animation: heart 0.5s linear; } {% for m in musicl %} <div class="card"> <div class="top"> <div class="year">{{m.Year}}</div> <span class="like"><i class="fa fa-heart"></i></span> </div> <div class="middle"> <a href="https://google.com" id="link" target="_blank"> <div class="img-container"><img src="{{ m.Image.url }}"></div> </a> </div> <a href="https://google.com" id="link" target="_blank"> <div class="bottom"> <div class="title">{{m.Name}}</div> <div class="genre">{{m.Genre}}</div> </div> </a> </div> {% endfor %} models.py class Music(models.Model): Name = models.CharField(max_length=100, blank=False) Year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) Genre = MultiSelectField(choices=GENRE_CHOICES) Image = models.ImageField(blank=False, null=True) def __str__(self): return self.Name Views.py def home(request): return render(request, template_name='main/home.html', context={"musicl": Music.objects.all}) def wishlist(request, id): pass How do I connect the User model to this favorite system and keep track of the favorite list in a view function(wishlist), in other words when someone clicks on the fav icon, I want that specific card to be saved to the wishlist view corresponding to that User model -
How to pass Django Template Tags to an html file that is not in the URLPatterns?
I am seriously new to Django, so it is much appreciated if you are reading my question! I have a CRM Project I am working on in Django,and I have a Navigation Bar that loads from the side, written in a separate html file (navBar.html) and added to main.html (a file that contains all common front end items in every page of the website) using {% include 'crm/navBar.html' %}. Navigation Bar There is an "Add+" button that is supposed to act as a drop down menu. The options of such drop down menu should come from a model called "Sale_Steps" using template tags. The Problem is: I am struggling to import Sales_Steps into navBar.html, here is the code in a nutshell: in views.py def NavBar(request): Sale_steps = Sales_Step.objects.all() context = {'sale_step':Sale_steps} return render(request, 'crm/navBar.html',context) in urls.py urlpatterns = [ path('', crm_views.home_page), path('home/',crm_views.home_page), path('sales/', crm_views.sales_page), path('all_queries/',crm_views.all_queries_page), path('Queries/',crm_views.all_queries_page), path('checkQuery/',crm_views.check_query_page), path('Customers/',crm_views.all_customers_page), path('checkCustomer/',crm_views.check_customer_page), path('blank/',crm_views.blank_page), ] in navBar.html {% for s in sale_step %} <a class="dropdown-item" href="#">{{s.Name}}</a> {% endfor %} Thank you so much in advance! -
"psycopg2.errors.SyntaxError: multiple default values specified for column "id"" when trying to switch to postgresql in django
I would like to migrate a django project from a sqlite database to postgresql. Everything works in sqlite but running python manage.py --run-syncdb after changing the database settings returns to following error: psycopg2.errors.SyntaxError: multiple default values specified for column "id" of table "tasks_task" This is the corresponding model: class Task(models.Model): task_id = models.CharField(max_length= 36, default = "") content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null = True) object_id = models.PositiveIntegerField(null = True) task_input = GenericForeignKey('content_type', 'object_id') result = models.ForeignKey(TaskResult, null = True, on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) module = models.CharField(max_length=20, null = True) taskname = models.CharField(max_length=20, null = True) description = models.CharField(max_length=200, null = True) filepath = models.CharField(max_length=100, null = True) issue_date = models.DateTimeField(auto_now_add=True, blank = True) Setting the id field manually id = models.AutoField(primary_ky=True) did not solve the issue. -
integration of css page impossible after integration of different media
hello I hope you are fine after integrating the different screen sizes and launching in Heroku I discovered that if I set the debug = false I have a 500 page if I remove the design it works the design and builds by scss is working correctly if the debug = true even if it is in production -
Why is bootstrap loaded in Django project and my CSS file isn't?
I'm new in Python/Django and I'm trying to create a little project. I'm running Python 3.8.2 and Django 3.0.6 on Ubuntu 20.04 LTS. I'm still developing so I'm testing and running the webpages with "python manage.py runserver" (debug=True). I'm having a really hard time trying to load my own CSS style. The project is organized like this: PROJECT FOLDER | --virtualenv | --media | --myproject | --myapp | --migrations | --templates | --myapp | --static | --favicon | --style | --vendor | --bootstrap | --jquery | --templates | --parcials I have this configuration in my "settings.py" (which is inside "myproject" folder) related to the static files: INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ... ] STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join( BASE_DIR, '/myapp/static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static') In the head of the html which is rendered, I have: {% load static %} ... <link href="{% static 'favicon/favicon.ico' %}" rel="shortcut icon"> <link href="{% static 'vendor/bootstrap/css/bootstrap.css' %}" rel="stylesheet"> <link href="{% static 'vendor/bootstrap/css/theme_1564087106285.css' %}" rel="stylesheet"> <link hrel="{% static 'style/index.css' %}" rel="stylesheet" type="text/css"> The "index.css" is inside the style folder and it has just a class selector: .style-v1 { font-size: x-large; background-color: blue; } In the html body, I just try to test the css … -
Why does 'user_pins_info' keeps showing up with an empty list
I have been spending the last several hours trying to find out why this unit test keeps failing. The view in question is below: class UserPinView(View): @login_required def get(self, request, *args, **kwargs): user = kwargs['user'] user_all_pins = user.pins.all() user_pins_info = [{ "id": pin.id, "image": pin.image_url, "name": pin.name } for pin in user_all_pins] return JsonResponse({"pins": user_pins_info}) and below is the tests.py snippet class UserPinView(TestCase): def setUp(self): client = Client() social = Social.objects.create(name='google') user = User.objects.create(id=3, social_service=social) pin = Pin.objects.create(id=5, name='one', paragraph1='one') pin.user.add(user) pin.save() def tearDown(self): User.objects.filter(id=3).delete() Social.objects.filter(name='google').delete() Pin.objects.filter(id=5).delete() def test_get_user_pin_view(self): header = {"HTTP_AUTHORIZATION":ACCESS_TOKEN} access_token = self.client.post('/account/google', content_type="applications/json", **header ).json()['access_token'] header = {"HTTP_AUTHORIZATION":access_token} response = self.client.get('/user-pins', content_type="application/json", **header) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['pins'][0]['id'], 5) As you can see from the views.py code, the result should be something like: {'pins': [{'id':5, 'image': 'some image url', 'name': 'some name'}]} but when the test runs, it keeps showing something like: {'pins': []} And below is the models.py snippet you can take a look at to get the idea class Pin(models.Model): name = models.CharField(max_length=100, null=True) paragraph1 = models.CharField(max_length=500, null=True) paragraph2 = models.CharField(max_length=500, null=True) board = models.ForeignKey(Board, on_delete=models.CASCADE, null=True) image_url = models.URLField(max_length=2000, null=True) article_url = models.CharField(max_length=200, null=True) user = models.ManyToManyField( 'account.User', through = 'PinUser', related_name = 'pins', ) topic … -
How to store activity log for password reset in django?
In my system I want to keep track of all the users login/logout activities but I got stuck while keeping the log for user password reset activity . How can I store this user activity in my UserActivity model ? Is there any suggestions ? models class UserActivity(models.Model): change_message = models.CharField(max_length=255) ip = models.GenericIPAddressField(null=True) user = models.CharField(max_length=255, blank=True, null=True) action_time = models.DateTimeField(auto_now_add=True) @receiver(user_logged_in) def user_logged_in_callback(sender, request, user, **kwargs): ip = request.META.get('REMOTE_ADDR') UserActivity.objects.create(change_message='User Logged in', ip=ip, user=user.email) @receiver(user_logged_out) def user_logged_out_callback(sender, request, user, **kwargs): ip = request.META.get('REMOTE_ADDR') UserActivity.objects.create(change_message='User Logged out', ip=ip, user=user.email) @receiver(user_login_failed) def user_login_failed_callback(sender, request, credentials, **kwargs): ip = request.META.get('REMOTE_ADDR') UserActivity.objects.create(change_message='User Login Failed', ip=ip, user=credentials.get('email', None)) urls for password reset path('password-reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html', success_url=reverse_lazy('users:password_reset_complete'), form_class=PasswordResetConfirmForm), name='password_reset_confirm'), path('password-reset/complete/', views.PasswordResetSuccessView.as_view(), name='password_reset_complete') view class PasswordResetSuccessView(View): template_name = 'users/password_reset_complete.html', def get(self, request): ip = request.META.get('REMOTE_ADDR') UserActivity.objects.create(change_message='An user resets the password', ip=ip, user = ? ) -
custom template fields doesnt work for update formset django
i tried to use my own template style instead of default django form style , it work fine for creating post but doesnt work for update my formsets (inlineformset) , it also work if i use default django form style this my views.py class TitleQuestionAnswer(LoginRequiredMixin,UserPassesTestMixin,UpdateView): model = Title form_class = TitleForm template_name = 'template/update_title_question.html' def get_context_data(self,*args,**kwargs): context = super(TitleQuestionAnswer,self).get_context_data(*args,**kwargs) if self.request.POST: context['questions'] = QA_InlineFormset(self.request.POST,instance=self.object) else: context['questions'] = QA_InlineFormset(instance=self.object) return context def form_valid(self,form): context = self.get_context_data() context = context['questions'] self.object = form.save() if context.is_valid() and context.cleaned_data !={}: response = super().form_valid(form) context.instance = self.object context.save() return response return super().form_invalid(form) def get_success_url(self): return reverse_lazy('q-answer:post',kwargs={'pk':self.object.pk}) and this is my template <form method="POST">{% csrf_token %} <div class="col-6 inp text-center"> {{form.name | add_class:'col-12 text-center'}} {% if form.name.errors %} <div class="error col-3 mx-auto">{{form.name.errors}}</div> {% endif %} </div> </div> <!-- order --> <div class="col-12 p-0 border-top border-light "> <table class="customeTable col-12 table-responsive-sm info text-center table1 mx-auto mb-2 "> <tbody class="tbody tb1 " id="form_set"> {{questions.management_form}} {% for form in questions.forms %} <tr class="p-0 col-12"> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{form.field_a | add_class:'col-12'}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{form.field_b | add_class:'col-12'}} </div> </td> </tr> {% endfor %} </tbody> </form> but if i change it … -
ModuleNotFoundError: No module named 'django' when installing django in venv
I am trying to do this: from django.contrib import admin from .models import Topic admin.site.register(Topic) however, I get the following error: ModuleNotFoundError: No module named 'django' I have also tried installing django in my system but still nothing and when i check installed packages it shows django is already installed My venv is also active so i dont know why the error is being raised? -
React Native & Django: app with 2 user types. Should I build 2 apps?
This question is slightly different than the others that are posted here. I will be using React Native and Django for the backend. I need to build an appointment booking application, 1 user type are lets say patients, 1 user type are doctors. Obviously the signup process is different for both of them, however, the patients will need to have a view where they can see what doctors are in the database and create appointments towards them. And the doctors will need to see also which patients are out there, what's their review score, etc. As I am completely new to building mobile apps, I need your advise on what's the best way of structuring this project. Should I build 2 different apps, one for each user? (like Uber driver / rider app) Should I just manage it with one application based on user permissions? Please also be welcome to comment about what limitations I could encounter in the way, since I've already noticed that implementing two user types with Django might be tricky. -
how to avoid error "429 too many requests" when serving static files in django?
I am trying to set up a swagger interface in my django application so I installed drf-yasg, the problem is that when I access the /swagger/ page, I get the "429 too many requests" error because too many static files are provided at once. How can I work around that? Thanks in advance. -
Elastic beanstalk - unable to pip install some requirements
Trying to run a django app on elastic beanstalk. When I run eb create django-env it's stated in the logs that some requirements can't be installed: 2020/06/17 12:08:38.841799 [ERROR] Creating a Pipfile for this project… Requirements file provided! Importing into Pipfile… An error occurred while installing mkl-random==1.1.1! Will try again. An error occurred while installing mkl-service==2.3.0! Will try again. An error occurred while installing openapi-client==1.0.0! Will try again. An error occurred while installing pandas==0.23.4! Will try again. An error occurred while installing pypiwin32==223! Will try again. An error occurred while installing pywin32==228! Will try again. [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/cli/command.py", line 254, in install [pipenv.exceptions.InstallError]: editable_packages=state.installstate.editables, [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 1874, in do_install [pipenv.exceptions.InstallError]: keep_outdated=keep_outdated [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 1253, in do_init [pipenv.exceptions.InstallError]: pypi_mirror=pypi_mirror, [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 862, in do_install_dependencies [pipenv.exceptions.InstallError]: _cleanup_procs(procs, False, failed_deps_queue, retry=False) [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 681, in _cleanup_procs [pipenv.exceptions.InstallError]: raise exceptions.InstallError(c.dep.name, extra=err_lines) [pipenv.exceptions.InstallError]: [] [pipenv.exceptions.InstallError]: ['ERROR: Could not find a version that satisfies the requirement mkl-random==1.1.1 (from versions: none)', 'ERROR: No matching distribution found for mkl-random==1.1.1'] ERROR: ERROR: Package installation failed... 2020/06/17 12:08:38.845458 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with … -
uploading media files for free that doesn't required credit card details on heroku django
I have uploaded my project on Heroku but media file(image) disappears after a while. When searching I found out that Heroku runs your application on dynos and dynos go to sleep after 30 minutes if there is not request comes, this makes Heroku not preserve user upload media files between dynos restart. Is there any other way I can upload my media files that stays there? I could use Amazon S3 service but I don't have any credit card or don't want to use a credit card info? Is there any other way? -
Django how to import value in request function to a function?
I have the following project structure: _stato_patrimoniale ___views.py _iva ___utility.py In the stato patrimoniale I have the following code: from iva.utility import my_func def stato_patrimoniale(request): now=datetime.datetime.now() last_account_year=float(now.year)-1 #definizione dell'ultimo anno contabile now = now.year if request.method == 'POST': year = request.POST['year'] if year != '': now = year last_account_year = float(now) - 1 data=my_func() iva_a_credito=data['iva_a_credito'] Now in my iva.utility I have the following code: def my_func(): pass Now I want to import in my_func()the value of last_account_year from the stato_patrimoniale. How is it possible? -
Order by return of class method
I have a model with a date field and a following method: class myModel(models.Model): date = models.DateField() def due_date(self): today = timezone.localtime(timezone.now()).date() if self.date < today: return today else: return self.date How can I order myModel.objects.all() based on the return of due_date function? -
Django 1.7.11 (NoReverseMatch, Current URL didn't find any matches) Strange Regex Problem
I have been given the task to fix some bugs in an old Django application. The version used for this application is Django 1.7.11 (running in Ubuntu 14.04 and using Python 2.7.6). When I run ./manage-py runserver, the site loads with NoReverseMatch Reverse for 'faq' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['faq/$']. The problem I face is that a few of the named URLs are not reverse-ing. The views are not giving the problem and the references to the named URL in the templates are correct. Take for example the following url pattern in urls.py, url(r'^faq/$','extra.views.faq', name='faq'), returns a NoReverseMatch error but when I change that line of code to, url(r'^fq/$','extra.views.faq', name='faq'), The url is able to reverse and render. What could cause such a strange behaviour? Could it be a python package? Here's the list of python packages installed in the project, Babel==1.3 BeautifulSoup==3.2.1 Cheetah==2.4.4 Django==1.7.11 Fabric==1.8.1 Fuzzy==1.0 Jinja2==2.11.2 Landscape-Client==14.12 MarkupSafe==1.1.1 PAM==0.4.2 Pillow==6.2.2 ProxyTypes==0.9 PyNaCl==1.4.0 PyYAML==3.10 Pygments==2.5.2 SecretStorage==2.0.0 South==0.8.2 Sphinx==1.3.1 Twisted-Core==13.2.0 Twisted-Names==13.2.0 Twisted-Web==13.2.0 Werkzeug==0.9.4 alabaster==0.7.12 amqp==1.4.9 anyjson==0.3.3 apt-xapian-index==0.45 argh==0.23.3 argparse==1.2.1 bcrypt==3.1.7 beautifulsoup4==4.3.2 billiard==3.3.0.23 celery==3.1.23 certifi==2020.4.5.2 cffi==1.14.0 chardet==2.0.1 cloud-init==0.7.5 colorama==0.2.5 configobj==4.7.2 cryptography==2.9.2 currencies==2014.7.13 decorator==4.4.2 django-ckeditor-updated==4.4.4 django-crispy-forms==1.4.0 django-debug-toolbar==1.4 django-extensions==1.2.5 django-filter==0.7 django-jenkins==0.18.0 django-oauth-toolkit==0.9.0 django-oauth2-provider==0.2.6.1 django-password-strength==1.0.0 django-polymorphic==0.5.5 … -
How to avoid similar rows during excel import with django-import-export?
I have an excel file that has multiple rows which contain similar data. For example employee name is repeated in multiple rows but i would like to import such records only once and not multiple times into my database to avoid redundancy. I have seen that skip_rows method may help with this but still cannot figure how exactly to use it since the documentation is very limited. Any help will be appreciated :) -
CSRF verification error in dynamic domains behind a proxy
In our site we are introducing a new feature that allows our users to have their domain point to our proxy so that they can quickly set up a page of their own using our system but with their own domain name. Basically our their domain is just an alias of ours. I'm testing all this in our staging environment and hit a wall with CSRF verification failure. When I try to log in at /accounts/login I am getting a 403 Forbidden error because of CSRF. This didn't happen in development when I tested domains acting as localhost aliases. I suspect the login view isn't going to be the only one raising this CSRF issue, but all POST requests. I am not sure where to go from this. Is there any way I can make CSRF tokens work in dynamic domains? If not, what's the solution, just disable the middleware? Or perhaps rewrite it so that it's skipped when the host is not the main site? Still, ideally I'd want CSRF protection to work regardless of the domain name. What would be the security implications, other than a non-trusted host making a request? In this sense, I think we already … -
How to write propber model tests in python with django?
For an ongoing school project me and my friends have developed a little bookfinder application in Python with Django. We are actually almost finished, but have problems with writing the tests. We would be happy to hear how you would approach the tests. They can be as simple as possible. book.py: from django.db import models import pdb class Book: def __init__(self, book_element): self.book_information = self.create_book(book_element) # some instance variabless are missing try fixing it maybe use forms def create_book(self, book_element): info = book_element["volumeInfo"] title = info.get("title") publisher = info.get("publisher, Nicht vorhanden") author = info.get("authors, Nicht vorhanden.") imageTrue = info["readingModes"].get("image") if imageTrue == True: image = info["imageLinks"].get("thumbnail") else: image = "Nicht vorhanden" published_Date = info.get("publishedDate, Nicht vorhanden.") page_Count = info.get("pageCount, Nicht vorhanden.") categorie = info.get("categories, Nicht vorhanden") book_information = { "title": title, "author": author, "publisher": publisher, "publishedDate": published_Date, "pageCount": page_Count, "image": image, "categorie": categorie } return book_information book_api.py: from django.db import models from .book import Book import requests import pdb class Book_Api: def __init__(self, search): self.show_books = self.process_data(search) # try using private methods and what about class methods def process_data(self, search): json_respose = self.__fetch_data(search) books_list = [] for book in json_respose["items"]: book_obj = Book(book) books_list.append(book_obj) return books_list def __fetch_data(self, book_search): key … -
How to sort list view using Ajax in Django?
In list view template I created a filter form that filters posts, and again their is a sort dropdown to sort them: <form id="sortForm"> <select class="input-text" id="sort" onchange="document.querySelector('#sortSubmitBtn').click()" name="sort" id="sort"> <option disabled selected>Sort by</option> <option value="price_l2h" {% if 'price_l2h' == values.sort %} selected {% endif %}> Price (low to high)</option> <option value="price_h2l" {% if 'price_h2l' == values.sort %} selected {% endif %}> Price (high to low)</option> </select> {% if values.keywords %} <input type="hidden" name="keywords" id="keywords" value="{{ values.keywords }}"> {% endif %} {% if values.mls_number %} <input type="hidden" name="mls_number" id="mls_number" value="{{ values.mls_number }}"> {% endif %} <button type="submit" id="sortSubmitBtn" style="display: none;">Submit</button> </form> and here is the Ajax I used to sort it, but it doesn't work. I used same Ajax syntax to save data in models it worked fine, but this one doesn't work. <script> $(document).on('submit', '#sortForm', function (e) { e.preventDefault(); $.ajax({ type: 'GET', url: "{% url 'listing:search' %}", data: { sort: $('#sort').val(), keywords: $('#keywords').val(), mls_number: $('#mls_number').val(), csrfmiddlewaretoken: "{{ csrf_token }}", }, success: function () { alert('Form submitted successfully!!'); } }) }) </script> the urls.py: path('search/', search, name='search'), Thank you I hope someone help me with this. -
Django 3, I change DEBUG = False, and when I send letters the images disappear, why is this happening?
Send letters in the mail, and disappears images when DEBUG = False when DEBUG = True, everything is displayed, why is this happening ??? the website is deployed on heroku to send emails using sendgrid to store dynamic images using AWS mail template <div class="row"> <div class="col-12 d-flex justify-content-center" > <img class="img-fluid w-100" style="width: 100%;" src="sitename.com/{{ img_path }}" alt="1"> </div> </div> debug=true debug=false -
AttributeError: 'str' object has no attribute '_meta', when trying to create user registration
Im using my own User model extendeds with the AbstractUser model. I am trying to create a registration page but it keeps throwing me an error, AttributeError: 'str' object has no attribute '_meta'. models.py from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass forms.py from django.contrib.auth.forms import UserCreationForm from django import forms from django.conf import settings class UserRegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = settings.AUTH_USER_MODEL fields = ['username', 'email', 'password1', 'password2'] views.py from django.shortcuts import render from .forms import UserRegistrationForm def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): form.save() else: form = UserRegistrationForm() return render(request, 'users/register.html', {'form': form})