Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can Control User View class based on Role - Django
I am using class based view and trying to load content based on user Role. I want load form fields enabled or disabled based on user role.... (But still want to show the form for both type of users) MyView: class MyListView(LoginRequiredMixin, UserPassesTestMixin, ListView): def test_func(self): return self.request.user.user_type == 'Business' def get_context_data(self, **kwargs): context['form'] = MyForm(disable_fields=True) # this disable_fields will become true or false based on user role... return context MyForm: class MyForm(forms.Form): comment = forms.CharField(widget=forms.Textarea(attrs={'style': 'height: 4em;'})) ready = forms.BooleanField(label="are you ready?", required=False, initial=False) def __init__(self, disable_fields=False, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) if disable_fields: for visible in self.visible_fields(): visible.field.widget.attrs['readonly'] = True So I want to check user role before or with in the get_context_data function called... Please advise -
DJANGO NEW USER REGISTRATION
is there a way to create a new user from a html file with customs fields without using forms.py and if no how can i add custom columns in auth_user table in postgresql -
Django post-save when the superuser is the sender
I created 3 groups named 'admin', 'teacher' and 'student' and I want every user I register to be in only one of these groups not two. If i create the super-user by entering in the command line 'createsuperuser' it works well,it is added to the 'admin' group, but the problem is that if I create the teacher it is added to the 'teacher' group and also to the 'admin' group and same problem with student. these is the post-save for my 3 profils signals.py @receiver(post_save, sender=User) def admin_profil(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='admin') instance.groups.add(group) @receiver(post_save, sender=Teacher) def teacher_profil(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='teacher') instance.user.groups.add(group) @receiver(post_save, sender=Student) def student_profil(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='student') instance.user.groups.add(group) -
Iterate List in Dict with Python in the template
I want to iterate with django in the template a list in a dictionary. For example py = {name[a,b,c],age[10,12,13],username[aa,bb,cc]} -
Object of type TemporaryUploadedFile is not JSON serializable
I am trying to run my file upload view in Django as a task using celery, every works fine except when the image file is more than 2.5MB which celery complains that it cant serialize. the reason i am using celery is that I want to get the progress info from each file upload task and create a progress bar from it. below is my code. /views.py def simple_upload(request): if request.method == 'POST' and request.FILES['image']: file = request.FILES['image'] #process_download(file) task = process_download.delay(file) #print(task.task_id) return redirect('index') return render(request, 'upload.html') @shared_task(bind=True) def process_download(self, image_file): process_recoder = ProgressRecorder(self) print('Upload: Task Started') # time.sleep(50) fs = FileSystemStorage() buffer = io.BytesIO() chunk_size = 0 for chunk in image_file.chunks(): chunk_size += sys.getsizeof(chunk) buffer.write(chunk) process_recoder.set_progress(chunk_size, image_file.size) buffer.seek(0) image = ImageFile(buffer, name=image_file.name) fs.save(image_file.name, image) return 'Done' is there any way i could make celery serialize the images that are larger than 2.5, using the Django settings FILE_UPLOAD_MAX_MEMORY_SIZE = 50*1024*1024 does not work too? -
Missing migration files
I am stuck at this error for missing migration files.. Do I need to drop the whole database to reset the migrations or is it possible to do some type of migrate rollback for that app gigs? Does anyone know how to solve it? Would highly appreciate the help! -
How do I get Django's 'context' variables accessible to more than one view?
Is it possible to have the variables of a context block accessible to more than one view? Can one create "constants" in Django 'views.py'? I have two pages: 'index.html' and 'post_list.html'. They both use the model 'Post', but the two pages aren't identical. So the DRY principle went out the window. A quick search dug out some older questions about writing the variables into 'settings.py' or writing a block of code like def settings... How is it done with Django 3.x? -
Can I override the related_name of a ForeignKey in a proxy model?
I have a Django model ActivityLog to track general user related activities in the system. I created a proxy model StudentActivityLog where I gathered the student specific business logic related to user activity. This proxy model has a custom model manager too. class ActivityLog(models.Model): person = models.ForeignKey( "Person", on_delete=models.PROTECT, related_name="activity_logs" ) # ... class StudentActivityLogManager(models.Manager): def custom_something(): # ... class StudentActivityLog(models.Model): objects = StudentActivityLogManager() class Meta: proxy = True # ... When I have a Person instance, I would like to be able to write person.student_activity_logs.custom_something() to access the method of the student model manager. However, this attribute is not available, I can only access person.activity_logs but that obviously doesn't have custom_something(). I know that StudentActivity.objects.filter(person=student).custom_something() will work, but I was wondering if I can avoid this tedious format. -
Django not displaying content of an existing model, instead displays a pair of double quotes(" ") in its place
Like the title says when i try to display some aspect of a model is displays quotes instead HTML {% block content %} <div> {% for listings in listing %} <p>"{{ listing.title }}"</p> {% endfor %} </div> {% endblock %} what shows up views.py def getListingAll(request): listing = Listing.objects.all return render(request, 'all.html', {"listing":listing} ) models.py class Listing(models.Model): title = models.CharField(max_length=150) available_till = models.DateField('Available till') description = models.TextField(max_length=2000) pub_date = models.DateTimeField('Date published', auto_now = True) price_per_day = models.IntegerField(default=0) def __str__(self): return self.title -
Best Practice for Junction Table Form
As stated in the title, I want to use a junction table from my model as the form. Below i've included the models (only the necessary fields). Currently, I have an html template that shows information regarding the dataset. I have a function that goes to the source system and gets all of the columns. The same operation grabs them from the destination system. The aim is to ultimately be able to match columns from the source system to the destination system. To do this, I pull of the columns into the dataset_columns table and mark it as either 'source' or 'destination'. I would like to use a form with the dataset_column_junction table that would allow me to match a 'destination' column to a 'source' column. (I should mention that we don't expect to pull in all source columns). class csc_data_sets(models.Model): dataset_id=models.CharField(primary_key=True, max_length=36, default=uuid.uuid4) class dataset_columns(models.Model): column_id=models.CharField(primary_key=True, max_length=36, default=uuid.uuid4) dataset_id=models.ForeignKey(csc_data_sets, models.DO_NOTHING, db_column='dataset_id',blank=True, null=True) class dataset_column_junction(models.Model): destination_column_id = models.OneToOneField(dataset_columns, primary_key = True, on_delete=models.CASCADE,db_column='destination_column_id') source_column_id = models.ForeignKey(dataset_columns, models.DO_NOTHING, related_name='source_column_id', db_column = 'source_column_id') I have a few attempts but all of them feel sloppy or don't function well. I was hoping to see if someone's tackled this before and if there is a … -
How to get a filesystem path using Django and JavaScript
I have a server built with Django listening on 127.0.0.1, everything is local and on the same machine (same file system). My client needs to communicate a folder’s path to the server so that the server can launch a script to manipulate what is in that folder. How would I go on about making a GUI in the browser to get that path? I have seen a similar question asked here and the answer suggests that the server exposes the file system in some way so that the client can choose a folder. I understand that this is pretty much the only way to go on about this, but I fail to find a simple implementation of this idea. What I have in mind requires many interactions between the client and the server to update the path as the user progresses in the fs hierarchy. -
Python+Django : I cannot see my rendered data in checkout but I am able to see it in other pages
I have this code: {% for items in items%} <div class="cart-row"> <div style="flex:2"><img class="row-image" src="{{item.product.imageURL}}"></div> <div style="flex:2"><p>{{item.product.name}}</p></div> <div style="flex:1"><p>${{item.product.price}}</p></div> <div style="flex:1"><p>x {{item.quantity}}</p></div> </div> {% endfor %} checkout.html I do not seem to be able to render out the information in checkout.html, but I did so in cart.html using the same code. Views.py: from django.shortcuts import render from .models import * def store(request): products = Product.objects.all() context = {'products':products} return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer = customer, complete = False) items = order.orderitem_set.all() else: items = [] order = {'get_Cart_total' : 0, 'get_cart_items' : 0} context = {'items' : items, 'order' : order} return render(request, 'store/cart.html', context) def checkout(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer = customer, complete = False) items = order.orderitem_set.all() else: items = [] order = {'get_Cart_total' : 0, 'get_cart_items' : 0} context = {'items' : items, 'order' : order} return render(request, 'store/checkout.html', context) models.py from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, null = True, blank = True, on_delete = models.CASCADE) name = models.CharField(max_length = 200, null = True) email = models.CharField(max_length = 200, null=True) def __str__(self): return self.name class … -
Saving data after non-Django Form submission
I have a payment form that is made up of various elements. Here my problem is that the card for a new stripe user isn't registered until after form submission. I know that if my form has a newly added Address, I can use form.is_valid() but that doesn't apply if my address is one that is saved already. But is there a way I can set the card using stripe.PaymentMethod.list after the form is submitted, regardless of if the Django form is part of it? form <form method="POST" id="subscription-form" data-secret="{{client_secret}}"> {% csrf_token %} <label class="block uppercase text-gray-600 text-xs font-bold mb-2">Payment Details</label> {% if payment_methods %} <div class="form-check my-3 bg-gray-200 p-2 rounded-md"> <input class="form-check-input" type="radio" name="payment-methods" id="add-new-card" value="add-new-card" onclick="addCard()" {%if payment_methods %} {%else%}checked="checked" {%endif%} required> <label class="form-check-label" for="add-new-card"> Add new payment method </label> <div id="new-card" style="display: none;"> <label class="block uppercase text-gray-600 text-xs mb-2" for="cardholder-name"> Name on Card </label> <input id="cardholder-name" class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150" value="{{customer.name}}" detype="text"> <!-- placeholder for Elements --> <label class="block uppercase text-gray-600 text-xs mb-2" for="card-element"> Card Details </label> <div id="card-element" class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"> … -
How do I merge data of two objects in Django REST Framework
So let's say I have this 2 models Poll: class Poll(models.Model): title = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_available = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title Options: class Option(models.Model): title = models.CharField(max_length=255) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) def __str__(self): return f'{self.poll.title} - {self.title}' These two objects are connected with ForeignKey. Now let's say I have a frontend that renders both options and the question (title of the poll) but I only want make a single API call to the backend. Basically I need the API to looked like this: { "title": "Which is the best frontend framework?", "options":[ { "id": 1, "title": "React" }, { "id": 2, "title": "Vue" }, { "id": 3, "title": "Angular" } ] } How what method/technique should I use to merge two objects like this? -
Registered User can't login with credentials django rest framework
The issue i've got is my login endpoint wont permit me to login with authenticated users for unkown reasons Here is my serializers.py file class UserSerializer(ModelSerializer): class Meta: model = User fields = ['id','first_name','last_name','email','is_seller','date_joined'] extra_kwargs ={ 'password':{'write_only':True} } def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance Here is my views.py for Login class LoginAPIView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] print(email) print(password) # since email is unique use first() user = User.objects.filter(email=email).first() print(user) if user is None: raise exceptions.AuthenticationFailed(f'User {email} not found') if not user.check_password(password): raise exceptions.AuthenticationFailed(f'Incorrect Password') return Response(UserSerializer(user).data) Now when i do try to login the and given user i get this error below from post man { "detail": "Incorrect Password" } And these are my logs below Forbidden: /api/sellers/login/ [15/Jul/2021 21:50:30] "POST /api/sellers/login/ HTTP/1.1" 403 31 I've been unable for hours to figure out why exactly register users can't sign in and also i am using a Custom user model and in my settings.py file the Rest_Framework is set to AllowAny...Thanks in advance for any help... -
Faster Django filter querying for very large database
I am creating a geospatial web app and have a very large database, at the moment it is 7.5 million entries long and will be almost 60 million entries long by the time all the data is uploaded. I want to display all the points from a certain date and am simply using Model.objects.filter(datetime__date=requested_date) at the moment. Each date request takes ~8s to load. How can I filter in a more efficient way? If there are better ways to store geospatial data points, I would greatly appreciate any advice! -
django-admin-tools-stats : Reverse for 'admin-charts' not found. 'admin-charts' is not a valid view function or pattern name
just installed django-admin-tools-stats. gives me the following error: Reverse for 'admin-charts' not found. 'admin-charts' is not a valid view function or pattern name. what do I do? -
NOT NULL constraint failed: core_question.poll_id error
I'm stack on problem with POST method in Django. Core Idea of the project to make Polls, in polls add questions, and for each question to add Answers. I did make all of that. And i have few APIs working: GET: http://127.0.0.1:8000/poll/ Showing all created polls in database GET: http://127.0.0.1:8000/poll/{poll_name}/ // poll_name -> Weather (for example) Showing all questions, all answers and correct answer POST: http://127.0.0.1:8000/api/token/ Providing authorization Token if admin credentials are correct. (username: Admin, password: admin) But now I need APIs for add, remove, update Polls, Questions and Answers. I did try it for Questions first: class Questions(APIView): def get(self, request, format=None, **kwargs): question = Question.objects.filter(poll__title=kwargs['topic']) serializer = QuestionSerializer(question, many=True) return Response(serializer.data) def post(self, request, format=None, **kwargs): serializer = QuestionSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) But i'm getting error: NOT NULL constraint failed: core_question.poll_id error I did try to search it in Internet and its says that i'm not requesting proper parameter's. I did try 100 variations and still cant find what is the problem. This is Github link for project: https://github.com/NeoVic2006/Polls_with_questions_answers Please check it and let me know where is the problem. PLEASE be specific since i'm not really experienced in Django. Thank … -
Problems with marking djangoo option select labels
I'm a student who is learning how to do a funeral. We are having a hard time in the process of indicating the option value of the product. What I want is for one option label to pop up and the option_value to come underneath it in order, but it's showing up like this. There are currently two options: green, blue, and red under the color, and S, M, and L under the size. How can we solve this? option.html <form method="get" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row"> <label for="value_code" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-5" style="margin-left: -56px"> <select type="text" class="form-control" name="value_code" id="value_code" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <optgroup label="{{option.name}}"> <option value="{{value.value_code}}">{{value.name}} (+원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> </div> models.py # 옵션(옵션코드, 옵션명, 상품코드(fk)) class Option(models.Model): option_code = models.AutoField(primary_key=True) name = models.CharField(max_length=32) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') def __str__(self): return self.name # 옵션값(옵션값코드, 옵션값명, 옵션코드(fk), 상품코드(fk)) class Value(models.Model): value_code … -
I am using DRF, My view returns an empty response but my blog is adding successfully i want my serializer data
I am using DRF, My view returns an empty response but my blog is adding successfully i want my serializer.data. My models.py file: from django.db import models from django.utils import timezone from datetime import datetime from .validators import validate_allfile_extension from restfapp.models import User class Blog(models.Model): title = models.TextField(max_length = 50) author = models.TextField(max_length = 50) description = models.TextField() date = models.DateField(auto_now=True) time = models.DateTimeField(default=datetime.now) image = models.ImageField(null=True, verbose_name="", validators=[validate_allfile_extension]) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title My serializers.py file class AddBlogSerializer(serializers.ModelSerializer): title = serializers.CharField(max_length=128, write_only=True, required=True, error_messages={'blank': "Please provide title"} ) author = serializers.CharField(max_length=128, write_only=True, required=True, error_messages={'blank': "Please provide author"}) description = serializers.CharField(max_length=128, write_only=True, required=True, error_messages={'blank': "Please provide description"}) image = serializers.FileField(write_only=True, required=True, error_messages={'invalid': "Please upload image, video or audio file"}) class Meta: model = Blog fields = ["title","author","description","image",] My views.py file @api_view(['GET', 'POST']) # @parser_classes([MultiPartParser, FormParser]) # @csrf_exempt @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def add_blog(request): if request.method == 'POST': serializer = AddBlogSerializer(data=request.data) if serializer.is_valid(): serializer.save(user_id=request.user.id) data = {'result': 'success', 'message': serializer.data} return Response(data=data, status=201) elif not serializer.is_valid(): data = { 'result': 'error', 'message':serializer.errors} return Response(data=data) My json response: { "result": "success", "message": {} } I want to get serializer.data I know if i assign like this blog=serializer.save(user_id=request.user.id) then print(blog.id) it … -
Why not use "runserver" for production at Django?
Everywhere i see that uWSGI and Gunicorn are recommended for production mode from everyone. However, there is a lot more suffering to operate with it, the python manage.py runserver is more faster, simpler, and the logging is also more visible if something goes wrong. Still, why not recommend the "python manage.py runserver" command for live production? -
Django Filter by date and status
my first question here, I've been looking around but couldn't find a solution. I am building a reservation system, my models are class Room(models.Model): number = models.IntegerField() beds = models.IntegerField() capacity = models.IntegerField() category = models.ForeignKey( RoomCategory, on_delete=models.CASCADE, blank=True, null=True) class Booking(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, blank=True, null=True) check_in = models.DateField() check_out = models.DateField() status = models.IntegerField(blank=True, null=True) if request.method == 'POST': no_disponible = "No hay habitaciones disponibles, selecciona otras fechas" if form.is_valid(): room_list = Room.objects.filter(category=1).exclude(booking__check_in__lt=form.cleaned_data['check_out'], booking__check_out__gt=form.cleaned_data['check_in'], booking__status__gt=0) I am changing status when the customer confirms so I want to check if dates are available when status is not 1 (I change status to 1 once the payment is approved. However booking__status__gt=0 doesn't seem to work here, any help is welcome! -
how do i sum the userinput
give me the erro in that pic all i want is when people input the Macros i wantit sum all of that make a total count def index(request): macros = Macros.objects.all() goals = Goals.objects.filter(user=request.user) count = Macros.objects.values('calories', 'protein','carbohydrates','fats') sum = 0 for c in count: sum += count[c] print(sum) return render(request, 'macro/index.html', {'macros': macros,'goals':goals,}) class Macros(models.Model): name= models.CharField(max_length=100) calories= models.FloatField(max_length=10) protein=models.FloatField(max_length= 4) carbohydrates= models.FloatField(max_length= 4) fats= models.FloatField(max_length=4) goals = models.ForeignKey(Goals, on_delete=models.CASCADE) [enter image description here][1] -
On Popup on Folium marker, how to define a push button to show some data about that point
So, I have hundreds of marker points on a Folium map. By clicking, I open the popup. On the popup, there is a push button that marked more info!. By clicking the more info, I would like to see the data related to that specific point in that URL down the map box. I am using Django, Folium and MongoDB. Can you help me or give any keyword in this regard? Thank you -
How to build a path in my templates file for Django
right now in my Django settings file for my project i am trying to build a path to so I can display my templates/projects/index.html file. Can I get help solving this? # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent and in my TEMPLATES dictionary I have this is DIRS `TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'projects/templates'), ],`