Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django download not starting even though HTTP response is 200
I am trying to create a zip file full of .wav files and download it from a React front end, which is making an AJAX request to the Django endpoint. Here is what I have so far: def saveZipFile(request): if request.method == 'POST': in_memory = BytesIO() zipFile = ZipFile(in_memory, "a") keys = generate_piano_keys(3) # activeNotes = {} for index, key in enumerate(keys): nameOfFile = request.POST.get(key) if(nameOfFile != None): zipFile.write('./{}'.format(nameOfFile), arcname="{}.wav".format(key)) for file in zipFile.filelist: file.create_system = 0 zipFile.close() downloadFile = in_memory.getvalue() in_memory.seek(0) response = HttpResponse(in_memory.getvalue(), content_type='application/zip') response["Content-Disposition"] = 'attachment; filename="sample_map.zip"' return response I am getting the following response from the Django server: "POST /test/saveZipFile HTTP/1.1" 200 61894 I have tried debugging the response.content and it is the same bytes as the bytes I am writing to the zipFile variable, which means that it is getting written to the response. I have tried using application/force-download instead of application/zip in the content_type. Is there something I am missing, since every thread and article says that it should look like that. -
How to force save Django model ignoring blank field in inline formsets
I am trying to prevent my app from saving formset values if a particular field is not filled. I am pre-filling a model field intended as formset row serial number. Now I want that a key field (for price) must be filled for a row or rows to be saved. As a corollary, if a value is not "filled in" in the field (price) by the user, that particular row must be ignored during save (i.e. save will still happen, without the rows not filled with "price" value). My dependent (child) model is something like this: class PriceItems(models.Model): item_parent = models.ForeignKey(HdrData, on_delete=models.CASCADE,....) item_ser_num = models.PositiveSmallIntegerField(null=True, blank=True, verbose_name='Serial No.') from_date = models.DateField(null=True, verbose_name='From date') to_date = models.DateField(null=True, verbose_name='To date') price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, default=0.00,...) Since the serial number field (item_ser_num) is a model field and Django considers all rows with the filled fields (here, the item_ser_num field) as having been filled with data (by the user) and that the rest of the fields must be filled before saving is possible (possibly, correctly so). In case a particular field is a not required field, rows get save without the data (in this case, the price field), which for my case … -
2 ids in django rest url
I'm using @action method to create a custom function in django rest. However I need 2 arguments on it. I'm having trouble creating the api url. view.py class ProfessorClassViewSet(viewsets.ModelViewSet): serializer_class = ClassSerializer authentication_class = (TokenAuthentication, ) permissions_class = (IsAuthenticated, ) @action(detail=True, methods=['GET']) def grade(self, request, pk=None, *args, **kwargs): if request.user.is_professor: user = request.user student_id = int(kwargs['student_id']) discussion = Grade.objects.select_related('class_list').filter(activity_type__contains='discussion', class_list__student_id=student_id) discussion_serializer = GradeSerializer2(discussion, many=True) response = { 'message': 'Success!', 'discussions': discussion_serializer.data } return Response(response, status=status.HTTP_200_OK) urls.py router.register('classes', ProfessorClassViewSet, 'prof_class') router.register('classes/<int:pk>/grade/<int:student_id>', ProfessorClassViewSet, 'prof_grade_class') -
How to compose two fields to create custom field in Django?
I want to create a custom field MyCharField, it composes models.CharField with a models.BooleanField, which might render as: □ _____________ If it is checked, its pre_save will do_something; if it is not, its pre_save will just return. The code may look like: class MyCharField(models.CharField): def pre_save(self, model_instance, add): value = getattr(model_instance, self.attname) checked, content = ... if checked: content = do_something(content) return content But I couldn't find document about this, how can I make it? -
MultiValueDictKeyError - Dganjo
I am having a problem by getting MultiValueDictKeyError in Django. I am trying to logout user from my website so I made the following codes. In html </li> <li class="nav-item mr-3"> <a href="javascript:{document.getElementById('logout').submit()}" class="nav-link"> <i class="fas.fa-sign-out-alt"></i>Logout </a> <form action="{% url 'logout'%}" method="POST" id="logout"> {% csrf_token %} <input type="hidden"> </form> </li> Here's my login and logout function in say 'accounts/views.py' def login(request): # request method if request.method == 'POST': #Saving the username and password in a variable username = request.POST['username'] password = request.POST['password'] #checking if the user name and password matches using auth function user = auth.authenticate(username=username, password=password) # checking if the user is found in Database with user name and password, if found then login if user is not None: auth.login(request, user) messages.success(request, "Welcome to BTRE.") return redirect('dashboard') # if user name and password do not match with DB. display message and redirect to login page. else: messages.error(request, "Incorect Username and/or Password. Please type correct user name and password") return redirect('login') else: return render (request, 'accounts/login.html') def logout(request): if request.method == 'POST': auth.logout(request) messages.success(request,"You are now logged out") return redirect('index') -
Dynamic USERNAME_FIELD djangorestframework and simplejwt
I am working on a authentication application where user's can login via (email or mobile) and (password or otp) Framework/ Library Used Django Rest Framework and djangorestframework-simplejwt I am trying to add multiple claims in the jwt token getting generated. Below is my LoginView and LoginSerializer. View class Login(TokenObtainPairView): serializer_class = LoginSerializer Serializer class LoginSerializer(TokenObtainPairSerializer): mobile = serializers.CharField(allow_blank=True) email = serializers.EmailField(allow_blank=True) password = serializers.CharField(allow_blank=True) otp = serializers.CharField(allow_blank=True) @classmethod def get_token(cls, user): token = super().get_token(user) token['name'] = user.first_name return token def validate(self, attrs): mobile = attrs.get("mobile", None) email = attrs.get("email", None) password = attrs.get("password", None) otp = attrs.get("otp", None) user = authenticate(mobile=mobile, email=email, password=password, otp=otp) if user is None and self.password: raise serializers.ValidationError( detail="Incorrect Username or Password.", code=HTTP_401_UNAUTHORIZED ) if user.is_active: refresh = self.get_token(user) data = dict() data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) return data if user.is_locked: raise serializers.ValidationError( detail="Account Locked. Contact Support.", code=HTTP_423_LOCKED ) raise serializers.ValidationError( detail="User Account is Deactivated.", code=HTTP_401_UNAUTHORIZED ) But i am getting email can't be blank error when sending a valid phone number and password in request. This is because of TokenObtainPairSerializer which chack for User.USERNAME_FIELD (which in my case is email.) How can i handle this situation or get it working ? -
Django Defect-dojo: aws-prowler upload failed
I've implemented django-DefectDojo and trying to upload This sample-scan file but it throws me the following error in the logs. Everything is perfectly installed and other files are being uploaded(whichever I require) but this file. Error Thrown Server Error (500) Logs 2/engagement/1/import_scan_results" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36" "-" uwsgi_1 | Internal Server Error: /engagement/1/import_scan_results uwsgi_1 | Traceback (most recent call last): uwsgi_1 | File "/usr/local/lib/python3.5/site- packages/pandas/core/indexes/base.py", line 2897, in get_loc uwsgi_1 | return self._engine.get_loc(key) uwsgi_1 | File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc uwsgi_1 | File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc uwsgi_1 | File "pandas/_libs/hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item uwsgi_1 | File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item uwsgi_1 | KeyError: 'PROFILE' uwsgi_1 | uwsgi_1 | During handling of the above exception, another exception occurred: uwsgi_1 | uwsgi_1 | Traceback (most recent call last): uwsgi_1 | File "/usr/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner uwsgi_1 | response = get_response(request) uwsgi_1 | File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response uwsgi_1 | response = self.process_exception_by_middleware(e, request) uwsgi_1 | File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response uwsgi_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) uwsgi_1 | File "/usr/local/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view uwsgi_1 | return view_func(request, *args, **kwargs) uwsgi_1 | File "./dojo/engagement/views.py", line 523, in … -
Django-import-export post_save called twice
I created a custom user subclassed from AbstractUser and a post_save signal and a receivedr that prints the new user's id. @receiver(post_save, sender=CustomUser, dispatch_uid='members.models.customuser.post_save') def post_save_custom_user(sender, instance=None, created=False, **kwargs): if not created: return print('post_save_custom_user: {}'.format(instance.id)) When I create a new user via the admin interface the receiver is called once. When I import a user using django-import-export the receiver is called twice: once after the initial Submit of the import file and then again after the Confirm Import. And the weirdest thing is that the id remains the same, like it creates the user, rolls back the transaction and creates it again? post_save_custom_user: 15 post_save_custom_user: 15 I am using Python 3.6, Django 3.0.3, django-import-export 2.0.1 Anyone seen this before? -
MongoEngine or PyMongo to use for Python-Django
In a brand new project i need to use either PyMongo or MongoEngine with Django following which creating apis. I am having a hard time deciding which one to go for. I need an expert opinion for the matter. In stack overflow i found a few posts of such kind but they are 8 years or 5 years old... so not that helpful. -
Django: showing different title on login template
I'm using a single View, Template, URL to show the LoginForm to our different users. We were using the default LoginView that Django 3.0 offers. But now we've introduced an extra step: a screen with 2 buttons so users choose if they are "clientes" or "vendedores" (sellers). Both buttons take you to the same login page. We' would like to show a different message/title, even provided that it is the same Login template. I've been reading about extra_context, so I've tried to make a custom LoginView but don't understand how to show a different title on the same Login Template, according to with button is clicked. This is the template with the 2 buttons that lead to the same LoginForm: {% block content %} <h2>Ingresar con tu cuenta</h2> <p class="lead">Selecciona qué tipo de usuario eres</p> <a href="{% url 'core:login' %}" class="btn btn-primary btn-lg" role="button">Soy un cliente</a> <a href="{% url 'core:login' %}" class="btn btn-secondary btn-lg" role="button">Soy un vendedor</a> {% endblock %} My Custom LoginView: from django.contrib.auth.views import SuccessURLAllowedHostsMixin from django.views.generic.edit import FormView from django.contrib.auth.forms import AuthenticationForm class LoginView(SuccessURLAllowedHostsMixin, FormView): """ Display the login form and handle the login action. """ form_class = AuthenticationForm authentication_form = None #redirect_field_name = REDIRECT_FIELD_NAME template_name = … -
django-allauth : how to dynamic text on login page
I made custom login template and it's work. Now, I need to add some dynamic text to it based on the source IP address of request. Kindly please give me some clue (or code?) on how to do it. Sincerely -bino- -
Django Username error when I try run a project
When ever I clone a project and try to run the project I receive this error auth.User: (auth.E003) 'User.username' must be unique because it is named as the 'USERNAME_FIELD'. How can I solve this? -
design a django model so that we can have have a category field and the category can have unknown no of attributes
I want to create a web app for a medical lab and i want to store the patient's information with the type of test they have done. The problem here is that a patient can do multiple tests and the tests can have unknown number of fields to it. I want the test category as well as the test to be manually added. I'm stuck in designing the Django model. What is the best approach to this problem? Sorry if this is a noob question. -
Django password reset email showing invalid -- but works after refreshing the page?
This is an incredibly odd -- and I'm not sure if even Django related -- question. I am using the Django default password reset by email functionality. User types in email and gets a emailed a link where they can reset their passwords. For some reason, when I click the link in the email, it say "This link has expired / already been used." However, if I then refresh the page, the password reset works, and lets me set a new password. Additionally, if instead of clicking directly on the link in my email, I open the password reset link in a new tab, it works. Why does the method of opening the password reset link matter? Did I set some security setting where it doesn't like me coming from an outside source? In summary: password link doesn't work when being clicked on from email, but does work when opened in new tab. I am using Django-AllAuth. -
django oscar get cheepest offer
im new to django oscar framework.. my problem is when i'm adding offers to basket, it will add first created offer to given product, not the cheapest offer. offer condition type is Count and benefit type is Absolute example { "id": 74, "type": "Absolute", "value": "70.00", "max_affected_items": 1, "proxy_class": "", "range": 54 }, { "id": 75, "type": "Absolute", "value": "100.00", "max_affected_items": 1, "proxy_class": "", "range": 55 } if product has this two offers. i need to add cheapest offer, but when i used oscar builtin apply offer method it will add first object, not the cheapest one -
Django: ModuleNotFoundError: No module named 'vote'
I'm trying to add apps to my django project and wanted to add in django-vote. I did so by first using pip to install django-vote (showing that it is installed and where): Requirement already satisfied: django-vote in /usr/local/lib/python3.7/site-packages (2.1.7) Following the instructions from the github site (https://github.com/shanbay/django-vote), I added "vote" to installed apps: INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'vote', ] I added the necessary lines to my models.py file, but am still getting the following error when I try to use python3 manage.py makemigrations: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Python/3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Python/3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/Library/Python/3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Python/3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Python/3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'vote' The only other post I've found to have a similar error to mine is ModuleNotFoundError: … -
Django; Bugsnag simply does not work as advertised
I have a simple Django app using Django Rest Framework to serve API calls. Testing BugSnag to catch all server-side exceptions and It's difficult beyond belief. It simply does not work. Based on BugSnag's own documentation (https://docs.bugsnag.com/platforms/python/django/) This is all you need: in settings.py BUGSNAG = { 'api_key': 'YOUR_API_KEY_HERE', 'project_root': '/path/to/your/app', } Add at the top of the MIDDLEWARE definition: MIDDLEWARE = ( 'bugsnag.django.middleware.BugsnagMiddleware', ... ) I have done exactly that: in my own settings.py I have: BUGSNAG = { 'api_key': '[redacted]', 'app_version': "1.0", 'project_root': "/path/to/my/project/folder/where/manage.py/is", 'release_stage': "development", 'notify_release_stages': ['development', 'staging', 'production'] } Then I run my server and send it an API call that throws an exception on purpose. NADA. Nothing happens. No bug report is sent to BugSnag. At the bottom of my config file I tried this: bugsnag.configure(api_key="[redacted]") bugsnag.configure(release_stage="development") bugsnag.configure(project_root="/path/to/my/project/folder/where/manage.py/is") bugsnag.configure(app_version="1.1") bugsnag.notify(Exception("Something broke!")) Calling bugsnag.notify directly works! and a bug report IS being sent to BugSnag. Can anyone venture a guess as to why BugSnag completely ignores all Django Rest Framework Exceptions? -
Django ModelForm initial value converted to list
I have a Django ModelForm with initial value from HTTP request class Question(models.Model): text = models.CharField(max_length=50) class QuestionForm(forms.ModelForm): class Meta(object): model = Question fields = ('text',) def index(request): form = QuestionForm(initial=request.GET if request.GET.get('text') else QueryDict('text=FooBar')) return HttpResponse(form) This code shows values with square bracket <input type="text" name="text" value="[u'qweqweqweqwe']" required id="id_text" maxlength="50" /> How to correct pass initial value to ModelForm? -
I am having trouble solving this error: EmailAddress matching query does not exist
I am using a custom user, and attempted to login at my API endpoint. I created a custom serializer excluding the username field, as email is the unique identifier for my model. I have this serializer set to the auth-registration serializer in my settings.py file. I also verified that this email does exist through the admin file. Is there some kinda of disconnect between the serializer and the model? My Urls.py: """goal_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include #from django.views.generic.base import TemplateView #the generic template view for use as the homepage########was for the home page #the imports below are for the REST implementation from django_registration.backends.one_step.views import RegistrationView #the custom user forms from accounts.forms import CustomUserCreationForm from accounts.forms import CustomUserChangeForm urlpatterns = … -
Adding a user as an object to a many to many field
I am creating a functionality where a project/showcase has an administrators ManyToManyField, which would contain a list of users that can control a project. I am having issues adding users to this field. by default, I was able to set the person that creates a project as an administrator. but adding other administrators has been a challenge. models.py class Showcase(models.Model): title = models.CharField(max_length=50) description = models.TextField(null=True) skill_type = models.ForeignKey(Skill, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="Showcases") content = models.TextField(null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="upvotes") slug = models.SlugField(max_length=255, unique=True) administrator = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="administrators", blank=True) serializers.py class ShowcaseAdminSerializer(serializers.ModelSerializer): class Meta: model = Showcase fields = ['administrator',] views.py class showcaseAddAdminApiview(APIView): ''' Add a user as an admin to a showcase ''' serializer_class = ShowcaseAdminSerializer permission_classes = [IsAdmin] def post(self, request, slug): showcase = get_object_or_404(Showcase, slug=slug) if request.user in showcase.administrator.all(): showcase.administrator.add(user) showcase.save() serializer = self.serializer_class(showcase) return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py path("<slug:slug>/addadmin/", qv.showcaseAddAdminApiview.as_view(), name="add-administrator-to-showcase"), -
Django template perms returns "True" in all case
I want to check perms in templates. I got a Custom User Model and I using groups to give perms. When a new user is created, it don't get any special perms, just like default. Now, in templates, when I check {{ perms.app_label }} for a normal user, it returns set(), and if that user are in my group, {{ perms.app_label }} returns a list of perms, so that work good. But, when I check any perm just like {{ perms.app_label.perm_name }} it always returns true, even if that "perm_name" dont exist! Must be returning False, but it is falling. Why is this happening? -
Hosting image with it's own URL with Django
I'm trying to emulate the exact functionality of this URL: https://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png, but with a different image. I have the image in my static folder but I can't access that static folder using any external URL I have tried. It should be simple but I can't find many resources on it. I've googled everything I can think of but I've only found: Get the file path for a static file in django code and How to get the correct URL for an image in Django, and neither have worked. I'm fairly new to this. Thanks. -
How to serialize a nested serialize, update and save in django-rest-framework
How serialize a nested serialize, I have two models User and UserProfile, when I create or update a user the UserProfile is created or updated, I used signal post_save for it, but when I serialize the UserProfile with ModelSerializer User is not updated neither serialized, my code: class UserSerializer(serializers.ModelSerializer): followers_count = serializers.SerializerMethodField() following_count = serializers.SerializerMethodField() friends_count = serializers.SerializerMethodField() def get_following_count(self, obj): return obj.relationships.objects.following(obj).count() def get_followers_count(self, obj): return obj.relationships.objects.followers(obj).count() def get_friends_count(self, obj): return obj.relationships.objects.friends(obj).count() class Meta: model = User fields = '__all__' read_only_fields = ('created_at', 'updated_at',) class UserProfileSerializer(serializers.ModelSerializer): # profile_image = ImageSerializer() user = UserSerializer() class Meta: model = UserProfile fields = '__all__' read_only_fields = ('created_at', 'updated_at',) def update(self, instance, validated_data): instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.occupation = validated_data.get('occupation', instance.occupation) instance.DOB = validated_data.get('DOB', instance.DOB) instance.about = validated_data.get('about', instance.about) instance.user = ????? # I don't know what do here instance.save() return instance Every help is welcome -
In Django, is on_delete implemented in Python, or using DB triggers, for PostgreSQL databases?
I have an application that shares a database between a large Django application, and a set of microservers (written in Go). If a record is deleted by a microserver, such that a record in a different table has a foreign key that references it, and if I've specified on_delete=models.CASCADE in the respective ForeignKey field, which of the following is true? The dependent record will be deleted by PostgreSQL, or the dependent record should be deleted "manually" by the microserver (this is what I currently do), or is there a way to specify how I want on_delete to be handled? Here's a bit of an example for completeness: from django.contrib.gis.db import models class Parent(models.Model): name = models.CharField(max_length=128) class Child(models.Model): name = models.CharField(max_length=128) parent = models.ForeignKey( Parent, null=False, on_delete=models.CASCADE) and in Go: _, err = db.Exec(`DELETE FROM module_parent WHERE ID = $1`, parentID) or do I have to do: _, err = db.EXEC(`DELETE FROM module_child WHERE parent_id = $1`, parentID) ... _ err = db.EXEC(`DELETE FROM module_parent WHERE id = $1`, parentID -
Is there a django way of grouping records in to groups (groups in a list) and returning a list of ocurrences for each item group?
I have the following list, containing the weeks in the year (python - Django): weeks = list(range(1,53)) I have a Project model with date_started and date_registered attributes as follows: class Project(models.Model): from_company = models.ForeignKey(Company,on_delete=models.CASCADE) project_name = models.CharField("Nombre de Proyecto", max_length=200,unique=True) follow_date = models.DateField("Fecha de Seguimiento", default=timezone.now() + timezone.timedelta(days=5)) date_registered = models.DateTimeField("Fecha de Registro",auto_now_add=True) date_started = models.DateTimeField("Fecha de Inicio",null=True) last_modified = models.DateTimeField("Ultima Vez Modificado",auto_now=True) Currently, I'm itterating through each week and get the lenght of the queryset that matches the date_registered__week with the week in the loop, and appending it to a list, like so: project_active_week = [] for week in weeks: if week is not None: active_projects = [x.project_name for x in Project.objects.filter(date_registered__week = week,date_registered__year = timezone.now().year)] project_active_week.append(len(active_projects)) I have several of this stuff going on and my app has become very slow. Is there a way to perform this more efficiently? Database is Sqlite. Thank you very much for your help!