Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Delete multiple Django objects via ORM [duplicate]
This question already has an answer here: Delete multiple objects in django 1 answer Is it possible to delete many Model instances without iterating over them and calling .delete() on each one? Let's say we have something like this: objects = [o for o in MyObject.objects.filter(...)] objects_to_delete = get_validate_objects(objects) # some of objects from objects And now I want to delete every MyObject in objects_to_delete. Is there any better/smarter way than this?: for o in objects_to_delete: o.delete() -
Sort django rest framework paginated list by date in vue
A list of items needs to be sorted (ASC and DESC) by date on click. This list of items is paginated by Django Rest Framework Pagination. Therefore, the first page of items contains just 15 results. The default sorting is newest date first. Whenever the list is sorted, the current state is sorted by .sort(), through a mutation in Vue. This works, however, just for the current state which only contains the list of items that are in the first page (assuming the user didn't go to next page). This causes the order only to be valid for the results per page, but not for all results. To solve this, I could do an API request to return the results in the correct order, but my question is, is there a smarter way to do this? -
Django error page with DEBUG=True much more detailed than logging
While DEBUG=True in settings.py, any Python error is shown in a page where I can see not only the traceback but also every local variable at the moment of the exception. How can I have such a detailed traceback with local variables in my log files, when DEBUG=False? I've tried this in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'logs', 'django.log'), }, }, 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, 'django.template': { 'handlers': ['file', 'console'], 'level': 'INFO', }, 'app': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, } But the only thing that I get in my log file and in the console are the standard Python traceback's, devoid of any detail. I don't want to know only which line of code caused the error: I also want to know variables values. -
django.db.utils.InterfaceError:('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) )
I have a Django web app with azure sql server,i move the code from one laptop to another and suddenly i got django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') imidatly after starting the web server I have been able to isolate the problem , and realized it coming from the db connection in setting.py , i tried to run simple python quay from the console and it worked I tried all the solutions i saw online with no luck Any ideas? DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'XXXXXX', 'Trusted_Connection':'No', 'HOST' : 'XXXXXXXXXXX', 'DRIVER': '{ODBC Driver 17 for SQL Server}', 'OPTIONS': { 'extra_params': 'APP=Setting.py', }, 'AUTOCOMMIT' : True , 'USER' : 'XXXXXXX', 'PASSWORD' : 'XXXXXXX' }} -
Django apps throw ImportError on Heroku
I'm deploying a Django application to Heroku. This application runs locally, and was built as a structural clone of django-vue-template. The only notable changes being: I have more apps in my project. I do not use a settings package with prod/dev modules, just single module. File structure: The error I get in the build log throws an ImportError on 'users', but its not app-specific, its whatever app is the first Django app in my INSTALLED_APPS. -----> $ python manage.py collectstatic --noinput PYTHONPATH: . BASE_DIR /tmp/build_1803d0c0cef716d3bc64a04ddb7b7ea0/backend Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'users' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can … -
My application container is not able to my mysql container
After all of web searching and coming up of no answer to this, I thought of asking this question on this platform. I had an application container which i try to connect with mine database container but due to reasons unaware mine application is not able to connect. I am providing all the relevant information required for it. Here is mine docker-compose file version: '2' services: application: &application image: gmasmatrix_application:latest command: /start.sh volumes: - .:/app depends_on: - db ports: - 8000:8000 # cpu_shares: 874 # mem_limit: 1610612736 # mem_reservation: 1610612736 build: context: ./ dockerfile: ./compose/local/application/Dockerfile args: - GMAS_ENV_TYPE=local db: image: mysql:5.7.10 environment: MYSQL_DATABASE: gmas_mkt MYSQL_ROOT_PASSWORD: pulkit1607 ports: - '3306:3306' volumes: - my-db:/var/lib/mysql volumes: my-db: I also changed the host in the settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'gmas_mkt', 'USER': 'root', 'PASSWORD': 'pulkit1607', 'HOST': 'db', 'PORT': '3306', } } Here is the error I get upon running the docker-compose up file application_1 | Traceback (most recent call last): application_1 | File "manage.py", line 22, in <module> application_1 | execute_from_command_line(sys.argv) application_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line application_1 | utility.execute() application_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute application_1 | self.fetch_command(subcommand).run_from_argv(self.argv) application_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 394, … -
Error while creating a superuser on heroku with django
I've created an app,called learning logs, on heroku (it is an project from the book python crash course).When I try to create a superuser it shows me an error. I first run (in a termial): heroku run bash and then : python manage.py createsuperuser the main error is the following: You have 20 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, learning_logs, sessions. Run 'python manage.py migrate' to apply them. Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: auth_user The above exception was the direct cause of the following exception: 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) the rest of the error is this: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 61, in execute return super().execute(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 82, in handle default_username = get_default_username() File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/management/__init__.py", line 140, … -
How to make django not to ask for migrations?
When I run my Django project. It prints the following: You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. I'm using raw queries and not using admin and models feature. So migrations will not be of any use for me. How can I make Django to not ask for applying migration? -
Django get ManyToMany variable in template
i have to models linked with ManyToMany relation: class Event(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=512) class Task(models.Model): event = models.ManyToManyField(Event, blank=True, related_name='tasks') description = models.CharField(max_length=1000, blank=True) in view.py i collect all user events by: events = Event.objects.filter(user=request.user) now in template i want to display each event in loop with event-task.description {% for event in events %} {{event.title}} {{event.task.description}} ??? {% endfor %} How to get this work? Related questions: link_1, link_2 -
Unit testing a function which consumes request from django rest api view
I'm not sure what's the proper way to test functions which are used inside views/permission classes. This is the payload of my request: {"name": "John"} And this is the function I want to test: def get_name(request): return request.data['name'] This is the view that will be using the function: class SomeView(APIView): def get(self, request): name = get_name(request=request) return Response(status=200) How should I create a fixture to test the get_name function? I've tried this: @pytest.fixture def request_fixture() factory = APIRequestFactory() return factory.get( path='', data={"name": "John"}, format='json') def test_get_name(request_fixture): assert get_name(request=request_fixture) == "John" But I'm getting an error: AttributeError: 'WSGIRequest' object has no attribute data. One workaround seems to be decoding the body attribute: def get_name(request): data = json.loads(request.body.decode('utf-8')) return data['name'] But it doesn't feel like the right way to do this and I guess I'm missing something about the WSGIRequest class. Can someone explain to me how it should be tested? It would be great if I could use the same fixture to test the view too. -
drf-yasg how to display the api description outside?
I want the describe in there: but mine is in there: This is my code: @swagger_auto_schema(method='GET', manual_parameters=[project_param]) @api_view(['GET']) def get_project_info(request): """ 获取项目信息 """ Version info: Django==2.2.1 drf-yasg==1.16.1 -
Is there a way to annotate django query with non-expression?
I have use case where I need to get all objects where existing_field is the beginning of some string. some string changes dynamically so I need a smart way to filter out objects. My idea is to create annotated query like this: MyModel.objects.annotate(annotated_field='some string').filter(annotated_field__startswith=F('existing_field')) Currently it is failing with: QuerySet.annotate() received non-expression(s): some string Is there a way to annotate objects with string value? -
What is equivalent library of cStringIO in python 3? [duplicate]
This question already has an answer here: python 3.x ImportError: No module named 'cStringIO' 2 answers Currently I am converting my python2 project into python 3 & came up code related to cStringIO module. import cStringIO buffer = cStringIO.StringIO() I know that import StringIO been replaced with from io import StringIO but what will be similiar code in python 3 for CStringIO. -
Django Rest frame work "CSRF Failed: CSRF token missing or incorrect." error on JSONWebTokenAuthentication
I want to send a POST request using POSTMAN and my url is like http://127.0.0.1:8000/restaurant/article/update/23 On login I am sending a token which is Json web token (created like this) https://jpadilla.github.io/django-rest-framework-jwt/#creating-a-new-token-manually def get_token(user): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) return jwt_encode_handler(payload) And on login my api response is like { "success": true, "message": "Successfully logged in", "data": { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6IkRlbW9AZ21haWwuY29tIiwiZXhwIjoxNjAyNzU1MDE4LCJlbWFpbCI6IiJ9.sgLS4NofzDtdUSHYvuepRruw2PgTPLyGCdjIOiLdrkw", "restaurant": { "id": 1, "image": "/media/Restaurant/Entertainment.jpg", "restaurant": "Demo", } } } when I am using this token like this in post man its not working BUT token provided in post man cookie when I use that it works like this .What's going on here ? any help would be highly appreciated. -
Connect django web app to postgresql in gcloud
i have been struggling to connect my django web app to a PostgreSQL instance which I set up inside my gcloud account for testing purposes. I have done the following DB configs in settings.py in Django: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'instance connection name from gcloud', 'USER' : 'postgres', 'PASSWORD': 'passsss', 'HOST': 'ip-address', 'PORT': '5432', } } the error that I receive in Django after trying to migrate is : django.db.utils.OperationalError: FATAL: database "..instance connection name from gcloud.." does not exist I have tried creating a new database "django" and adding it to the NAME with:. This did not work as well. I have also configured in gcloud connections my own computer IP as an authorized network Normally if I use service like elephantsql it works fine. Any help would be appreciated. Thanks! -
The 'image' attribute has no file associated with it
I have been trying to update image since i added an ImageField to model.py but it always gives me this error The 'image' attribute has no file associated with it. From Admin panel given by django i can do so i can add and updat, but i need to create my own way of updating images but id doesn't work. Here are my attachments This is my model class rooms(models.Model): room_number = models.PositiveIntegerField(unique = True) room_type = models.ForeignKey(room_types, on_delete=models.CASCADE) number_of_beds = models.PositiveIntegerField() image = models.ImageField(upload_to = 'room_pics/', null = True, blank = True) price = models.PositiveIntegerField(default=0) class Meta: verbose_name_plural = 'Rooms' def __str__(self): room_number = "Room number: " + str(self.room_number) return room_number Here is a form from forms.py class addRoomForm(forms.ModelForm): class Meta: model = rooms fields = ['room_number', 'room_type', 'number_of_beds', 'price', 'image'] and here are the views from views.py to add and update def add_room(request): form = addRoomForm() if request.method == 'POST': form = addRoomForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Room added successfully!') return redirect('add_room') else: form = addRoomForm() context = { 'form' : form, } myTemplate = 'hotel/addRoom.html' return render(request, myTemplate, context) def update_room(request, id): instance = get_object_or_404(rooms, pk = id) form = addRoomForm(request.POST or None, instance = instance) if … -
Get_next_by_field with complex query
I have model Match that has fields team_first and team_second fields, also it has datetime field for the time of the match. I want to get the next match with team_first, it can be team_first or team_second, so i'm trying to do this query: self.get_next_by_datetime(Q(team_first=team) | Q(team_second=team)) It doesn't work giving me the following error: TypeError: _get_next_or_previous_by_FIELD() got multiple values for argument 'field'. Of course there are some workarounds like getting next with team_first=team and team_second=team and then comparing them and selecting the earliest and etc, but is there way to do it without? -
How to make a forum like tag system for images in Django
I am trying to make a educational website using Django where anyone can create posts. Now in those posts I want to provide links to images in a tag so that it shows up in the post. For example something similar to the html img tag will do. My Post creation view: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content', 'display', 'category'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def cat_on_all_pages(request): return {'cat': Category.objects.all()} My html template for post creation (I use crispy forms here): {% extends "blog/base.html" %} {% block title %}Submit a Course{% endblock %} {% load crispy_forms_tags %} {% block content %} <div> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Submit or Edit a Course</legend> {{form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} -
get celery progress using AJAX in Django
I am new in web development.I want to upload a file and proccess it in a Celery task and show progress percent using AJAX. I used some samples and here is my code: views.py: def importnewdata(request): if request.method == 'POST': form = RawFileAddressForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] file_name = default_storage.save("sample.txt", file) task = proccess_file.delay(file_name) return HttpResponse(json.dumps({'task_id': task.id}), content_type='application/json') else: return HttpResponse("Error!") else: form = RawFileAddressForm() return render(request, 'modelmanager/importnewdata.html', {'form': form}) def get_task_info(request): task_id = request.GET.get('task_id', None) if task_id is not None: task = AsyncResult(task_id) data = { 'state': task.state, 'result': task.result, } return HttpResponse(json.dumps(data), content_type='application/json') else: return HttpResponse('No job id given.') forms.py: class RawFileAddressForm(forms.Form): file = forms.FileField() importnewdata.html: <!DOCTYPE html> <html> <head> <title>import new raw data to db</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </head> <body style="text-align: center;"> <h1>select your file to proccess it!</h1> <progress id="progress-bar" value="0" max="100" style="display:none; margin-bottom: 1em;"></progress> <form id="proccess-raw-data" action="/modelmanager/importnewdata/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"/> </form> <script type="text/javascript"> var frm = $('#proccess-raw-data'); var pgrbar = $('#progress-bar'); frm.submit(function () { $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { if (data.task_id != null) { get_task_info(data.task_id); } }, error: function (data) { frm.html("error!"); } }); return false; }); function get_task_info(task_id) { $.ajax({ type: … -
Django - Need Help Converting View To Class Based
I'm having trouble converting this to a class-based view :/ Can anyone help me out ? (and explain in the process if possibile) I went through the docs, this is the only view from my app that I still didnt convert. def apartment_view(request, apartment_id): reservation = Reservation.objects.filter(apartment__pk=apartment_id) apartment = get_object_or_404(Apartment, pk=apartment_id) unavailable = [] for start, end in apartment.reservations.values_list('start_date', 'end_date'): while start <= end: unavailable.append(start.strftime('%-d-%m-%Y')) start += datetime.timedelta(days=1) form = ReservationForm() if request.method == 'GET': form = ReservationForm() elif request.method == 'POST': form = ReservationForm(request.POST) if form.is_valid(): reservation = form.save(commit=False) reservation.apartment = apartment reservation.save() form.save() return HttpResponseRedirect(reverse('booking:apartment', kwargs={'apartment_id': apartment.pk})) args = {} args['form'] = form args['apartment'] = apartment args['unavailable_dates'] = json.dumps(unavailable) return render(request, 'booking/apartment.html', args) -
Django - Data source name not found and no default driver specified
I am trying to deploy my Django app and connect it to the mssql server. Django app is running on the iis and MSSQL Server 16 I am getting this error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') I am running Django==2.1.11 and pyodbc==4.0.27 This is my settings,py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'my_database', 'USER': 'app_user', 'PASSWORD': 'XXXXX', 'HOST': 'XYZ.XYZ.XYZ.XYZ', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', } } } I have no idea what to do to make it working. -
Can I transfer the site from heroku to another hosting?
The site is currently hosted on heroku. There are constant problems with opening the site. A very long time to open. At first they thought that the reason for falling asleep on a free tariff, but installed a program that wakes up the site and it still opens badly. Now suspicions that RCN is blocking the ip addresses heroku. -
Subscription django paypal integration
Anyone help me on django with website for Subscription of two plans and integrate paypal payment gateway are any basic project on github Thanks In advance -
How to test if user can display his profile?
I've got a model UserProfile. class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE) city = models.CharField(max_length=100, blank=False) region = models.CharField(max_length=100, blank=False) post_code = models.CharField(max_length=100, blank=False) def create_profile(sender, **kwargs): #Funckja, ktora tworzy profile użytkownika user = kwargs["instance"] if kwargs["created"]: user_profile = UserProfile(user=user) user_profile.save() post_save.connect(create_profile, sender=User) def __str__(self): return self.user.username And his view: def user_details(request, pk): user = get_object_or_404(User, pk=pk) userprofile = user.user return render(request, 'user_details.html', {'userprofile': userprofile}) The problem is I want to test if user can display his profile by clicking on: <a href="{% url 'accounts:user_details' pk=user.pk %}">Your profile</a> I can not figure out how to do it. I tried to do this way: from django.test import TestCase from accounts.models import * from django.test import Client class UserDetailsView(TestCase): @classmethod def setUpTestData(cls): cls.client = Client() cls.user = User.objects.create(username="Test") owner = cls.user cls.user.save() def test_view_url_exists_at_desired_location(self): response = self.client.get('accounts/{}').format(owner) self.assertEqual(response.status_code, 200) But it's not working. The full code is here: https://github.com/Incybro/DjangoShop -
Django/Heroku After pushing a new version certain templates do not update
I have made some changes to a Django template, saved them, committed them to git, pushed to GitHub and then deployed this new version to Heroku. The build succeeds and I can view the template but the change is not there. I checked the GitHub repo, the change is there. When I check the activity feed on Heroku I can see the change when I click the Compare diff link. When I make changes to other areas of the project, views etc there's no problem, I have updated other templates without issue but can not get the new CSS into the deployed version. Inspecting the code of the deployed version shows the old CSS not the new so it isn't just an issue with my stylesheet, inheritance or so on. I've run out of ideas, any suggestions of how I can resolve this?