Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create new user to login from different model?
i've try to create a system for student and teachers, create new user model to login from different model , not a OneToOneField from default User model , i want to make two different registration form for visitors (Student and Teacher) forms genders_selection = ( ('male','male'), ('female','female') ) class CustomUser(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) email = models.EmailField() objects = UserManager() def __str__(self): return self.username class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(choices=genders_selection,max_length=10) age = models.PositiveIntegerField() class Teacher(models.Model): teacher = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(choices=genders_selection,max_length=10) age = models.PositiveIntegerField() def __str__(self): return self.user.username but this architecture wont allow similar idea , and it will required first to create User then select one of them as student or teacher !? thanks for helping -
How to import model of of 1 project to another project in django?
I have 2 different django projects.I am trying to import model of project2 to project1, i am using same database for both the projects.How will i achieve that, here is my project structure all_pro_folder /project1_folder/ /src_project1 /app1(application) + projectfolder containing settings.py models.py, views.py etc /project2_folder/ /src_project2/ /app2(application) + projectfolder containing settings.py models.py, views.py etc I want to import src_project2's model in src_project1 just like from src_project2.app2.models import * -
local variable 'mobile' referenced before assignment
I want that when the user logged in, the data from the database should be displayed on the page. Here is the view: def login_view(request): if request.method == 'POST': mobile= mobile.objects.all() form= AuthenticationForm(data=request.POST) if form.is_valid(): user=form.get_user() login(request,user) return render(request,'pages/store.html',{'mobile':mobile}) else: form= AuthenticationForm() return render(request, 'pages/login.html', {'form':form}) The HTML page: {% load static %} <html> <head><title>store</title></head> <body> Hi {{user}} <table> <thead> <tr> <th>Model</th> <th>Price</th> </tr> </thead> <tbody> {% for item in mobile %} <tr> <td>{{ item.Model }}</td> <td>{{ item.Price }}</td> </tr> {% endfor %} </tbody> </table> </body> </html> My model consists of mobile and Price as attribute. I have tried creating a view to display the database: def display_view(request): if request.method == 'GET': mobile= mobile.objects.all() return render(request,'pages/store.html', {'mobile':mobile}) But the error showing is the same: local variable 'mobile' referenced before assignment Can anyone help me out in displaying the data to the page? I don't think the error is because I have created the signup and login forms using django built-in form. -
How to send email from my G-Suite account using Django and OAuth 2?
How to send email from my G-Suite account using Django and OAuth 2 ? I am using Django to send email but its asking me to make my account enable for less secure app. I don't want to do that, I want to use OAuth 2 in my app and send email from my G Suite account. -
Vue vs React vs Angular with Django?
I'm a Django developer planning to learn a front end framework so I could easily scale my applications.The thing that is bothering me is Which is the most simpler and easier to use framework in Vue,react and Angular that I can get started within a day,build some projects and doesn't come up with a lot of confusing things to learn about and most important is easy to integrate with Django to build large scale applications.Which one is the most appropriate in this case? -
How to access Django Docker app in a Virtual Machine?
Currently, I'm trying to access a simple Django application, which I created in an Azure Virtual Machine. As the application is still simple, I only want to access the "The install worked successfully! Congratulations!" page from my local machine by accessing http://VM_IP:PORT/. I was able to do just that, but when I tried to Dockerized the project and then trying to access it again from my local machine, it didn't work. I've already made some setup in my Azure portal so that the Virtual Machine is able to listen to specific port; in this case is 8080 (so http://VM_IP:8080/). I'm quite new in Docker so, I'm assuming there was something missing in the Dockerfile I've created for the project. Dockerfile RUN mkdir /app WORKDIR /app # Add current directory code to working directory ADD . /app/ # set default environment variables ENV PYTHONUNBUFFERED 1 ENV LANG C.UTF-8 ENV DEBIAN_FRONTEND=noninteractive # set project environment variables # grab these via Python's os.environ# these are 100% optional here ENV PORT=8080 # Install system dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ tzdata \ python3-setuptools \ python3-pip \ python3-dev \ python3-venv \ git \ && \ apt-get clean && \ rm -rf … -
Django reading data from 2 models with foreignkey and make single list
I'm new to django. I've been coding with sql but django orm is hard for me to convert my knowledge of sql to orm models. I've client model class client(models.Model): c_id = models.AutoField(primary_key=True) name= models.TextField() age=models.IntegerField() and address model class address(models.Model): c_id = models.ForeignKey(client, on_delete=models.CASCADE) addr = models.CharField(max_lenght=20) city= models.CharField(max_lenght=20) This is my table --------------------------- | c_id|Name | age | --------------------------- | 1 | John | 23 | ---------------------------- | 2 | Rose | 20 | ---------------------------- ------------------------------ | c_id|addr | city | ------------------------------ | 1 | buspark | florida| ------------------------------ | 2 | homesquare| florida| ------------------------------ how to get allclient with address in list -
Django - database query optimisation - over 100 queries per request
models.py class Category: name = ... class SubCategory: name = ... category = models.ForeignKey(Category) class Item: name = ... category = models.ForeignKey(Category) subcategory = models.ForeignKey(SubCategory) class ItemImage: item = models.ForeignKey(Item) image = ... views.py def show_all(request): categories = Category.objects.all() return render(request, 'template.html), {'categories':categories}) template.html {% for cat in categories %} <!-- cat.name --> {% for subcat in cat %} <!-- subcat.name --> {% for item in subcat.item_set.all %} <!-- item.name --> <img src="{{item.itemimage_set.first.image.url}}"> Problem: The last iteration in html for itemimage_set causes extra query for each item rendered. I've got 300 items to render on the page, then over 300 queries for each request. Not sure where to add prefetch... or this is unavoidable? Please help! -
How to Setting Up Django Static Files?
So for settings up my django static files I added these code in settings.py STATIC_URL = '/static/' STATIC_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') So I created A static folder In Base Directory and then I created a folder named css inside of it and I added a file named nav.css into it. <link rel="stylesheet" href="{% static 'css/nav.css' %}"> But it's not working at all. It gives me error : Failed to load resource: the server responded with a status of 404 (Not Found) What I did wrong? -
Django summernotes model customize
I am currently working on django summernotes but facing trouble in form submission. I think it is due to the model models class htmlpage(models.Model): id= models.AutoField(primary_key=True) title = models.CharField(max_length=50) content = models.CharField(max_length=2000) thumbnail = models.ImageField(upload_to='images/blog') tags = models.CharField(max_length=50) ... def __str__(self): return self.title The content Field in the model is implemented with summernotes. forms.py class FormName(forms.Form): title = forms.CharField(required=True) thumbnail = forms.ImageField(required=True) content = forms.CharField(widget=SummernoteWidget(), required=True) tags = forms.CharField(required=True) How to save data in Django in-order to separate the media files inside the summernotes. Currently all the image files are getting stored as text in Charfield. This way works fine for retrieving and displaying but having trouble in validating the form created. is_valid() is becoming false for every form submit. You can submit the form without is_valid() but image is not uploaded in database. form = forms.FormName() if request.method == "POST": form_name = FormName(data = request.POST) title = form_name["title"].data thumbnail = form_name["thumbnail"].data content = form_name["content"].data tags = form_name["tags"].data instance = htmlpage(title=title, thumbnail=thumbnail, content= content, tags=tags, by=request.user) instance.save() -
Django RestFramework Elastic Search: Timeline API
I'm using django restframework along with elastic search to develop a backend application for a mobile app. I need to develop a timeline API that will load a timeline of posts from other users the user is following. Along with other related poststhat the people they're following may comment. What is the best implementation method for this problem? -
duplicate key value violates unique constraint "booking_reservation_student_id_key" DETAIL: Key (student_id)=(1) already exists
I am new to Django and currently working a hostel booking system. I however experincing some errors. Firstly,I want the is_reserved field in the room model to be True upon reservation,I have tried manay ways but it doesnt work for me. Secondly,I get an error when a user tries to book twice,Is there any way I cane solve this error: Here is my code and errors displayed: def RoomBookingView(request,pk): if request.method == 'POST': if pk: room_id = Room.objects.get(pk = pk) student_id = request.user reservation = Reservation( room_id = room_id.id, student_id = student_id.id, ) reservation.save() room_id.is_reserved = True return redirect('confirm') return render(request,'room-detail.html',{}) class Reservation(models.Model): student = models.OneToOneField(User,on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete = models.CASCADE) start_date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Reservation' verbose_name_plural = 'Reservations' def RoomBookingView(request,pk): if request.method == 'POST': if pk: room_id = Room.objects.get(pk = pk) student_id = request.user reservation = Reservation( room_id = room_id.id, student_id = student_id.id, ) reservation.save() room_id.is_reserved = True return redirect('confirm') return render(request,'room-detail.html',{}) class Room(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200,null=True,blank=True,unique=True) price = models.IntegerField() hostel = models.ForeignKey(Hostel,on_delete=models.CASCADE,null=True) number_of_beds = models.IntegerField() room_thumbnail = models.ImageField(null=True) resized_thumbnail = ImageSpecField( processors=[ResizeToFill(620, 430)], format='JPEG', options={'quality': 60}) room_type = models.ForeignKey(Category,on_delete=models.CASCADE) room_number = models.IntegerField() is_reserved = models.BooleanField(default=False) description = models.TextField() def get_absolute_url(self): return … -
How to create templates folder inside of an app in Django?
So Basically I like to create templates folder in main project directory and than I just create HTML file inside of it. But now I want to create this templates folder inside of an app. How can I do it? Thanks Good people in Advance. -
Is there a method to create a persistent variable in my Django view function?
I'm currently grabbing a variable 'type' via GET when my view function is called, as shown. I need to query by this variable in my POST method. def article_delete_view(request, pk): type = request.GET.get('type') #GET THE VARIABLE from referring data-url obj = Listing.objects.get(type=type) # I could query here if I wanted (illustration only) article = get_object_or_404(Article, pk=pk) data = dict() if request.method == 'POST': article.delete() data['form_is_valid'] = True articles = Article.objects.all() obj = Listing.objects.get(type=type) #THIS DOES NOT WORK, since 'type' is not passed on submit. context = {'articles':articles, 'obj':obj} data['article_table'] = render_to_string('article_table.html', context) else: context = {'article':article} data['html_form'] = render_to_string('article_delete.html', context, request=request) return JsonResponse(data) Is there a best-practice way to make that variable persist when POST is called on a submit? I know declaring a global is a bad idea. Thought about writing it to memory (attached to article) but that feels like a hack. I could get my <input> method to pass 'type' but to do so I'd have to refactor a lot of other things. Are django session variables the answer here? Any perspective is helpful. Thanks in advance. -
When are Django model objects initialized?
I'm facing an interesting problem in Python with Django. I think just by putting my code you will get what I'm trying to do. views.py: def ingredients(request): objects = Ingredient.objects.all()[:50] return render(request, 'template.html', {'objects': objects} models.py: class Ingredient(models.Model): stock_by = models.IntegerField(null=False) unit = "" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) unit_type = { 1: 'Units', 2: 'Kilograms', 3: 'Litters' } self.unit = unit_type[IntegerField.to_python(self.cost_by)] Error: TypeError at /Ingredient/ to_python() missing 1 required positional argument: 'value' (Value is None). I think it's clear what I'm trying to achieve. Just a String attribute which will take the name of the unit value (represented by integers in db). -
Trying to understand why Selenium cannot see Binary at '/app/.apt/usr/bin/google-chrome' error despite solutions tried - using Heroku
I am trying to use Selenium and Heroku I've run into a common error: selenium.common.exceptions.WebDriverException: Message: unknown error: no chrome binary at '/app/.apt/usr/bin/google-chrome' I've come across this article as to why this may be happening: WebDriverException: Message: unknown error: no chrome binary at C:/.../Chrome/Application/chrome.exe with ChromeDriver Selenium and Python I am using Selenium 3.141.0 It suggests that Chromedriver is unable to locate the binary chrome.exe. It also suggests to ensure that I am not using the deprecated option: ChromeOptions() and don't believe I need to use the keyword argument executable_path as I am launching it from Heroku where I would use '/app/.apt/usr/bin/google-chrome' path. Other solutions I've come across suggests various different configurations and I feel like I have everything configured correctly but maybe not. What else could be the reason that I am unable to get this to work? Buildpacks https://github.com/heroku/heroku-buildpack-google-chrome https://github.com/heroku/heroku-buildpack-chromedriver Heroku Config Variables GOOGLE_CHROME_BINARY = "/app/.apt/usr/bin/google-chrome" CHROMEDRIVER_PATH = "/app/.chromedriver/bin/chromedriver" Options class WebDriver: def __init__(self): self.GOOGLE_CHROME_BINARY = config('GOOGLE_CHROME_BINARY') self.CHROMEDRIVER_PATH = config('CHROMEDRIVER_PATH') self.chrome_options = Options() self.chrome_options.add_argument("--disable-dev-shm-usage") self.chrome_options.add_argument('--no-sandbox') self.chrome_options.binary_location = self.GOOGLE_CHROME_BINARY self.chrome_options.add_argument("headless") self.driver = webdriver.Chrome(self.CHROMEDRIVER_PATH, options=self.chrome_options) Any help even in just helping me understand what's going on better would be much appreciated -
How can I fix the problem:"TypeError: filter() takes no keyword arguments",please help me
I have followed the official tutorial of Django to make a poll app, but I have gotten an error: File "C:\Users\oliver\Desktop\TPA Part 5\mysite\polls\views.py", line 17, in get_queryset return Question.objects,filter( TypeError: filter() takes no keyword arguments The code(The code is at mysite\polls\views.py and the required changing action is on part 5 of the tutorial): class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future) """ return Question.objects,filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] Could you please help me? The platform: Windows 10 ,Django version: 3.0.4 ,Python version: 3.8.2 ,The database is MySQL8.0 and the tutorial:Tutorial,my code files:Files -
How to get image data from Django form which returns False for is_valid()
How to save image in Django form that is not validated. I could able to save data of Charfield using title = form_name["title"].data Other data that are passed are getting saved but image is not getting saved. How to fix it. form = forms.FormName() if request.method == "POST": form_name = FormName(data = request.POST) title = form_name["title"].data thumbnail = form_name["thumbnail"].data content = form_name["content"].data tags = form_name["tags"].data instance = htmlpage(title=title, thumbnail=thumbnail, content= content, tags=tags, by=request.user) instance.save() -
Django: Iterate queryset over list
I cannot iterate over Querysets. Below produce an error meanwhile if I would manually type: return chain(queryset.filter(company__contains=1, queryset.filter(company__contains=2) it works. How do I solve this?, I cannot find anything online. Key here I that I do not know the size of the list beforehand and cannot use the manual notation, such as 1 | 2 from itertools import chain class ProductListView(ListView): model = Product template_name = 'product_list.html' def get_queryset(self): queryset = super(ProductListView, self).get_queryset() query = [] for g in [1,2]: query.append(queryset.filter(company__contains=g)) return chain(tuple(query)) -
Django is not rolling back with atomic transactions
I have the following models: class InventoryAction(CustomModel): action_content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, limit_choices_to={'model__in': ('inventoryinput', 'inventorytransfer', 'inventoryadjustment', 'physicalinventory', 'requisition', 'sale')}, related_name='inventory_actions', verbose_name=_("Tipo de Acción")) action_object_id = models.PositiveIntegerField(verbose_name=_("ID de la acción")) action_object = GenericForeignKey('action_content_type', 'action_object_id') timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y hora")) class Meta: verbose_name = _("Acción de Inventario") verbose_name_plural = _("Acciones de Inventario") def __str__(self): return "{}-{}/{}/{}".format(self.id, self.action_content_type.model, self.action_object_id, self.timestamp) class InventoryActionProduct(CustomModel): inventory_action = models.ForeignKey(InventoryAction, on_delete=models.PROTECT, related_name='products', verbose_name=_("Acción de Inventario")) product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='actions', verbose_name=_("Producto")) amount = models.FloatField(verbose_name=_("Cantidad")) class Meta: verbose_name = _("Producto de Acción de Inventario") verbose_name_plural = _("Productos de Acciones de Inventario") def __str__(self): return "[{}] {}/{}/{}".format(self.id, self.inventory_action.action_content_type.model, self.product.name, self.inventory_action.timestamp) class InventoryActionItem(CustomModel): inventory_action_product = models.ForeignKey(InventoryActionProduct, on_delete=models.PROTECT, related_name='items', verbose_name=_("Producto de Acción de Inventario")) product_item = models.ForeignKey(ProductItem, on_delete=models.PROTECT, related_name='invetory_action', verbose_name=_("Artículo")) class Meta: verbose_name = _("Artículo de Acción de Inventario") verbose_name_plural = _("Artícuos de Acciones de Inventario") def __str__(self): return "[{}] {}/{}".format(self.id, self.inventory_action_product.product.name, self.product_item.serial_number) class InventoryInput(CustomModel): repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='inputs', verbose_name=_("Almacén")) class Meta: verbose_name = _("Entrada de Inventario") verbose_name_plural = _("Entradas de Inventario") def __str__(self): return "{}-{}".format(self.id, self.repository) KARDEX_INPUT = 'INPUT' KARDEX_OUTPUT = 'OUTPUT' KARDEX_CHOICES = ( (KARDEX_INPUT, _("Entrada")), (KARDEX_OUTPUT, _("Salida")), ) class Kardex(CustomModel): type = models.CharField(max_length=6, choices=KARDEX_CHOICES, verbose_name=_("Tipo de Movimiento")) repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='kardex', verbose_name=_("Almacén")) product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='kardex', … -
Django Rest Framework filter - Select a valid choice
I encountered such an error when using django rest framework filter. I want to return 0, is it possible to fix this? # http://localhost:8000/api/v1/target/?project=TEST-00002 # RESPONSE 400 Bad Request { "project": [ "Select a valid choice. That choice is not one of the available choices." ] } Definitions and test cases are below. ## Definition class Project(models.Model): project_number = models.CharField(max_length=255, unique=True, null=False, blank=False) project_name = models.CharField(max_length=255, null=False, blank=False) class Target(models.Model): project = models.ForeignKey(Project, db_column='project_number', to_field='project_number', on_delete=models.CASCADE, null=False, default=None) target_name = models.CharField(max_length=255, null=False, default='') comment = models.TextField(default='', blank=True, null=False) class TargetViewSet(viewsets.ModelViewSet): queryset = Target.objects.all() serializer_class = TargetSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_fields = ['id', 'project'] class TargetSerializer(serializers.ModelSerializer): class Meta: model = Target fields = '__all__' read_only_fields = ('created_at', 'updated_at', 'delete_at') ## TEST DATA { "hits": { "total": 2, "next": null, "previous": null, "hits": [ { "id": 1, "project": "TEST-00001", "target_name": "bob" }, { "id": 2, "project": "TEST-00001", "target_name": "mary" } ] } } ## TEST ## http://localhost:8000/api/v1/target/?project=TEST-00002 ## 400 bad request { "project": [ "Select a valid choice. That choice is not one of the available choices." ] } ## http://localhost:8000/api/v1/target/?project=TEST-00001 ## no problem { "hits": { "total": 2, "next": null, "previous": null, "hits": [ { "id": 1, "project": "TEST-00001", "target_name": "bob" … -
Should I Use Relational Database OR Non-Relational Database For My Application
I am in the early stages of building a music/video streaming app similar to Tidal/Spotify but for a different niche of artists. I have a somewhat basic question: I am afraid I don't want to make the mistake of building a database that can't scale linearly later on. I have decided I am going to be using Google Cloud Platform. I want to use Google Spanner because it scales very well and is relational (which my data is going to be, I am assuming. Playlists, library, users, artists... can be schemed relationally unless I am not seeing something I should be seeing). Anyways, I see that Google Spanner is really expensive especially for new applications that don't need that scaling option that early on. So my question is should I go with Cloud SQL with Postgres and if whenever if ever this app grows to a significant number of users, then migrate to Google Spanner. Or should I go with a non-relational database like BigTable or Datastore/Firebase that will scale by itself later on and also isn't expensive at the beginning. What databases would you use if you were asked to build this app that is required to scale? I … -
Django models AttributeError: 'User' object has no attribute 'set_attributes_from_name'
I am trying to create a simple chat app with Django and am working on creating the models right now: class User(models.Model): uuid = models.CharField(max_length=10) name = models.CharField(max_length=20) tag = models.IntegerField() creation = models.DateTimeField() status = models.IntegerField(default=0) login = LoginInfo() class Room(models.Model): users = ArrayField(User()) With the above code, I get the following error: AttributeError: 'User' object has no attribute 'set_attributes_from_name' Am I using ArrayField wrong? Does the User class need an extra method called set_attributes_from_name? I'm using postgresql for the databse management. -
Learning Postress for my Django App on Heroku
my app is ready to go live but I tried to deploy on Heroku and their Postgress DB keeps old fields values. I migrated, tried to reset the Heroku DB but still I can see the reason from the error in my log but cannot get hold on it. I need an advice from your own experience. Should I learn Postgress and it will make my life easier or is there a better path ? I'm happy to go full postgres for few days but I want to be sure I dig in the right place. Tks so much for your POV. -
Django forms widget renderer
I am porting some code from Django 1.9 to 1.11. There is the following form: class FruitForm(FormFieldMixin, forms.Form): choices=( ("app", "Apple"), ("pea", "Pea, not Pear"), ), widget=forms.RadioSelect(renderer=CustomRadioFieldRenderer), ) this fails in 1.11 with: TypeError: __init__() got an unexpected keyword argument 'renderer' looking at the source code, RadioSelect in 1.9 inherits from RendererMixin which indeed accepts a renderer argument. RadioSelect in 1.11 inherits only from ChoiceWidget which in turn inherits from Widget. Widget's render accepts a renderer. This is in agreement with the Django release notes for 1.11. So the new way would be to pass a renderer when the Widget render is being called. There are some oblique guidelines here but I cannot imagine how one would use the Widget.render directly. I do not want to set a universal form renderer, just for this one class. In summary, how do I do that class, with a custom widget renderer in 1.11 where we do not have a renderer argument. Thank you.