Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Images can be added to HTML in Django, As i tried by static folder but still not getting image on html page
STATIC_URL = '/static/' {% load static %} Why this is not working in my case ... ? -
How do I know if and where my google cloud clogs are getting written
I have added a google-cloud-logging handler to the LOGGING settings of my django app and added it as a handler for my apps logger as below: from google.cloud import logging as google_cloud_logging gcloud_log_client = google_cloud_logging.Client() LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}, "require_debug_true": {"()": "django.utils.log.RequireDebugTrue"}, }, "formatters": { "console": {"format": "%(name)-12s %(levelname)-8s %(message)s"}, "file": {"format": "%(asctime)s %(name)-12s %(levelname)-8s %(message)s"}, }, "handlers": { "console": {"class": "logging.StreamHandler", "formatter": "console"}, "apps_log_file": { "level": "DEBUG", "class": "logging.FileHandler", "formatter": "file", "filename": "/tmp/apps_logfile.txt", }, "mail_admins": { "level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log.AdminEmailHandler", }, "gcloud_log": { "level": "INFO", "class": "google.cloud.logging.handlers.CloudLoggingHandler", "client": gcloud_log_client, }, }, # "root": {"handlers": ["console"], "level": "WARNING"}, "loggers": { "apps": { "level": "DEBUG", "handlers": ["console", "apps_log_file", "mail_admins", "gcloud_log"], } }, } When I run this django app locally, the logs from apps logger are getting written to console and to the file as expected. Similarly, when I run this on GAE, I can see the logs on stdout logs. But I am not able to find the logs associated with gcloud_log handler. The stdout logs are not labeled by severity, so I am looking to log as separate google cloud log. The documentation for the google.cloud.logging is not at … -
Get all value selected from bootstrap selectpicker multiselect
Using bootstrap selectpicker for selecting multiple options but when I fetch it using post method I get only the last value selected. However the selected values are displayed properly in the select box. I am using Django framework and when I fetch value using request.POST['selection'] it returns only the last value selected. <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script> <select class="selectpicker" name="selection" multiple data-live-search="true"> <option>Mustard</option> <option>Ketchup</option> <option>Relish</option> </select> -
Django, queryset to find count in manytomany field
I have below model, class Blog(models.Model): name = models.CharField(max_length=100) class Author(models.Model): name = models.CharField(max_length=200) class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) head = models.CharField(max_length=255) authors = models.ManyToManyField(Author) How do I find authors count ? Let us say I have an Entry object as Entryobject (Entryobject = Entry.objects.filter(blog__name='a') ), I tried as below but got attribute error. Entryobject.authors.count() # got error here Also please let me know how can I query list of authors in Entryobject . -
Unable Force Download File in Django HttpResponse (HTML/ PDF)
I am trying to output HTML or PDF files for download. I have written few lines of code to generate html & PDF file from a template and download it. However, my code is working for Chrome browser only. When I try to download it from other browser (e.g. DuckDuckGo) I am getting my current page (i.e. roll.html) downloaded instead of the file (i.e. file rendered from html_output_template.html) which I want to export. Here's the code I am trying: views.py def generate_html(request, res): cdict = {'res':res, 'date':datetime.date.today()} if request.method == 'POST': inv_form = InvoiceInfoForm(data= request.POST) if inv_form.is_valid(): inv_data = inv_form.cleaned_data cdict = {'res':res, 'inv_data':inv_data, 'date':datetime.datetime.today().strftime("%d %h %Y")} template = get_template('app_name/html_output_template.html') html = template.render(cdict) response = HttpResponse(html, content_type='application/force-download') filename = "Inv_%s.html" %(datetime.datetime.today().strftime("%d_%h_%y_%H_%M_%S")) content = "attachment; filename= %s" %(filename) response['Content-Disposition'] = content return response def MyView(request): """Some Calculations Here""" if 'download_pdf' in request.POST: if inv_form.is_valid(): return generate_pdf(request, res) elif 'download_html' in request.POST: if inv_form.is_valid(): return generate_html(request, res) return render(request,'app_name/roll.html',context=cdict) Sample of html template: html_output_template.html {% load staticfiles %} <!-- Few Lines here --> <tr> <td style="text-align:left">1</td> <td style="text-align:left">{{inv_data.description}}</td> <td style="text-align:right">{{res.rate_per_gram}} {{res.rate_kilo_gram}}</td> <td style="text-align:right">{{res.wgt_of_goods}}</td> <td style="text-align:right">{{res.total_amount}}</td> </tr> I feel there is some problem with my HttpResponse which is getting auto corrected in Chrome … -
Avoid making multiple Django database calls
I would like to query my Django database once and return a Queryset (assigned the name 'codes'), which I can iterate over to obtain each instance's 'internal_code' attribute without making further calls to the database. Here is my code, but I am unsure as to whether I am querying the database each time I use 'get' on the Queryset, and how I can avoid this: codes = models.RecordType.objects.all() permanent = sorted( [(codes.get(industry_code=category.value).internal_code, self.labels.get(category, category.name)) for category in enums.Category]) -
Render the key value of a dictionary based on an event in Django
I have two dropdowns in my .html file of Django app namely: <select class="form-control" id="exampleFormControlSelect1"> <option>op1</option> </select> <select class="form-control" id="exampleFormControlSelect2"> <option>opt1</option> </select> A dictionary is rendered from the Django views.py.I want the keys to be displayed as options in the first dropdown and whenever a key is selected,the corresponding values need to be displayed in the second dropdown.I tried some js and jina Template but no luck.How can I implement it? -
Filter model object by difference in days
My model has a date field and i want to filter the model by the last 7 days. class Count(models.Model): task = models.ForeignKey(Task, related_name = 'counts', on_delete = models.CASCADE) start_time = models.DateTimeField(null = True, blank = True) end_time = models.DateTimeField(null = True, blank = True) time_spent = models.PositiveIntegerField() deleted = models.BooleanField(default = False) class Meta(): ordering = ['accesses'] def __str__(self): return f'{self.task.department} - {self.accesses.first().user} [{self.time_spent} min]' def stamped_date(self): if not self.start_time: return self.accesses.first().date return self.start_time def users(self): return list(set(map(lambda x: x.user, list(self.accesses.all())))) I need to filter every count that has "stamped_date" in the last 7 days. What i tried to do (in the model): def daysBy(self): return (datetime.now() - self.stamped_date()).days to filter like this: Count.objects.filter(daysBy__let = 7) However, datetime.now() requires a timezone object, otherwise will throw the follwing error: TypeError: can't subtract offset-naive and offset-aware datetimes I'm also feeling this might not be the most correct way of achieving my goal, please correct me with a better way. Or.. give me a way of inserting a timezone object related to the TIME_ZONE setting. -
Static files are not fetching in django
My settings description. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/css') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Also, I had added static files to urls.py urlpatterns += staticfiles_urlpatterns() My HTML template {% load static %} <!DOCTYPE html> <head> <meta charset="utf-8"> <title>Things I eat</title> </head> <body> <h1> Hello world</h1> </body> findstatic command output: > python manage.py findstatic styles.css Found 'styles.css' here: /project_name/static/css/styles.css I use django == 3.0.7 I followed advice from similar questions [1,2,3] But my static files are not fetching while rendering. Any advice for debugging? -
CORS-Error when using django as backend for ionic app
I'm using Django Rest Framework as a backend for my Ionic app. I set up the API with JWT and with postman everything works fine. As soon as I try making a API call from my Ionic app I get the following error messages: Error 1 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.mywebsite.com/api/movies. (Reason: header ‘password’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response). Error 2 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.mywebsite.com/api/movies. (Reason: CORS request did not succeed). I run my django app on a apache2 webserver. django-cors-headers is installed, added to installed_apps, added to the middleware and CORS_ORIGIN_ALLOW_ALL = False In my Ionic app the request looks like this: Service fetchMovies() { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.authService.getToken()}`, 'username': 'USERNAME', 'password': 'PASSWORD' }) } return this.http.get(this.url, httpOptions).pipe(tap(resData => { console.log(resData); })); } I get the token like this: getToken() { return this.http.post('https://www.mywebsite.com/api-token', this.params); } And I use the service as follows: ionViewWillEnter() { this.moviesServcie.fetchMovies().subscribe(); } Does anyone have an idea what I'm doing wrong? If you need more information feel free to write a comment! … -
How to access variables class in a child function in Python/Django
Like I said in title I'm trying to access variables class in a child function. In the class I import Json data from a file and I convert them in dict then in variables so far no worries. but I can't access my variables in JsonForm function below to render them in the Form, I've tried many solution with init and self but any works there is my code : class UpdateSwitch: # folder location of my Json data CWD = os.getcwd() JSON_CONFIG_FILE_PATH = '%s/%s' % (CWD, 'mod_switch/EmailDataScript/mailData.json') # I store the data in this viariable CONFIG_PROPRETIES = {} # data are loaded and converted to a dict try: with open(JSON_CONFIG_FILE_PATH) as data_file: CONFIG_PROPRETIES = json.load(data_file) except IOError as e: print (e) print ('IOError: Unable to open mailData.json') exit(1) print (CONFIG_PROPRETIES) # OUTPUT something like this : {'data': 'somedata', 'data2': 'somedata2', 'data3':'somedata3', 'data4': 'somedata4', 'data5': 'somedata5', 'data6': 'somedata6'} # Convert the dict keys to variables and dict values to value of these variables for key,val in CONFIG_PROPRETIES.items(): exec(key + '=val') # And there is what I get(everything work) : data, data1, data2, data3, data4, data5, data6 def JsonForm(request): if request.method == "POST": stackForm = JsonStacksForm() stackForm.Meta.fields = { "ip" : … -
Django: ZipFile does not recognize file as zip: raised BadZipFile or AttributeError
I am trying to handle ZipFile. I have archived 6 images as "images.zip". >>> zf=zipfile.ZipFile('images.zip') >>> zipfile.is_zipfile(zf) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 183, in is_zipfile result = _check_zipfile(fp=filename) File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 169, in _check_zipfile if _EndRecData(fp): File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 241, in _EndRecData fpin.seek(0, 2) AttributeError: 'ZipFile' object has no attribute 'seek' Also when I try to open my file as File in django I get an error. from django.core.files import File f = File(open('images.zip')) >>> zip=ZipFile(f) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 1100, in __init__ self._RealGetContents() File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 1168, in _RealGetContents raise BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a zip file It seems that with the file all is fine, I can unpack it, all images are fine. I can also access other zipfile atributes and functions eg. >>> zf <zipfile.ZipFile filename='images.zip' mode='r'> >>> zf.namelist() ['img6.jpg', 'img5.jpg', 'img4.jpg', 'img4.jpeg', 'img3.jpg', 'img2.jpg', 'img1.jpg'] >>> zf.infolist() [<ZipInfo filename='img6.jpg' compress_type=deflate filemode='-rw-rw-r--' file_size=97335 compress_size=97217>, <ZipInfo filename='img5.jpg' compress_type=deflate filemode='-rw-rw-r--' file_size=83314 compress_size=83030>, <ZipInfo filename='img4.jpg' compress_type=deflate filemode='-rw-rw-r--' file_size=133511 compress_size=132992>, <ZipInfo filename='img4.jpeg' compress_type=deflate filemode='-rw-rw-r--' file_size=154011 compress_size=153871>, <ZipInfo filename='img3.jpg' compress_type=deflate filemode='-rw-rw-r--' file_size=119871 compress_size=119024>, <ZipInfo filename='img2.jpg' compress_type=deflate filemode='-rw-rw-r--' … -
Django Rest Framework is detecting AnonymousUser on PUT requests
I have this viewset class OrderItemViewSet(viewsets.ModelViewSet): serializer_class = OrderItemSerializer def get_queryset(self): print('Current User', self.request.user) return OrderItem.objects.filter(order__owner=self.request.user.profile) take note of the print('Current User', self.request.user) I have used that to identify the root of the problem. urls.py router.register('order_items', shopping_api.OrderItemViewSet, 'order_items') So far so good... But when I make a PUT request; const response = await fetch(api.authurl+'/order_items/'+order_item.id+'/', { method: 'PUT', headers: api.httpHeaders, body: JSON.stringify(order_item) }); This error shows up AttributeError: 'AnonymousUser' object has no attribute 'profile' The print statement identifies these for a GET then a POST request respectively: [19/Jun/2020 20:17:22] "GET /sellers/3/ HTTP/1.1" 200 196 Current User AD [19/Jun/2020 20:17:30] "GET /order_items/ HTTP/1.1" 200 1060 Current User AnonymousUser So I have reason to believe that when I make a get request, the authenticated user is detected, but with a PUT it's suddenly Anonymous. I doubt I have to make frontend authentication right? e.g having Authorization with a token in my headers in the request. Since I have that GET request doing fine. -
Need to get all permissions for groups assigned to a custom table
We are using the standard contrib auth app in Django, which, of course, allows permissions to be assigned directly to users, and/or to groups, with the groups then being assigned to users. Before I knew about the get_all_permissions() method of the User object, I had my own method that returned all permissions for a user using this statement: user_permissions = Permission.objects.filter(Q(user=user) | Q(group__user=user)).all().distinct() I'm sure I found that code after searching about how to get all permissions, and just copy/pasted it into my code. We now want to add groups at a different level in our site. We assign users to projects via the ProjectUser model, which essentially has foreign keys to project and user. We want to add group to that model so that, for example, a user (developer) could be "project lead" on one project, but just a "contractor" on another. I added a many-to-many field named "groups" to the ProjectUser model, but now I'm not sure what the statement equivalent to the one shown above would be to get all project-level permissions. -
Can't create object in django
I'm trying to make django app somthing like instagram where you can post images. I have my code with no errors but can't create object post. I can display template in html but after i fill the fields and click button submit nothing happend besides reloading site. models.py: from django.db import models from django.contrib.auth import get_user_model import datetime # Create your models here. User = get_user_model() class Post(models.Model): author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) image = models.ImageField(upload_to='media') caption = models.TextField(blank=True, null=True) date_of_publication = models.TimeField(blank=True, default=datetime.datetime.now()) forms.py: from django.forms import ModelForm from .models import Post #POST FORMS.PY class PostForm(ModelForm): class Meta: model = Post fields = ['user', 'image', 'caption'] exclude = ['user'] views.py: from django.shortcuts import render from .forms import PostForm from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect # Create your views here. @login_required def create_post(request): if request.user.is_authenticated: if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save(commit=False) form.user = request.user form.save() return HttpResponseRedirect('/about/') else: form = PostForm() return render(request, 'posts/create_post.html', {'form':form}) -
Getting an error: got an unexpected keyword argument 'version'
I was doing the Django haystack tutorial, and when I run the search query, I get the error __call__() got an unexpected keyword argument 'version'. This error is coming from Django. I am fairly new to Django, and I'm not sure what all to add to help debug this. Also, in engine, I am using haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine, and am using ElasticSearch v7 -
How can I access another field of a related ManyToMany table?
Let's say I have the following models: class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) upload = models.ForeignKey(related_name='x1', Uploads) class Uploads(models.Model): topic = models.CharField(max_length=100) I want to select all the Articles of a specific upload topic along with their Publication title. So my output should be: <QuerySet [{'id': 1, 'headline': 'headline1', 'publications': 'publication title 1'}, {'id': 2, ''headline': 'headline2', 'publications': 'publication title 2'},] Currently I have this: Dataset.objects.filter(upload__topic='sports').values('id', 'headline', 'publications') which gives me the following: <QuerySet [{'id': 1, 'headline': 'headline1', 'publications': 1}, {'id': 2, ''headline': 'headline2', 'publications': 2},] I know I can loop over the QuerySet and for each publication fire another DB query towards the Publication table to get the relevant title, but I'm wondering if there's a better way to do that. Perhaps with a single query? -
Circular Dependency between Form and Model
Here is a form: class ToDoItemModelForm(forms.ModelForm): class Meta: from ToDoDashboard.models import ToDoItem model = ToDoItem fields = ['description', 'label', 'comment', ('start_date', 'due_date', 'time_estimate_hours')] def clean(self): start_date = self.cleaned_data.get('start_date') end_date = self.cleaned_data.get('due_date') if start_date > end_date: raise forms.ValidationError("Dates are incorrect") return self.cleaned_data and here is a model: class ToDoItem(models.Model): dashboard_column = models.ForeignKey(DashboardColumn, on_delete=models.CASCADE) description = models.TextField() label = models.CharField(max_length=128) start_date = models.DateTimeField(null=True) due_date = models.DateTimeField(null=True) from ToDoDashboard.forms.ToDoItemForm import ToDoItemModelForm form = ToDoItemModelForm Now it says ImportError: cannot import name 'ToDoItem' from partially initialized module 'ToDoDashboard.models' (most likely due to a circular import) How to solve the problem? -
URL Routing trouble in React + Django
I have the following urlpatterns configured for my Django app. This rule will route to http://localhost:8000/profile/. urlpatterns = [ path("profile/", test_frontend_views.profile), ] The views code: def profile(request): return render(request, 'frontend/Profile_temp_master.html') Within my React components that are dynamically creating HTML for the template, I am making requests to my Django backend API with the following scheme: fetch("api/profile", requestOptions).then(..).then(..) However, rather than this request routing to http://localhost:8000/api/profile/, it is routing to http://localhost:8000/profile/api/profile/ which is not a valid endpoint and returns and error. How can I solve this so that the URL routes to the correct endpoint? -
Why do I get a Key Error for 'post' in PostListView
I don't know why I got a Key Error message (KeyError at / 'post') when I def get_context_data in PostListView. But that was totally fine when I just def get_context_data in PostListDetailView. Views.py def home(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'posts': Post.objects.all(), 'is_liked': is_liked, 'total_likes': post.total_likes(), } return render(request, 'blog/home.html', context) def like_post(request): # post like post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True return HttpResponseRedirect('http://127.0.0.1:8000/') class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 is_liked = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['post'] if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return context class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post is_liked = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['post'] if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return context -
Admin Section with Users and Groups Disappeared
I want to add custom views and templates to Admin and wrote this: # in models.py class MyAdminSite(admin.AdminSite): def my_view(self, request): return HttpResponse("Test") def get_urls(self): from django.urls import path urlpatterns = super().get_urls() urlpatterns += [ path('my_view/', self.admin_view(self.my_view)) ] return urlpatterns admin.site = MyAdminSite() # and in apps.py class MyAdminConfig(AdminConfig): default_site = 'ToDoDashboard.admin.MyAdminSite' I have registered all the models and I see them in my custom Admin panel. However, the section with users and groups has disappeared. How to get it back? -
Query database in django using model procedure
I have created model with procedure that subtract two dates from fields in model returning days difference between them, for example: class Example: earlierDate=models.DateField() laterDate=models.DateField() def day_diff(self): return (laterDate-earlierDate).days Is it possible to query database including day_diff procedure ? in_views_query=Example.objects.filter(day_diff__gte=30) When i use this kind o query it shows me that there is no field 'day_diff' Regards -
How to redirect to post detail page after deleting a comment in Django?
Can someone help me out please. I want to redirect to a post detail page after deleting a comment of a given pk. I got an AttributeError when ever I hit the comment delete button. Error: function object has no attribute 'format' If I change my success_url of the comment delete view to redirect to post list page with no argument, it works well but that's not what I want. I need the user to be redirected to post detail page after deleting a comment. Here's my Post model STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') objects = models.Manager() published = PublishedManager() tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[self.pk, self.slug]) def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs)''' **Comment model** ```class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) comment = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.author} on {self.post}' def get_absolute_url(self): return … -
Unable to access static files in Django - Development server
I am trying to access static files in browser but unable to access them. My static settings insettings.py are below STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") My urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', FrontPage.as_view()), # url('', include(router.urls)) ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My folder structure projectname projectname settings.py urls.py app1_name static bootstrap css cover.css templates My template.html <link href="/static/bootstrap/css/cover.css" rel="stylesheet"> The above link isn't loading the static file. Please let me know where am I going wrong. -
TypeError: __init__() got an unexpected keyword argument 'instance' for custom user in Django
When I am trying to register a custom user or when i am trying to view profile of login user, i am getting this error. I am not sure why i am getting this error, Here is my code, please suggest where i am doing wrong. Thank you in advance. Url.py path('register/', RegisterView.as_view(template_name='users/register.html'), name='register'), path('profile/', user_views.profile, name='profile'), Model.py user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=254, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser # notice the absence of a "Password field", that is built in. USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # Email & Password are required by default. objects = UserManager() ``` Form.py ``` class RegisterForm(forms.Form): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: Model = User fields = ('email',) def clean_email(self): email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") return email def clean_password2(self): # Check that the two password …