Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save extra fields on registration using custom user model in DRF + django-rest-auth
Using Django REST Framework (DRF), with django-rest-auth, I created a custom user model with one extra field. My aim is to use the django-rest-auth registration endpoint to register a new user in one request, and thus sending all the data to create a new user, including the data for the extra field. I am using AbstractUser, since it seems recommended for beginners, where more advanced developers could use AbstractBaseUser. This is also why the following SO answers looks too complicated for what I want to achieve: link here. I know this question has been asked multiple times, but the answers are not exactly what I am looking for. For a beginner like me this is complicated stuff. So, my question is, can anyone explain how to achieve what I want? I am using: Django 2.1.4 django-allauth 0.38.0 django-rest-auth 0.9.3 djangorestframework 3.9.0 Here's the code that I have up until this point: Used this tutorial to get to this code settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '!gxred^*penrx*qlb=@p)p(vb!&6t78z4n!poz=zj+a0_9#sw1' … -
Django dict key,value in for loop does not work
I'm getting a little stuck on a Django problem where I can't access the values of a dict in a for loop. It works outside the for loop, just not inside. Am I missing the obvious here? Python: err{} err['else'] = {'class': 'Low', 'txt': 'zero'} err['if'] = {'class': 'High', 'txt': 'one'} data = { 'errors': err } return render(request, 'index/error.html', data) HTML template: <p>{{ errors }}</p> <p>{{ errors.if }}</p> <p>{{ errors.if.class }}</p> {% for error in errors %} <div class="{{ error.class }}"><p>{{ error.txt }}</p></div> {% endfor %} The upper 3 lines are for code debugging and work just fine. The for loop doesn't produce any code. Best regards, LVX -
Face Recognition For Web application
I am currently working on a project- facial recognition + Web application for banks. I am done with the front-end part, but the problem is that I don't know how to implement the facial recognition part. Any help please?? -
AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user'
I can't get this to work. I've researched what this error means and have really only received a response close to "change MIDDLEWARE to MIDDLEWARE_CLASSES". This did not work. I've tried rearranging Middleware Classes, however, this too did not work. Is there anything in my code i should be concerned with that is causing this error? Traceback (most recent call last): File "C:\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python37\lib\site-packages\django\contrib\admin\sites.py", line 241, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "C:\Python37\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Python37\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Python37\lib\site-packages\django\contrib\admin\sites.py", line 212, in inner if not self.has_permission(request): File "C:\Python37\lib\site-packages\django\contrib\admin\sites.py", line 186, in has_permission return request.user.is_active and request.user.is_staff AttributeError: 'WSGIRequest' object has no attribute 'user' settings.py """ Django settings for trydjango19 project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start … -
Multiple left join and left join against the same model raw query convert to Django ORM
Using Django 1.11 I have the following models: class Product(Model): class Pricebook(Model): class Quote(Model): class SKU(Model): product = models.ForeignKey(Product) pricebook = models.ForeignKey(Pricebook) class SKUPrice(Model): sku = models.ForeignKey(SKU, related_name="prices") class LineItem(Model): quote = models.ForeignKey(Quote, related_name="quote_line_items") sku = models.ForeignKey(SKU) This is the raw query that works for me. SELECT qli.quantity, sku_source.product_id, sku_dest.id as sku_dest_id, sku_dest_price.id as sku_dest_price_id FROM lineitem qli INNER JOIN sku sku_source ON qli.sku_id = sku_source.id LEFT JOIN sku sku_dest ON sku_dest.pricebook_id = sku_source.pricebook_id AND sku_dest.product_id = sku_source.product_id LEFT JOIN skuprice sku_dest_price ON sku_dest_price.status = 'default' AND sku_dest_price.sku_id = sku_dest.id WHERE qli.quotation_id = 40 AND qli.quantity > 0 AND sku_dest.vendor_id = 38; What I have tried is: the_quote_with_id_as_40.quotation_line_items.filter(quantity__gt=0).select_related('sku__product').values('sku__product__id', 'quantity'); This produces this query SELECT "sku"."product_id", "lineitem"."quantity" FROM "lineitem" INNER JOIN "sku" ON ("lineitem"."sku_id" = "sku"."id") WHERE ("lineitem"."quotation_id" = 40 AND "lineitem"."quantity" > 0) which is not exactly what I want. I can of course use raw query. But I would like to know if possible to use ORM. At the very least, of expanding my knowledge. Thank you. -
Reverse for 'product_list' with arguments '('cars',)' not found
I get the following error when i try http://192.168.1.107:8000/shop/. However I do not get any errors when my shop_urls.py looks like this urlpatterns = [ path('shop/', views.product_list, name='product_list'), re_path(r'shop/(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list'), ] why can't I use a different name like product_list_by_category? Also, 'cars' is a category slug name and I do not understand why it isbeing called. Error Reverse for 'product_list' with arguments '('cars',)' not found. 1 pattern(s) tried: ['shop\\/$'] Request Method: GET Request URL: http://192.168.1.107:8000/shop/ Django Version: 2.1.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'product_list' with arguments '('cars',)' not found. 1 pattern(s) tried: ['shop\\/$'] Exception Location: /home/gravityns/PycharmProjects/prodgdscorehome/venv/lib/python3.6/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 622 Python Executable: /home/gravityns/PycharmProjects/prodgdscorehome/venv/bin/python Python Version: 3.6.7 Python Path: main.urls urlpatterns = [ path('admin/', admin.site.urls), path('', include(('gdsauth.urls','gdsauth'), 'gdsauth')), path('', include(('gdsshop.urls','gdsshop'), 'gdsshop')), ] shop_urls.py path('shop/', views.product_list, name='product_list'), re_path(r'shop/(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_category'), re_path(r'shop/(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.product_detail, name='product_detail'), View in question def product_list(request, category_slug=None): context = {} category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) context['title'] = 'Shop' context['category'] = category context['categories'] = categories context['products'] = products return render(request, 'gdsshop/products/list.html',context) models class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') def get_absolute_url(self): return reverse('gdsshop:product_detail', args=[self.id, self.slug]) class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, … -
How to create the manytomany "Through" object automatically?
My django project contains three models: Article, Section and ArticleSection ArticleSection is the manytomany model of relation between Article and Section. The detail view of Article has "Add Section" and the section form works for adding a new section. And right now I have to go to another form of ArticleSection to create a new ArticleSection object to link the article and section explicitly. class Article(models.Model): owner =models.ForeignKey(User, null=False) name =models.CharField(max_length=120, null=False, blank=False) description =models.CharField(max_length=120, null=True, blank=True) class Section(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) articles = models.ManyToManyField('articles.Article', through='articlesections.ArticleSection', related_name='sections') name = models.CharField(max_length = 120) class ArticleSection(models.Model): section = models.ForeignKey("sections.Section", related_name='articlesection', on_delete=models.SET_NULL, null=True, blank=True) article = models.ForeignKey("articles.Article", related_name='articlesection', on_delete=models.SET_NULL, null=True) description= models.CharField(max_length = 120) I would expect the "Add Section" in article detail view would create the section and automatically create the ArticleSection object to link the source article and the newly created section object. Thanks BY -
Don't use `get_queryset()` while creating
Let's say you are modifying get_queryset in you manager something like this class VoteManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_deleted=False) class Vote(models.Model): objects = VoteManager() This works as expected but the problem when you use something like get_or_create on Vote model it creates an instance even if it is present in the database because we modified the get_queryset() method. Can we not shadow the soft-deleted instance while creating?? -
FieldError: Cannot resolve keyword 'published_date' into field.
i am creating a new blog django apllication but when run it i got error here is my code #model.py class Post(models.Model): author=models.ForeignKey('auth.user',on_delete=models.CASCADE) title=models.CharField(max_length=200) text=models.TextField() create_date=models.DateTimeField(default=timezone.now()) pubished_date=models.DateTimeField(blank=True,null=True) def publish(self): self.pubished_date=timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comments=True) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title class Comment(models.Model): post=models.ForeignKey('blog.Post',related_name='comments') author=models.CharField(max_length=200) test=models.TextField() create_date=models.DateTimeField(default=timezone.now()) approved_comment=models.BooleanField(default=False) def approve(self): self.approved_comment=True self.save() def get_absolute_url(self): return reverse('post_list') def __str__(self): return self.text whenerver i run server i got this field error message. i m new to django -
Is there any way to get 'views.py' of pre-installed apps in django especially 'auth' app?
I got 403 Forbidden while loading my web page, and it says to ensure that 'The view function passes a request to the template's render method.' also i tried all other solutions. if there's any alternate solution please suggest. PS: IT WORKS FINE IN FIREFOX, NO FORBIDDEN ERROR. BUT NOT IN CHROME(i've ensured that it accepts cookies). -
html alert window mode
I have one django project. In the html template, I want to show one alert window after clicking the button. I use the following java function to show the window, but I don't how to adjust the position & text size of such window and also how to hide the default sentence " website says:". Can any one help? Thx! <script LANGUAGE="javascript"> function word() { alert("Start") } </script> <button type='submit' class="btn btn-primary" style="font-size:15px;" onclick="word()"> Start </button> -
How to give initial data to put method ,Django (I want to create edit profile page)
I want to have an edit profile page in django,and I want when user enter this page current username fill username box and if he want then he can change username. I have this put method: def get_object(self, pk): try: return User.objects.get(pk=pk) except Exception as e: raise Http404 def put(self, request, pk, format=None): user = self.get_object(pk) serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) how can i do this? -
django user registration error with django_rest_auth package
i used django rest auth in my project,but i get these error when i try to create a new user [WinError 10061] No connection could be made because the target machine actively refused it -
Django: Where generic forms like LoginView renders functions dictionary fill and how can I change it
I use LoginView class in Django. We can use this class as login view with a HTML template, like below: urls: from django.contrib.auth.views import LoginView urlpatterns = [ path('', LoginView.as_view(), {'template_name': 'login.html'}), ] login.html: <head> <title>test<title> {% load static %} </head> <body> <form method="POST"> {% csrf_token %} {{ form.as_p }} </form> </body> my question is where renders function dictionary or httprequest fill? and how can I change, form.as_p to login_form.as_p, for example? -
Django DateTimeField says 'You are 5.5 hours ahead of server time.'
In one of my model I am storing time_stamp = models.DateTimeField(default=timezone.now) But when I save the model it says You are 5.5 hours ahead of server time. for example local time in my machine is 13:02 but after saving what gets stored in db is 7:16 I got one related here but it does not an have a satisfying answer... models.py class Comment(models.Model): time_stamp = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.time_stamp = timezone.now() return super(Comment, self).save(*args, **kwargs) -
adding and removing a class to element using javascript
I have a javascript intended to add specific ads to favorite list when user click on favorite icon. Now, I want to change this icon from empty to solid (through removing and adding different class). Note: I am using Django for the backend and font awesome for the icon I wrote a javascript line to select the specific icon has been clicked. However, I got an error telling me that Cannot read property 'classList' of null. I added if statement to make sure that specific code is executed.Hence, I got rid of the error but the code still not working as I want and still not be able to add and remove the class upon the user add and remove the item to and from the favorite list. here is the code: <i id="favouriteBtn_{{item.id}}" onclick="currentAddFav({{item.id}})" title="add this ads to favorite list " class="fa fa-star-o favo_ls"> </i> this is the javascript portion: function currentAddFav(item_id){ if (localStorage.getItem('favourites')) { // If there are favourites var storage = JSON.parse(localStorage['favourites']); if (storage.indexOf(item_id) == -1) { // not found storage.push(item_id); localStorage.setItem('favourites', JSON.stringify(storage)); console.log('item has been added to favorites') cc="#favouriteBtn_"+item_id console.log(cc) var fav_solid = document.getElementById(cc); if (fav_solid){ fav_solid.classList.remove("fa-star-o"); fav_solid.classList.add("fa-star");} } else { // found storage.splice(storage.indexOf(item_id),1) localStorage.setItem('favourites', JSON.stringify(storage)); … -
Create a table for each entry in a model
I am new to python and django, I Want to add a table dynamically in the database when a new user register (in python way of course), in other words when a user inserts a new data into a model i want to create a table explicitly for that entry, to add extra Data which will related with that entry. I think python has an easy way to handle this kind of situation Image representation -
How to use user uploaded image in Django template
Before marking this question duplicate please be informed that I have tried looking existing q/a and other tutorial along with documentations. My problem is I am unable to use images in templates that are uploaded by an admin with admin interface. I have configured my settings and urls according to documentation. in browser inspect element it is showing <img src(unknown)> uploaded image by an admin using admin interface is stored in the /media/ which is media root. location of the image is /media/img/imagename.jpg settings.py # media MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py (my project url file) from django.conf import settings from django.conf.urls.static import static ## urlpatterns here if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_URL) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_URL) models.py class AboutMe(models.Model): image = models.ImageField(upload_to='img') ## other fields views.py def index(request): aboutme = models.AboutMe.objects.all() context = {'information': aboutme,} return render(request, 'portfolio/index.html', context) template/index.html {% for info in information %} <img src="{{ info.inage.url }}"/> <div class="name-profile t-center"> <h5 class="uppercase">{{info.name}}</h5> </div> {% endfor %} -
django:type(int instance) shows long
order = OrderCacheTab.objects.filter(order_id=3001180).first() print type(order.status) #order.status=7 》》》》<type 'long'>` with DB mysql,the order.status is INT(11) with frame django 1.6.11, status = models.IntegerField() # python console showed the right answer:int pycharm run console and degug console shows wrong answer type 'long' -
I updated Python to a newer version, now running python in my virtualenv prints out errors
I get this error when I try to run python myvenv) C:\Users\SONY\Desktop\djangoproject>python Fatal Python error: Py_Initialize: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' Current thread 0x000021f0 (most recent call first): Any ideas on how I can fix this please?? -
Illustrated texts in Django model
I am trying to make one Blog using Django 2.0 and I have already created a primitive one. It has a Post model which is as follows: class Post(models.Model): PriKey = models.CharField(max_length=255,primary_key=True) Heading = models.CharField(max_length=100) DateOfPost = models.DateField(default=datetime.date.today()) Content = models.TextField() As it can be seen, the content area is only textual and as of now, I can't add any special style or pictures inside my content. I thought of using HTML tags inside the text content but they are appearing unchanged when the web page is rendered. So my question is, is there any way of storing pictures along with the text in the content field of the Post model? I want to make something like this Is there any way of showing the pictures in there respective positions using Django model? If no, is there any other way of doing this? Also, is there any way of storing HTML codes inside django models and render them as it is when the website is run? -
Angular push to Django for user login form error "SyntaxError: Unexpected token < in JSON at position 2 at JSON.parse (<anonymous>)"
I'm assuming that the < is because it's returning a HTML or XML response. This is my login part where it's failing. public login(user) { this.http.post('/api-token-auth/', JSON.stringify(user), this.httpOptions).subscribe( data => { console.log('login success', data); this.updateData(data['token']); }, err => { console.error('login error', err); this.errors = err['error']; } ); user returns {username: "user", password: "password"} JSON.stringify(user) returns {"username":"user", "password":"pass"} this.httpOptions returns {headers: HttpHeaders} with array content-type application/json console is returning the err 'login error' and I don't know why This is the error: HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8000/api-token-auth/", ok: false, …} error: {error: SyntaxError: Unexpected token < in JSON at position 2 at JSON.parse (<anonymous>) at XMLHttp…, text: "↵↵<!doctype html>↵<html>↵<head>↵ <base href="/"…s"></script>↵</body>↵</html>↵ "} headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message: "Http failure during parsing for http://localhost:8000/api-token-auth/" note: I temporarily disabled csrf middleware because I was running into an issue there as well, not sure if related. -
Getting and cleaning data from non-model form
I'm pretty experienced with model forms and know how to obtain data from them within a view. Example: if form.is_valid(): instance = form.save(commit=False) name = instance.name I'm using a non-ModelForm (i.e. forms.Form) for the first time. Within my view, I'm not sure how to obtain the cleaned form data from the form before saving it to a model. I've tried the following, but it doesn't seem to work. if form.is_valid(): name = form.get('name') Within the 'if form.is_valid():' section of a view, how would you: a) Obtain the form data b) Clean the form data Thanks so much! -
How to fetch Django related model rows and return as a list of dictionary?
AM using Django v1.11 I have the following models: class LineItem(): quote = models.ForeignKey(Quote, related_name="quote_line_items") sku = models.ForeignKey(SKU) class Quote(): def fetch_as_list_of_dict(self): return LineItem.objects.filter(quote=self).select_related('sku__product').values() class SKU(): product = models.ForeignKey(Product) My fetch_as_list_of_dict fails to contain the sku.product_id or sku.product object. I only need to get the sku.product_id as part of a dictionary which in itself is one of many in a list. How do I achieve this? -
Django db_index=True not creating index, but class Meta indexes yes
In my django model, when creating indexes via db_index=True in field definitions, the index is not created. Only if I created in the class Meta class Agreement(UUIDPrimaryKey): job = models.ForeignKey( 'posts.Job', on_delete=models.CASCADE, verbose_name=_("job"), ) class Meta: indexes = ( models.Index(fields=['job']), ) And if I run makemigrations, the index is created. Create index agreements__job_id_eb7df0_idx on field(s) job of model agreement But If I change my model to: class Agreement(UUIDPrimaryKey): job = models.ForeignKey( 'posts.Job', on_delete=models.CASCADE, verbose_name=_("job"), db_index=True, ) And I run makemigrations, the index is deleted. Remove index agreements__job_id_eb7df0_idx from agreement Should not be the same both definitions?