Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting validation error field can not be null, even if null=True in model
I've a foreign key in my model and this field can be null. status = models.ForeignKey(Status, on_delete=models.SET_NULL, null=True, blank=True, related_name="status") When i send a request with this field as null i get validation error saying [ { "status": [ "This field may not be null." ] } ] Even though I have set null=True I'm not sure why it's throwing me that validation error? Can anyone please help me with this. -
How to create a validation check that ensures the right-formatted directory path is stored and if it contains a file extension in Django?
I have a template that allows a user to store a pathname of a directory in my model (the directory should be available/exist in the server for a website or seen in a local machine). Before saving the path to the model, I need to ensure whether if the right format for the directory is being saved. Example: var/www/html/media/product or C:\Users\Danny\Desktop\folder. There shouldn't be any irregular strings, expressions or invalid format seen in the path like var/www/html/media/product\pic/... Moreover, I want to stop users if they want to save a specific directory path that contains a file extension. Example: var/www/html/media/product/file.<'file extension'> ('file.png', top.txt', 'random.jpg', etc...) How can this be done in my views.py code? Currently, this is what I did so far: views.py: def dashboard(request): if request.method == 'POST': form = PathForm(request.POST) if form.is_valid(): path = form.cleaned_data['path'] #CharField that stores the path name in model from form. #Two checks required. Need to see if it is a valid directory path format or if the path contains a general path directory. Not specific files (like images, text, csv file) should be seen in the path. #if file path contains a file extension at end. This is tedious since I need include all … -
Django: Get last record by ID [many-to-one relationship]
I'm trying to get the last record in one table connected to another one using many-to-one relationship in django models. Here's my django models: class DataCollecttion(models.Model): default_name = models.CharField(max_length=100) class NameHistory(models.Model): old_name = models.CharField(max_length=100) collection_data = models.ForeignKey(DataCollection, on_delete=models.CASCADE, null=True) Here I created a sample data for DataCollection table: And here's the sample data for NameHistory table: What I want here is to filter or get the last record in NameHistory in each collection_data_id (the records inside the red rectangle) and display it in my views. So in short I want to get these lines and how can I do it in ORM Query: sample3 test2 data1 -
A mistake on django "'django.forms.models' has no attribute 'Model'
[whats appears on the terminal ][1] i cant solve this error when i write the comand python manage.py makemigrations polls [1]: https://i.stack.imgur.com/brkOJ.png python manage.py makemigrations polls -
How do i host a django website via filezilla?
I am trying to host a django website via filezilla using a2hosting server.Steps i followed are given below 1. Uploaded my website from local host to remote site via filezilla. 2. Install all django requirements via putty. 3. Add allowed host as "mydomain". 4.Run server using the command "python3 manage.py runserver myip:8000 now i can access my website.But the problem is after stop running the server.It shows "404 Not Found Nginx/1.10.3 (Ubuntu)" error message. How do i resolve this issue? -
Static Files not saving on S3 bucket using cookiecutter-django
I'm trying to deploy my project on Heroku. I ran heroku run python3 manage.py collectstatic after deploying it. I have this on config/base.py STATIC_ROOT = str(ROOT_DIR("staticfiles")) STATIC_URL = "/static/" STATICFILES_DIRS = [str(APPS_DIR.path("static"))] STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] This is on the config/production.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS += ["storages"] # noqa F405 AWS_ACCESS_KEY_ID = env("DJANGO_AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = env("DJANGO_AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = env("DJANGO_AWS_STORAGE_BUCKET_NAME") AWS_QUERYSTRING_AUTH = False _AWS_EXPIRY = 60 * 60 * 24 * 7 AWS_S3_OBJECT_PARAMETERS = { "CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate" } AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = env("DJANGO_AWS_S3_REGION_NAME", default=None) STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" from storages.backends.s3boto3 import S3Boto3Storage # noqa E402 class StaticRootS3Boto3Storage(S3Boto3Storage): location = "static" default_acl = "public-read" class MediaRootS3Boto3Storage(S3Boto3Storage): location = "media" file_overwrite = False DEFAULT_FILE_STORAGE = "config.settings.production.MediaRootS3Boto3Storage" MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/media/" These are my heroku env variables I generated this using cookiecutter-django. Everything works fine on my localhost but when I deploy it to heroku, it doesn't save the static files. -
I keep getting below error when starting django server. Below is a full trace of the error. Please let me know what could fix this issue
(env) C:\Users\LENOVO\Desktop\SD\backend>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\channels\apps.py", line 6, in <module> import daphne.server File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\daphne\server.py", line 18, in asyncioreactor.install() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\asyncioreactor.py", line 320, in install reactor = AsyncioSelectorReactor(eventloop) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\asyncioreactor.py", line 69, in init super().init() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\base.py", line 571, in init self.installWaker() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\posixbase.py", line 286, in installWaker self.addReader(self.waker) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\asyncioreactor.py", line 151, in addReader self._asyncioEventloop.add_reader(fd, … -
Define a path for a file in python script on heroku
I have a text file in a folder inside of my app in a django project. I am using Heroku bash to run a script that reads the text file and populate the data into the database. on my machine I have defined this: file=open(os.path.join(settings.BASE_DIR,'myappfolder/folder_name/data.txt'),'r',encoding="utf8") It works on my local but when I run it in the heroku using bash it replies: FileNotFoundError: [Errno 2] No such file or directory: '/app/myappfolder\\folder_name\\data.txt' Could tell me how can I modify in a way that it works on my heroku app and also my local machine? -
How to sync local Django sqlite3 data with Heroku's postgres database?
I have a Django website served by Heroku with a model storing data about projects that I've worked on in the past. I already ran makemigrations and migrate locally before pushing to heroku with git and running heroku run python3 manage.py migrate. So, my database models and fields are synced, but I'm asking about the field values. Whenever I update the value of a field for a model instance locally, I want it (the data) to sync with Heroku, and vice versa–sync values I've updated on Heroku in the admin panel with my local sqlite3 database. Is there a command for updating the values of the database itself, or am I missing something? Because I've looked all over the internet for the last hour for how to do this one thing. Side note: I also want the command I'm looking for to sync newly created instances, not just data for existing model instances. -
Python3 Django issues regarding paths and custom decorators
Rather new to Django first time using is. Python is not my strong point in a web context - i'm having issues with my custom decorator I made that will decode the jwt from all requests. decorators.py from django.core.exceptions import PermissionDenied import jwt def verify_token(function): def wrap(request, *args, **kwargs): if request: print('========='.format(request)) jwt.decode(request, 'secret', algorithms=['HS256']) else: raise PermissionDenied wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap views.py from .User_Predictions.PredictionService import PredicitonController from django.http import JsonResponse from rest_framework.views import APIView from .decorators import verify_token class UserPredictions(APIView): @verify_token def generate_full_report(request): _predction = PredicitonController() results = _predction.compile_complete_predition() return JsonResponse(results, safe=False) urls.py from django.urls import path from .views import UserPredictions urlpatterns = [ path('compilePredictions/', UserPredictions.generate_full_report, name='generate_full_report') ] . ├── Analytics │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── settings.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── wsgi.cpython-37.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── authentication │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── biometrics │ ├── admin.py │ ├── apps.py │ ├── bodyfatPrediciton.py │ ├── Config.py │ ├── __init__.py │ ├── models.py │ ├── templates │ │ ├── … -
Django template won't render form errors
After a user has submitted a form with data that fails validation, form.errors in fact collects those errors as I've been debugging the issue. However when I render the page after a POST request, the errors will not be parsed in HTML alongside the fields where errors occur. What needs to change in order for the validation errors to render in the template when user data doesn't pass validation? # view that renders the template @login_required(login_url="/accounts/sign_in/") def new_profile(request, username): form = ProfileForm() import pdb; pdb.set_trace() if request.method == 'POST': user_profile = ProfileForm(request.POST) if user_profile.is_valid(): user_profile.cleaned_data.update(user=request.user) Profile.objects.create(**user_profile.cleaned_data) return HttpResponseRedirect( reverse("accounts:profile", kwargs={'username': username}) ) return render(request, 'accounts/create_profile.html', {'form': form}) # create_profile.html {% extends 'layout.html' %} {% block body %} <form action="{% url 'accounts:new_profile' username=user %}" method="post"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> {% endblock %} -> if request.method == 'POST': (Pdb) n -> user_profile = ProfileForm(request.POST) (Pdb) n -> if user_profile.is_valid(): (Pdb) p user_profile.errors {'birth': ['Enter a valid date.'], 'bio': ['Add more detail to your bio.']} -
How to group products by sellers in django
I am working on a multivendor ecommerce project for academic perspective.I am very beginner in Django. I am struck into this problem.Pls someone help. Here is the models for my Order. In the Order model i have items which is a Many to Many relationship with OrderItem. In OrderItem there is a field item which relates to the Product model. The product model holds the seller information and price. I want my products show on the order-summary grouped by the seller. And create different invoices for each of the sellers. But cannot find how to do that. I want to do something like the following snippet: Seller 1: Invoice Id- ____ Total Price:____ , ProductName - Quantity- Price, ProductName - Quantity- Price, ProductName - Quantity- Price Seller 2: Invoice Id- ____ Total Price:____ ,ProductName - Quantity- Price, ProductName - Quantity- Price The models for my Order app: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey( 'BillingAddress', on_delete=models.SET_NULL, blank=True, null=True) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) class Product(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) price = … -
When to use render and when to use redirect if you want to create login with session
so i want to make a login with a session , but i dont know when to use render or when to use redirect , here's the code def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') guest = User.objects.get(username=username) role = guest.role user = authenticate(username=username, password=password) if user is not None: if role == 'Business Analyst': login(request, user) request.session['username'] = username return render(request,'index.html',{"username":username}) #return redirect('/home') elif role == 'Admin': login(request, user) request.session['username'] = username #return redirect('/manageuser/') elif role == 'Manager': login(request, user) request.session['username'] = username # return redirect('/approvallist/') elif role == 'Segment Manager': login(request, user) request.session['username'] = username #return redirect('/approvallist/') else: messages.error(request, "Invalid username or password!") else: messages.error(request, "Invalid username or password!") form = AuthenticationForm() return render(request,"login.html",{"form":form}) def index_view(request): #if request.session.has_key('username'): # username = request.session['username'] # return render(request,'index.html',{"username":username}) #else: # return render(request,'login.html',{}) return render(request,'index.html') am i doing this right? about the use of return render? or i must use return redirect? -
Spanning two multi-valued relationships in the same query [Django]
I can span foreign key relationships in django filters like this: brand_asset__business_unit__in=user.owner_for_business_units.id If the last item returns multiple values, I can use __in and all() brand_asset__business_unit__in=user.owner_for_business_units.all() How do I span two m2m relationships in a Teachers have a m2m relationship with I looked through the documentation but it deals with spanning one m2m relationship. -
Getting multiple queryset list of single model
I have a model say: class Abc(models.model): .... ..... Now When performing query(let go all the imports): print(Abc.objects.all()) I am getting multiple list of querySet: Output as <QuerySet [<Abc: ...>, <Abc: .....> , .....]> <QuerySet [<Abc: ...>, <Abc: .....> , .....]> I have to User so I am getting 2 different QuerySet. How can I get all the user's querySet in single list, Wanted output as: <QuerySet [<Abc: ...>, <Abc: .....> , .....]>, <QuerySet [<Abc: ...>, <Abc: .....> , .....]> or in a single list <QuerySet [<Abc: ...>, <Abc: .....> , .....]> But from my knowledge a model should list all the querySet in single list , why am I getting multiple list ? Image of my model and error -
Plotting a timestamp with django and matplotlib
I'm having some trouble creating a view in django, I'm trying to make a web app which will read in from a csv and then display the plot, however the time axis I need to plot from the csv is not a float it is a string, then way I have it here I'm not sure how to plot this timestamp: def showMe(request): fig = Figure() canvas = FigureCanvas(fig) x, y = np.loadtxt('/Users/name/Desktop/garden_app/stored.csv', delimiter=',', dtype={'names': ('time','moisture'), 'formats': ('|S1', np.float)}, unpack=True) plt.plot(x, y, align='center', alpha=0.5, label='Name') plt.ylabel('moisture') plt.xlabel('time') plt.title('Moisture V. Time') buf = io.BytesIO() plt.savefig(buf, format='png') plt.close(fig) response = HttpResponse(buf.getValue(), content_type = 'image/png') return response The csv file I have looks like this: moisture,time,pump,light,temperature 1023,2019-10-27 17:22:27.367391,running,5V,25 Celsius 1023,2019-10-27 17:22:30.402280,running,5V,25 Celsius ... The "ValueError: could not convert string to float: 'time'" comes from the 'formats': ('|S1', np.float) on line 4, I'm just not sure how to change this where one is a number and the other is the timestamp. -
Bulk Update of model fields baseds on user input in admin site
In django, let's say I have a model with an integerfield called "RouteNumber" in my model. I manage all the model entries in the django admin site and I want to assign a route number to more than 100 entries at a time. How can I do that based on a user input? I was thinking using an admin action that would request a number and that all the queryset would be assigned this value In my model.py: class Person(models.Model): Name = models.CharField("Nom du parent", max_length=40, default="") RouteNumber= models.IntegerField("Numéro de route", default=None, blank=True, null=True) In my admin.py: def assign_route_number # This is where I'm lost ==== number = user_input("Enter a route number") # ======== for obj in queryset: obj.RouteNumber = number obj.save() However I don't know how to get the user input. Is there an easy way to get that? Thank you for your answers -
Django error 'ManagerDescriptor' object has no attribute 'filter'
I am relatively new to django and am running into the error 'ManagerDescriptor' object has no attribute 'filter' when retrieving view 'dashboard' -- below is my view and model. Can anyone point me in the right direction here? Thanks! #views.py def dashboard(request): tabledata_totals = '' if not request.user.is_authenticated: return redirect(settings.LOGIN_URL, request.path) else: orgs = Profile.objects.values_list('assigned_org_ids', 'view_group').get(user_id=request.user.id) tabledata_totals = org_totals.objects.filter(org_id__in=orgs[0].split(',')).aggregate( sum('open_supplement_count'), sum('open_estimate_count'), sum('open_measurement_count'), sum('total_open_count'), sum('supplement_sent_to_ins'), sum('revised_scope_received_additional_items_needed'), sum('homeowner_permission_needed'), sum('three_calls_to_adjuster_without_response'), sum('spoke_to_adjuster'), sum('missing_documents_required_for_supplementation'), sum('wWaiting_on_a_revised_scope'), sum('estimate_created_and_sent_to_customer'), sum('deal_in'), sum('supplement_complete'), sum('eagleview_measurements'), sum('confirmed_received'), sum('confirmed_assigned_to_adjuster'), sum('additional_documentation_needed') ) return render(request, 'HTML/dashboard.html', {'data': tabledata_totals}) #models.py @login_required(login_url='/login/') class org_totals(models.Model): organization = models.CharField(max_length=100, blank=True, null=True) org_id = models.SmallIntegerField(primary_key=True) open_supplement_count = models.SmallIntegerField(blank=True, null=True) open_estimate_count = models.SmallIntegerField(blank=True, null=True) open_measurement_count = models.SmallIntegerField(blank=True, null=True) total_open_count = models.SmallIntegerField(blank=True, null=True) Supplement_Sent_to_Ins = models.SmallIntegerField(blank=True, null=True) Revised_Scope_Received_Additional_Items_Needed = models.SmallIntegerField(blank=True, null=True) Homeowner_Permission_Needed = models.SmallIntegerField(blank=True, null=True) three_Calls_to_Adjuster_Without_Response = models.SmallIntegerField(blank=True, null=True) Spoke_to_Adjuster = models.SmallIntegerField(blank=True, null=True) Missing_Documents_Required_for_Supplementation = models.SmallIntegerField(blank=True, null=True) Waiting_on_a_Revised_Scope = models.SmallIntegerField(blank=True, null=True) Estimate_Created_and_Sent_to_Customer = models.SmallIntegerField(blank=True, null=True) Deal_In = models.SmallIntegerField(blank=True, null=True) Supplement_Complete = models.SmallIntegerField(blank=True, null=True) Eagleview_Measurements = models.SmallIntegerField(blank=True, null=True) Confirmed_Received = models.SmallIntegerField(blank=True, null=True) Confirmed_Assigned_to_Adjuster = models.SmallIntegerField(blank=True, null=True) Additional_Documentation_Needed = models.SmallIntegerField(blank=True, null=True) class Meta: managed = False db_table = 'org_open_totals' -
Django filter based on start date and end date for single day
I have a query start_date = '2019-11-17' end_date = '2019-11-18' events = Event.objects.filter(start_date__gte=start_date,end_date__lte=end_date) This doesn't return any result.. I tried direct mysql query, even this doesn't return any results, SELECT * FROM `events` where start_date >= '2019-11-17' and end_date <= '2019-11-18' Any idea where I am wrong? In my database I have these 3 rows, -
NEED TO UNDERSTAND BETTER THE FORMS IN DJANGO
SO AM NEW TO DJANGO, AND I KNOW HOW TO CREATE FORMS AND DEPLOY THEM ON TEMPLATES, SO FAR SO GOOD, BUT NOW HERE IS WHERE IT GETS ME CONFUSED I KNOW I CAN USE THE CRISPY_FORMS TO MAKE IT LOOK BETTER, BUT WHAT IF I WANT TO USE PLACEHOLDERS IN THE FORMS THAT I HAVE CREATED.... HOW DO I DO THAT? -
Slow Django Page - Doesn't Appear to be caused by SQL
I'm trying to debug a slow Django listview page. The page currently displays all tests (133), as well as the latest result for each test. There are approximately 60,000 results, each result having a FK relationship to a single test. I've optimized the SQL (I think) by selecting the latest result for each test, and passing it in as a prefetch related to my tests query. Django Debug Toolbar shows that the SQL is taking ~350ms, but the page load is ~3.5s. If I restrict the list view to a single test though, the SQL is ~7.5ms, and page load is ~100ms. I'm not fetching anything from S3 etc, and not rendering any images or the like. So my question is, what could be causing the slowness? It seems like it is the SQL, since as the result set grows so does page load, but maybe rendering of each item or something similar? Any guidance on what to look into next would be appreciated. -
return render(request, "index.html", {'index': "<div> dfdafadfasdsad </div>"})
I'm trying to append some html onto my index.html template from a view in django. This is my views.py from django.shortcuts import render from django.http import HttpResponse from .models import Greeting # Create your views here. def index(request): # return HttpResponse('Hello from Python!') return render(request, "index.html", {'index': "<div> dfdafadfasdsad </div>"}) However it is just outputting the index.html without the added html. What am I doing wrong? -
Django 2 multi model update view
I'm having a really hard time trying to get an update view class to work. I'm trying to make a cooking recipe app. I found an example of a createview that handles multiple models. im trying to write an update view, but. When ive plugged in my url, the page renders blank with no records. I think the problem is withthe context data, but my experiance with djagno is very limited. my class is below class RecipeUpdateView(UpdateView): model = Recipe form_class = RecipeForm success_url = '/recipe/' def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) ingredient_form = IngredientFormSet() instruction_form = InstructionFormSet() return self.render_to_response( self.get_context_data(form=form, ingredient_form=ingredient_form, instruction_form=instruction_form)) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) ingredient_form = IngredientFormSet(self.request.POST) instruction_form = InstructionFormSet(self.request.POST) if (form.is_valid() and ingredient_form.is_valid() and instruction_form.is_valid()): return self.form_valid(form, ingredient_form, instruction_form) else: return self.form_invalid(form, ingredient_form, instruction_form) def form_valid(self, form, ingredient_form, instruction_form): self.object = form.save() ingredient_form.instance = self.object ingredient_form.save() instruction_form.instance = self.object instruction_form.save() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, ingredient_form, instruction_form): return self.render_to_response( self.get_context_data(form=form, ingredient_form=ingredient_form, instruction_form=instruction_form)) Can any one help me out with this? Many thanks Ben -
creating superuser returns "no such table: accounts_user"
I am creating a rest API using Django-rest-auth, and I have a custom user model in an app named accounts. the problem is after making migrations when I try creating a superuser in the console after I input the email in the email field, I get a bunch of errors telling me "no such table: accounts_user" my settings.py INSTALLED_APPS = [ ... 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'accounts', ] # to use old_password when setting a new password OLD_PASSWORD_FIELD_ENABLED = True LOGOUT_ON_PASSWORD_CHANGE = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_EMAIL_FIELD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGOUT_ON_GET = True # UNSURE ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds ACCOUNT_LOGOUT_REDIRECT_URL ='api/accounts/rest-auth/login/' LOGIN_REDIRECT_URL = 'api/accounts/rest-auth/user/' SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'opeyemiodedeyi@gmail.com' EMAIL_HOST_PASSWORD = '9j@4lifE' DEFAULT_FROM_EMAIL = 'opeyemiodedeyi@gmail.com' DEFAULT_TO_EMAIL = EMAIL_HOST_USER EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/' REST_AUTH_SERIALIZERS = { "USER_DETAILS_SERIALIZER": "accounts.api.serializers.CustomUserDetailsSerializer", } REST_AUTH_REGISTER_SERIALIZERS = { "REGISTER_SERIALIZER": "accounts.api.serializers.CustomRegisterSerializer", } models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, fullname, password, is_staff, is_superuser, **extra_fields): if not … -
How to properly filter or exclude based on a parameter in Django?
I can do this in Django: query = {field_name: value} if include: return queryset.filter(**query) else: return queryset.exclude(**query) That's bad because there's a fair bit of duplication, and it's rather verbose. I can also do this, which is much simpler: return queryset._filter_or_exclude(not include, field_name=value) But that's also bad, because I'm calling a protected method. Is there a way to combine the best of both? return queryset.filter(exclude=not include, field_name=value) is not a thing.