Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wrong authentication of password
I am working on a form which is like a user login form but without default django's default authorisation. so it takes parameters and check that whether password entered is correct or not . def clean(self): form_data=self.cleaned_data LoginUsername=form_data['Username'] LoginPassword=form_data['Password'] if DiaryUser.objects.filter(Username=LoginUsername): UserCredentials=DiaryUser.objects.filter(Username='LoginUsername') for UserCredential in UserCredentials: if UserCredential.Password !=LoginPassword: raise ValidationError("The Password is not correct ") else: self._errors["Username"]="The User Credentials entered is not present in our database" del form_data['Username'] return form_data But when User enters wrong password it keeps on redirecting to success page. what is wrong with above code snippet. -
Django App installed from Git but not found
I want to install some apps I have developed and are hosted on my own git service but since it appears they have been correctly installed, when I add them to INSTALLED_APPS throws me a ModuleNotFoundError This is my setup file for the app setup( name='my-teams', version='0.1', packages=find_packages(), include_package_data=True, license='GPL', description='Teams app', long_description=README, url='https://<url>/my-teams', author='...', author_email='...', classifiers=[ ... ], install_requires=[requirements], ) This is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_teams', ] And this is what I've added to my requirements.txt file: -e git+https://<url>/my-teams.git@master#egg=my_teams When I install requirements.txt it seems to be okay: Found existing installation: my-teams 0.1 Uninstalling my-teams-0.1: Successfully uninstalled my-teams-0.1 And it appears when I execute pip freeze -e git+https://<url>/my-teams.git@cfa8cbf84d8d91ce573f33da3156e8f7f241d63a#egg=my_teams Finally, when I run python manage.py runserver it throws me the exception: ModuleNotFoundError: No module named 'my_teams' Could you please tell me what I'm doing wrong or what I'm missing? Thank you! -
Combine models and send to template
I want multiple data to be sent from two different model to a template class UserListView(generic.ListView): model = UserProfile template_name = 'users/users.html' context_object_name = 'users' class UserListView(generic.ListView): model = User template_name = 'users/users.html' context_object_name = 'users' -
Django Rest Framework I can't use Serializer save model of have foreign key
I'm a Django Rest Framework and Django newbie i can use random data to make stages but i can't use serializer to add new stages. My model and serializer class Stage(models.Model): class Meta: db_table = 'stage' stage_id = models.AutoField(primary_key=True) stage_name = models.CharField(max_length=64, null=False) company = models.ForeignKey( Company, db_column='id', on_delete=models.CASCADE, ) class StageSerializer(ModelSerializer): stage_id = IntegerField(read_only=True) class Meta: model = Stage fields = [ 'stage_id', 'stage_name', 'company', ] def update(self, instance, validated_data): pass def create(self, validated_data): # create stages stage = create_stage(**validated_data) return stage view.py class StageListAPIView(APIView): def post(self, request, company_id): data = request.data.copy() company = get_company_by_id(company_id) data['company'] = company.pk serializer = StageSerializer(data=data) if not serializer.is_valid(raise_exception=True): return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) new_data = serializer.validated_data serializer.save(company=company) return Response(new_data, status=HTTP_200_OK) request.data <QueryDict: {'stage_name': ['kAkSdKq9Gt'], 'company': [6]}> i will receive error: TypeError: Object of type Company is not JSON serializable i can't understand it and i don't know how to use serializer to save foreign key. -
Check ValueError before saving form
I’ve got an EventForm for my Event Model and in this event form I add some custom_questions, which have their own model CustomQuestions. I add those questions to my event form like: CustomQuestion.add_fields(self, self.program, instance=kwargs.get('instance'), scope='event') the add_fields function basically creates a small form for those questions. Now when I create or edit my Event, I always call CustomQuestion.save_changes(form, program=self.get_program(), instance=form.instance) in the event_create or event_edit methods. The save_changes has a check that validates the answers for my custom questions like: @staticmethod def save_changes(form, program, instance): (..) if not custom_question.validate_answer(custom_answer_value): raise ValueError("The value of '{}' is not a valid choice for the question '{} (type: {})'.".format(custom_answer_value, custom_question, custom_question.type)) It works fine and I receive a ValueError when they’re wrong, but is it somehow possible to do a check in my event Form for this ValueError and show an error message to the user that something went wrong and NOT save the form? I know I can show an message AFTER the form was saved in my event_create or event_update method, but I don’t want to repeat the code twice and also it only shows the messages after everything was saved. My event form looks like this: class EventForm(forms.ModelForm): (..) def … -
How to create common folder for css and js files in Django?
setting before any change. STATIC_URL = '/static/' here I want to create one static files folder rather than assigning them to each every app by creating there name as directory and then I have to assign. So I want one common folder for all JS and Css which can be reflected in each and every template rather than defining all of them at different places. -
How to create rotation log in Django?
I want to create a logger that will work in the following way: I want to limit the log file size to - X mb, and when the file is full, I want that it to continue putting new logs to end of file, but erasing the older logs from beginning of the file. Is this something possible to achieve? I tried to use RotatingFileHandler but it doesn't seem to work, because the file exceeded the max size. Here is how I configured the handlers section in LOGGING dictionary, in my settigns file: 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/home/ubuntu/logs/django.log', }, 'request_file_info': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/home/ubuntu/logs/request_configuration.log', 'formatter': 'verbose' }, }, -
How to filter queryset by full ManyToManyField occurrence?
I have a model with ManyToManyField class CustomUser(AbstractBaseUser, PermissionsMixin): skills = models.ManyToManyField('pro.Skill', related_name='users', blank=True) And search on it implemented by non-optimized way: def get_queryset(self): result = CustomUser.objects.all() if 'skills' in self.request.query_params: skill_ids = [int(sid) for sid in self.request.query_params.get('skills').split(',')] for skill_id in skill_ids: result = result.filter(skill_ownerships__skill_id=skill_id).distinct() return result.exclude(pk=self.request.user.pk) I need to get the same result by one query to the database. I need to find all users that have all skills, that are in skill_ids array. -
Generating a Fixed alpha + sequential numeric values in python
I am trying to workout a method where in my models would have a field that has a structure like: "ITEM1", where in the numeric part would increase sequentially and be unique eg: "ITEM2", "ITEM3", and so on. I am not sure how to achieve this. Please point me in the right direction. Thanks in Advance. -
How to make 2 for loop for these function in one
i have some problem how to merge 2 for loop in one, the function like this : for profile in profileContent['profiles']: profileName = profile['profileName'] for data_setting in profileContent['datasettings']: dataSettingName = data_setting['dataSettingName'] i have merge 2 for loop in one like this but still wrong, any idea for fix this? for profile,data_setting in profileContent['profiles']: profileName = profile['profileName'] dataSettingName = data_setting['dataSettingName'] -
How to see SQL query that caused error in Django migration?
I'm trying to run a data migration that deletes all rows in a table (say, MyModel). There is another table that points to that table (RelatedModel). The field in the RelatedModel that maps to MyModel has on_delete=models.SET_NULL. When I run the migration, however, I get: File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 211, in _commit return self.connection.commit() IntegrityError: update or delete on table "MyModel" violates foreign key constraint "f2274d6f2be82bbff458f3e5487b1864" on table "RelatedModel" DETAIL: Key (uuid)=(ywKMUYx7G2RoK9vqqEWZPV) is still referenced from table "RelatedModel". I added a breakpoint in the migration and checked the SQL DELETE queries. I ran them interactively in the shell and they worked inside the transaction, but the migration still breaks when it tries to commit it. I can't see however which query exactly causes this error, so I don't know how to debug this. Any suggestions? Thanks. PS: I'm using Django 1.9.13, Python 2.7, PostgreSQL 10.4. -
Django: Add value in template_tag
I am using django-qr-code. Just adding {{ attendee.ticket_code }} generates {{ attendee.ticket_code }} what I didn't intend. Can you tell me how I get the value of {{ attendee.ticket_code }} in there? {% qr_from_text "{{ attendee.ticket_code }}" size="M" %} -
Render Django template on AJAX call
So far I have been rendering Django templates via forms as below: return render(request,'base/errorPage.html') I would like to know how to render a template using HttpResponseRedirect(reverse('base:errorPage')) when doing an AJAX call. My Django AJAX view function generally returns JSON data. AJAX code in VUE Axios : axios({ method: 'post', url: 'ajax/logout/', data: { }, responseType: 'json', }) .then ( function (response){ console.log('AJAX success'); // window.location = '';//i cant just use this to call a url coz i need to send input para }.bind(this)) .catch ( function (error){ console.log('ajaxLogout error=',error); }); Django view looks like : def ajaxLogout(request): # return HttpResponseRedirect(reverse('base:errorPage')) return JsonResponse ({"success":1} ) I want to call return HttpResponseRedirect(reverse('base:errorPage')) in my ajaxLogout python function. -
Access the uploaded image file from models.imagefield in Django
I want to process the image before saving it while uploading from models.ImageField(upload_to=None) but i could not be able to find the way to access the image. my code is below from django.db import models class Document(models.Model): document_name = models.CharField(max_length=200) img = models.ImageField(upload_to=None) some_func_value = Process_image(img) In the above code Process_image() function expects an image file in the form of numpy array in its argument to process but when i pass img i.e Process_image(img) it gives me an error that img is not a numpy array. I want to find a way to access the image to process it before saving it. Also what is returned by models.ImageField() in other words what is the type of img variable in above code? is there anyway to access an image from img variable -
django how to display a weeks data
Hi thanks for helping me I being doing some browsing on google and stack overflow, but documentation django and python I can hardly understand, how the they make code run I just can't figure out a way to display week data (table & chart) with two toggle button to toggle different weeks of 53 weeks in a year I had try using the week in Django template tags; https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#date but I get empty value instead; here example I did {{ value|date:"W" }} is there easily way to do this? I do not wish to use the weekarchiveview: https://docs.djangoproject.com/en/2.1/ref/class-based-views/generic-date-based/#weekarchiveview As I need to toggle between years,months and weeks on same page. Below are my codes this my code for views from django.shortcuts import render from django.views.generic import ListView, DetailView ,TemplateView from zigview.models import tank_system from django.utils import timezone from datetime import date, timedelta class EC(ListView): model = tank_system template_name = 'FrounterWeb/extends/EC.html' ordering = ['-datetime'] # sort dates in descending order def get_context_data(self, **kwargs): return {'tank': self.get_queryset()} This is my apps url codes from django.urls import path from . import views #function views from django.views.generic.base import TemplateView from django.contrib.auth.decorators import login_required, permission_required urlpatterns = [ path('',login_required(views.index.as_view()), name='index'), # views to call our … -
how to add thumbnail in the external url in django
I create an URL, but the image is not added so I want to add an image in that URL is http://13.126.39.143/en/health/shilpa-shetty-s-quick-fix-yoga-15-min-full-body-workout/ -
How to make Django REST User API with complex permissions
I want to make a Django REST User API with complex permissions as follows: GET Only Admin should be able to get all User data Logged in User should be to get himself and the names of other Users PUT Only Admin and Self should be able to PUT Except for is_staff and is_superuser only is_superuser should be able to change the status of a user Password changes by a User should require the old password if User is !is_staff password reset should be possible POST / DELETE Only Admin should be able POST/DELETE User User should be able to update his own Profile Unfortunately, I have no idea how to control the view or serializer to allow such permissions. Is there a template how I can exactly control the permissions? -
How do I make custom URLs using django?
Right now my urls.py file looks like so: re_path(r'^product-offers/(?P<product_item_id>[-\w]+)$', views.ProductOffersListView.as_view(), This takes a user to the page: www.shop.com/product/1234 However, is there any way to display the URL with the title (even if that URL doesn't change the dispatching). I want the URL to look like this: www.shop.com/product/1234/toy-truck The "toy-truck" part doesn't have to do anything, but it looks professional and would be nice to have. -
I could not createsuperuser for django
I want ti create super user I used For create super user command prompt When I write This Code Python manage.py createsuperuser I am taking this error Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 112, in handle username = self.get_input_data(self.username_field, input_msg, default_username) File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 193, in get_input_data raw_value = input(message) File "C:\Users\ysr\Desktop\Blog\venv\lib\encodings\cp437.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character '\u0131' in position 6: character maps to I am using pycharm2018.3.1x64 Please Help me Thanks for your Reply -
Heroku application error: An error occurred in the application and your page could not be served (django)
Hi i am newbee in heroku and stuck in process of deploying heroku application and i am not able to track where is the error so please help me out , using python django for application :- after running heroku log (fdttest) abhisek@jarvis:~/Desktop/testenvFDT/foodmood$ heroku logs 2018-12-12T19:49:28.330386+00:00 app[api]: Initial release by user raizadaabhi11@gmail.com 2018-12-12T19:49:28.330386+00:00 app[api]: Release v1 created by user raizadaabhi11@gmail.com 2018-12-12T19:49:30.426621+00:00 app[api]: Enable Logplex by user raizadaabhi11@gmail.com 2018-12-12T19:49:30.426621+00:00 app[api]: Release v2 created by user raizadaabhi11@gmail.com 2018-12-12T21:10:51.000000+00:00 app[api]: Build started by user raizadaabhi11@gmail.com 2018-12-12T21:10:52.000000+00:00 app[api]: Build failed -- check your build logs 2018-12-12T21:15:18.000000+00:00 app[api]: Build started by user raizadaabhi11@gmail.com 2018-12-12T21:15:19.000000+00:00 app[api]: Build failed -- check your build logs 2018-12-12T21:21:05.000000+00:00 app[api]: Build started by user raizadaabhi11@gmail.com 2018-12-12T21:21:22.000000+00:00 app[api]: Build failed -- check your build logs 2018-12-12T21:24:47.000000+00:00 app[api]: Build started by user raizadaabhi11@gmail.com 2018-12-12T21:25:21.659682+00:00 app[api]: Attach DATABASE (@ref:postgresql-flexible-33726) by user raizadaabhi11@ gmail.com The Procfile contain :- web: gunicorn foodmood.wsgi --log-file - -
how to send automate birthday email using cron job in django
I want to send automatically email to birthday boy. how to use cron jobs. i did not get any proper tutorial all over internet please help me out guys -
Where is context.base_url set?
I'm using behave and behave-django for my django project's testing. When I run print(context.base_url), I thought http://localhost:8000 was displayed. In fact, for example, http://localhost:40655 is displayed. The port number is always changing. Why? My environment: macOS(v10.14.1), Docker(v18.06.1-ce), Django(v2.1.4), behave(v1.2.6), behave-django(v1.1.0) I want to set the fixed port number. What should I do? -
How to get serialized API view data into another view?
What is the best way to get DRF API view data into another Django view? Currently I am just calling the view through requests module: response = requests.get('my_api_view') but is there a cleaner way? I can also just instantiate the API view class in another view, but this will give me unserialized objects. -
How to convert django default timezone to different format
time format "2018-12-13T05:20:06.427Z" django providing time xone in above format when i am fetching data from database using ORM query. in my model field is in below way. models.DateTimeField(auto_now=True, blank=True,null=True) HOw can i convert it into "24 feb 2018" like this -
Django Model Field with Secondary Field
I am trying to create a user sign up form in Django that allows for a primary field with an associated integer field. I need each user to be able to select a genre (for movies), and then the percentage (0-100) they like that genre. I have created the percentage as a separate model, but I need it to be associated with each genre per user. How can I associate each user's genres with a specific "like" percentage? Right now, I just have a box of the genre list, with no way to select the percentage like for each genre. #app/models.py class Length(models.Model): length = models.IntegerField(default="Default") def __str__(self): return str(self.length) class Genre(models.Model): title = models.CharField(max_length=40, help_text="Enter genre name", default="Default") like = models.ManyToManyField(Like, help_text='Genre like percent', default="1") def __str__(self): return self.title #users/models.py import stuff class User(AbstractUser): first_name = models.CharField(max_length = 30, blank = True) last_name = models.CharField(max_length = 30, blank = True) email = models.EmailField(unique = True) city = models.CharField(max_length = 30, blank = True, default='Default Town') state = models.CharField(max_length = 2, default='CA') summary = models.CharField(max_length=250, default='Default summary') genres = models.ManyToManyField(Genre, help_text='Select each genre.', default='default', related_name='genre_model') def __str__(self): return self.email #users/forms.py class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = User fields = ['username', …