Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to copy information from a table in one project to another project in Django sqlite
I have to projects. They have different Databases. But one table - Brands - is the same. I need to add new brands from one project to another. What is the best way to do it. I tried to do it with the help of dumpdata and load data. But it doesn't work for me. maybe I was doing something wrong. The dumpdata worked well. I've got the json with all the data. But I cannot add this data to my existing table in another database. I solved this problem by parsing json. But I have more tables to copy. And I think there must be a better solution for this. Can someone help with this? -
AttributeError: 'NoneType' object has no attribute 'history_change_reason'
I am saving change history on every change in django model by using django-simple-history. that what I tried: class MyModel(models.models): field1 = .. ... history = HistoricalRecords( history_change_reason_field=models.TextField(null=True) ) name = 'xyz' for doc_id, status in my_data: reporting , _ = Reporting.objects.get_or_create( doc_id=doc_id, user=self.request.user ) reporting.is_accepted = status reporting.save( update_fields=['is_accepted] ) update_change_reason( instance=reporting, reason=f'Change request done by {name}' ) and I got below error. AttributeError: 'NoneType' object has no attribute 'history_change_reason' -
can someone explain me this django views part
def download(request , path): file_path = os.path.join(settings.MEDIA_ROOT , path) if os.path.exists(file_path): with open(file_path , 'rb') as file: response = hr(file.read(),content_type="application/admin_upload") response['Content-Disposition'] = 'inline;filename='+os.path.basename(file_path) return response raise Http404 i saw one on how to upload a img by the admin and the code works fine but i dont understand this part :/ -
How to login as an existing user in django shell
In django shell, I want to debug a specific api call, and for the resource to work, one should be logged in. from django.test import Client from urllib.parse import urlsplit, parse_qsl client = Client() client.login(username='my_username', password='my_password') # I also tried client.force_login() without success url_data = urlsplit(url) r = client.get(path=url_data.path, data=parse_qsl(url_data.query)) # r is <HttpUnauthorized status_code=401, "text/html; charset=utf-8"> How do I login properly? -
repeat watermark only once per page when printing the html page
I'm using pdfkit with Django to convert a html template into pdf. The template is 3 page long when printed and I need to display a "Cancelled" watermark on each page of the document when printed. Currently, it only gets printed once in the first page, but i need it to be printed at the center of the page, once on all the pages <style> #watermark { display:block; z-index: 99999; width: 86%; position:fixed; } #watermark img { opacity: 0.2; filter: alpha(opacity=15); } </style> <div id="watermark"> <img src="/media/images/policy_cancel.png" style=" width: 650px; height: 414px;"> </div> -
My models do not display in production template Django/nginx/postgre
I have a little issue I am unable to resolve. Live website doesnt display the faq template as it would be if my index.html doesnt recieve anything in the context. In localhost it displays everything properly and shows models in admins. In production it has all the models in admin, but doesnt display anything. (The only difference between local and production-I dont use postgre, instead using sqlite)...But again I can CRUD models on live server through python manage.py shell or www.website.com/admin panel. Any suggestions? For extra code look source code at https://github.com/Eakz/engyschool My index.html <div id="faq"> {% for i in faqsdown %} <div class="question down"> <div class="dropdown"> {% if i.question|length > 28 %} <div class="trigger" style="font-style: italic;">{{i.question|slice:":28"|add:"..."}}</div> <div class="content"> <p style="font-style: italic;">{{i.question|slice:"28:"}}</p> <hr> {{i.answer}} </div> {% else %} <div class="trigger">{{i.question}}</div> <div class="content"> <hr> {{i.answer}} </div> {% endif %} </div> </div> {% endfor %} {% for i in faqsup %} <div class="question up"> <div class="dropdown"> {% if i.question|length > 28 %} <div class="trigger" style="font-style: italic;">{{i.question|slice:":28"|add:"..."}}</div> <div class="content"> <p style="font-style: italic;">{{i.question|slice:"28:"}}</p> <hr> {{i.answer}} </div> {% else %} <div class="trigger">{{i.question}}</div> <div class="content"> <hr> {{i.answer}} </div> {% endif %} </div> views.py import os from django.conf import settings from django.shortcuts import render from django.templatetags.static import … -
Django RelatedObjectDoesNotExist error related in foreign key
my model : class Problem(models.Model): ... prob_id = models.IntegerField(null=False, unique=True) #autofield?, (unique=True) ... def __str__(self): return str(self.prob_id) def prob_path(instance, filename): return 'upload/{0}/{1}'.format(instance.problem, filename) class Testcase(models.Model): problem = models.ForeignKey(Problem, on_delete=models.CASCADE) input_data = models.FileField(upload_to=prob_path) output_data = models.FileField(upload_to=prob_path) def __str__(self): return str(self.problem) views.py : def problem_write_foruser(request): if request.method == "GET": form = ProblemForm() form_t = TestcaseForm() if request.method == "POST": form = ProblemForm(request.POST) form_t = TestcaseForm(request.POST, request.FILES) if form.is_valid(): user = CustomUser.objects.get(username = request.user.get_username()) new_problem = Problem( ... prob_id = form.cleaned_data['prob_id'], ... ) new_problem.save() if form_t.is_valid(): form_t.problem = new_problem form_t.input_data = Testcase(input_data = request.FILES['input_data']) form_t.output_data = Testcase(output_data = request.FILES['output_data']) form_t.save() return redirect('koj:problemset') context = {'form':form, 'form_t':form_t} return render(request, 'koj/problem_write_foruser.html',context) forms.py class ProblemForm(forms.ModelForm): ... prob_id = forms.IntegerField() ... class Meta: model = Problem fields = ['prob_id', 'title', 'body', 'input', 'output', 'time_limit', 'memory_limit'] class TestcaseForm(forms.ModelForm): input_data = forms.FileField() output_data = forms.FileField() class Meta: model = Testcase fields = ['input_data', 'output_data'] when i submit this form in website, RelatedObjectDoesNotExist error is occured i think 'form_t.problem = new_problem' in views.py and relation of Problem model and Testcase model Testcase has no problem. Request Method: POST Request URL: http://127.0.0.1:8000/problem_write_foruser/ Django Version: 3.0.8 Exception Type: RelatedObjectDoesNotExist Exception Value: Testcase has no problem. Exception Location: /home/dsyun/grad/venvs/mysite/lib/python3.6/site- packages/django/db/models/fields/related_descriptors.py in get, line … -
How to upload Multiple images using Django Rest Framework using foreign key?
i can not upload multiple image using Django rest framework.i have Searched this and i Found that using ForeignKey we can upload multiple images.for that We have to make two models.But i dont know how to use Foreign key for multiple image upload.i have tried many Code but did not Worked.can any one help me with this Issue? i have following code, In My models.py class UserModel(models.Model): username= models.CharField(max_length=255) user_images= models.ImageField(upload_to='images/') In My Forms.py from django import forms from user_register.models import UserModel #user_register is my app name class UserForm(forms.ModelForm): class Meta: model = UserModel fields = "__all__" My serializers.py is from user_register.models import UserModel #user_register is my app name from rest_framework import serializers class userSerializer(serializers.ModelSerializer): class Meta: model = UserModel fields = "__all__" And This is My views.py @api_view(['POST','GET']) def userfunction(request): if request.method=='POST': form = UserForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponse('Data Inserted') else: return HttpResponse('form is invalid') i Want my all images to be saved in 'images' folder.Can any one help me with this Issue? i would appreciate if anyone can help me. -
Creating React-Django project
I have confusion on creating react django project.I found two type of approaches of creating react-django project. First creating django project and the integrate react on it.(using npm run build) Creating react project and django project seprately Which approach is best?and which to use when? -
I am unable to install Django in my machine, It is showing error and I don't know what exactly I am doing wrong
Hello I tried installing Django in my laptop, but due to some reason it is not installing properly. i don't know what to do please help me. I have Python 3.8.5 installed in my computer, and I am using Windows 10 operating system. I tried installing django using pip install django It is giving me this error C:\Users\DELL>pip install django Collecting django Downloading Django-3.1.1-py3-none-any.whl (7.8 MB) |▌ | 143 kB 8.0 kB/s eta 0:16:01ERROR: Exception: Traceback (most recent call last): File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_vendor\urllib3\response.py", line 437, in _error_catcher yield File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_vendor\urllib3\response.py", line 519, in read data = self._fp.read(amt) if not fp_closed else b"" File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 62, in read data = self.__fp.read(amt) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\http\client.py", line 458, in read n = self.readinto(b) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\http\client.py", line 502, in readinto n = self.fp.readinto(b) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\ssl.py", line 1241, in recv_into return self.read(nbytes, buffer) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\ssl.py", line 1099, in read return self._sslobj.read(len, buffer) socket.timeout: The read operation timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_internal\cli\base_command.py", line 228, in _main status = self.run(options, args) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_internal\cli\req_command.py", line 182, in wrapper return func(self, options, args) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_internal\commands\install.py", line 323, in run … -
KeyError at /api/stores/product/create/ 'product_variation' in Postman while testing Django rest framework api
Hey guys i am getting this KeyError at /api/stores/product/create/ 'product_variation' in Postman while testing Django rest framework api. What has gone wrong with my code? Please do help. serializer class ProductCreateSerializer(serializers.ModelSerializer): images = serializers.ListField(child=serializers.ImageField()) #limit the number of images to 5 product_variation = ProductVariationSerializer(many=True, required=False) def create(self, validated_data): image = self.context['request'].FILES.get('image') images = self.context['request'].FILES.getlist('images') images_data = validated_data.pop('images') variations_data = validated_data.pop('product_variation') product = Product.objects.create(user= self.context['request'].user, **validated_data) for image in images_data: ProductImage.objects.create(product=product, **image) for variation in variations_data: ProductVariation.objects.create(product=product, **variation) return product views class ProductCreateAPI(generics.CreateAPIView): serializer_class = ProductCreateSerializer permission_classes = [IsAuthenticated] authentication_classes = (TokenAuthentication,) def create(self, request, *args, **kwargs): serializer = ProductCreateSerializer(data=request.data, context={'request':request,}) if serializer.is_valid(): serializer.save() return Response({'response':'Product listed successfully.'}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is how I give in postman, the product_variation as key and [{ "size-colour": "1", "size_name": "small", "colour_name": "Green", "price": "100", }, { "size-colour": "2", "size_name": "medium", "colour_name": "Blue", "price": "100", }] and this as the value, but still it shows the error. What can be the reason? Thanks -
How to launch this command mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql on Xampp Ubuntu
Hello i'm writing a website in django but I've this error: *Database returned an invalid datetime value. Are time zone definitions for your database installed?* People say that to solve this, i want to run this code: mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql The problem is that, I can't run this command because I'm using MySql from Xampp. How can I launch this command using Xampp's MySql? -
How do I create a custom view that doesn't depend on a model in the Django admin site?
Is it possible to have the Django admin site have a link to a custom view that isn't actually a model alongside the models? That custom view will have an add functionality that adds to every model in my existing database. -
Python Django: Filled in form field always throws error "This field is required" on POST
I have a form where I just included one textbox and a submit button. Everytime when I fill in the textbox and try to submit the form validation fails and the error message "This field is required" gets thrown. add_stock.html {% extends 'base.html' %} {% block content %} <h1>Add Stock</h1> <form action="{% url 'add_stock' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input class="form-control" type="text" id="ticker"> <button type="submit" class="btn btn-primary">Add</button> </form> {{ form.errors }} {% endblock %} views.py def add_stock(request): if request.method == 'POST': form = StockForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, ('Stock has been added')) return redirect('overview') return render(request, 'add_stock.html', {'form':form}) return render(request, 'add_stock.html', {}) models.py from django.db import models class Stock(models.Model): ticker = models.CharField(max_length=10) #trade_date = models.DateField(blank=True, default='') #quantity = models.IntegerField(blank=True, default='') #unit_price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, default='') #brokerage = models.DecimalField(max_digits=3, decimal_places=2, blank=True, default='') def __str__(self): return self.ticker forms.py from django import forms from .models import Stock class StockForm(forms.ModelForm): class Meta: model = Stock fields = ["ticker"] #fields = ["ticker", "trade_date", "quantity", "unit_price", "brokerage"] Error message -
How to fetch Google Meet participants using Google Api - Python
Hey we are creating Google Meet links using Calendar Api. No we have requirement to fetch participants in a meeting. We are able to see the participants from Gsuite Audit Report. We tried using Admin SDK Reports API. But we have getting Access denied googleapiclient.errors.HttpError: <HttpError 401 when requesting https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/meet?alt=json&maxResults=10 returned "Access denied. You are not authorized to read activity records."> SCOPES = ['https://www.googleapis.com/auth/admin.reports.audit.readonly'] def main(): creds = ServiceAccountCredentials.from_json_keyfile_name('srv.json', scopes=SCOPES) service = build('admin', 'reports_v1', credentials=creds) results = service.activities().list(userKey='all', applicationName='meet', maxResults=10).execute() print(results) We are using python (Django) -
How to implement upvotes and downvotes in Django models?
I am trying to develop a reusable votes Django application that can fit any model and allow me to avoid code duplication. Its purpose should be to just upvote and downvote objects. For example, I could develop a project where there are Question and Answer models, both of which have their respective score field (upvotes - downvotes). The code in models.py could look something like this: class Question(models.Model): score = models.IntegerField(default=0) def upvote(self): self.score += 1 def downvote(self): self.score -= 1 class Answer(models.Model): score = models.IntegerField(default=0) def upvote(self): self.score += 1 def downvote(self): self.score -= 1 It is clear that this code would work but is not well designed since the two models are practically a copy of one another. To solve this, I was thinking about creating a votes app with perhaps a Vote model in it that would fit both the Question and Answer models described above. I tried to create a single Vote model in votes/models.py, but I ended up needing two models anyway: a QuestionVote and an AnswerVote model. Besides, I could not really integrate this code with the Question and Answer models at all. Here is the general idea for the QuestionVote model I came … -
Django rest framework one to one relation model
I would like to add phone number as one to one relation to django User table. is there I can get phone number field too at the registration. -
Admin filters for django admin
Django admin provides very basic view for applying filters on List pages but we have several uses cases where we want multi select, multi search, range filtering. These cases include applying filtering on related fields and reverse related fields as well We explored several packages https://github.com/modlinltd/django-advanced-filters https://github.com/silentsokolov/django-admin-rangefilter https://github.com/lukasvinclav/django-admin-numeric-filter but none seems to fit our use cases well without fiddling with base model admin. Are there alternatives to these ? If creating own custom filters how are you handling such uses cases ? - any ideas / tips / suggestion to start with ? I did get some idea for search here - https://medium.com/@hakibenita/how-to-add-a-text-filter-to-django-admin-5d1db93772d8 for multiple options to search, planning to use comma separated values and then split that in backend confused on how to implement for multi select choices -
Pyinstaller Django Channels issue
I'm trying to pack a django app into an .exe, after a multiple tries (hooks etc...) Everything works fine, except django-channels. When I run mysite.exe runserver, the app starts but the routing are not found and channels are not working. Here is my .spec -- mode: python ; coding: utf-8 -- block_cipher = None a = Analysis(['mysite\manage.py'], pathex=['C:\Users\SFadili\Documents\_Never Backup\Django\help2'], binaries=[], datas=[ ('mysite/templates', 'templates'), ('mysite/static', 'static'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\plotly\', 'plotly'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\daphne\', 'daphne'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\daphne-2.5.0.dist-info\', 'daphne-2.5.0.dist-info'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\raven\', 'raven'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\raven-6.10.0.dist-info\', 'raven-6.10.0.dist-info'), ], hiddenimports=[ 'mysite.routing', 'mysite.urls', 'myapp.apps', 'myapp.urls', 'myapp.routing', 'myapp.consumers', 'channels.apps', 'channels_redis', ], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='mysite', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=True ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='manage') FYI : I had an issue with daphne saying that another application is using the server, I solved it by modifiying the pyi_rth_twisted.py file into : from twisted.internet import asyncioreactor This creates module: sys.modules['twisted.internet.reactor'] asyncioreactor.install() when I run the server , I got thit : System check identified no issues (0 silenced). September 14, 2020 - 10:13:24 Django version 2.2.16, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the … -
Django - nearby user without geodjango?
I'm looking for any suggestions and alternative to Geodjango. My goal is to propose to user to find the nearest users and display a distance between them. I got a classical model for localisation. class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') ... -
Django Quill text-editor
I have a problem when trying to add a value to QuillField field. I have a model field like this : ... from django_quill.fields import QuillField ... ... quill_field = QuillField(blank=True, null=True) #QuillField ... And the idea is to add a value on object creation inside the create function : ... if form.is_valid(): obj_ = form.save(commit=False) ... obj_.terms_of_use_text = get_default_terms() #Here obj_.save() ... ... With get_default_terms() function which basically just pulls all the text from txt file: def get_default_terms(): cpath = Path.cwd() document = open((Path(cpath, 'properties/defaultTerms.txt'))).read() text_json = { "delta": "{\"ops\":[{\"insert\":\"%s} \\n\"}]}", "html": "<p></p>" } return json.dumps(text_json['delta'] % document) get_default_terms() function returns simple text in a normal format : "TERMS AND CONDITIONS\nAll of the membership rules contained herein apply equally to members, temporary members and guests alike.\nOverview\nAll reference to the [Property Address] or [Property/Company Name] refers to [Property/Company Name], its staff, employees, sub contractors, agents and representatives. Facilities refer to any of the rooms to be reserved within. Including but not limited to: the gymnasium, showers, saunas, changing rooms and fitness studios where applicable.\n... The problem appears when I try to save the text inside the QuillField, I get django_quill.quill.QuillParseError: Failed to parse value error. Any idea why I can't … -
Django bulk_update not working on default attributes
I want to change the default value of an attribute from a model in Django. So I want to update the existing values in the database. Strange enough, a bulk update doesn't change those values. My model: class UserSettings(models.Model): offline_notification_filter = models.BooleanField(default=False) My test class TestSetOfflineNotificationMigration(APITestCase): def test_set_offline_notification_filter_to_false(self): user_settings_1 = UserSettingsFactory(offline_notification_filter=True) user_settings_2 = UserSettingsFactory(offline_notification_filter=False) user_settings_3 = UserSettingsFactory(offline_notification_filter=True) user_settings_4 = UserSettingsFactory() all_user_settings = UserSettings.objects.all() for user_setting in all_user_settings: user_setting.offline_notification_filter = False UserSettings.objects.bulk_update( all_user_settings, ["offline_notification_filter"] ) self.assertEqual(user_settings_1.offline_notification_filter, False) This test is failing because the the offlince_notification_filter is not updating. Anyone knows why not? -
In Django, how to keep many-to-many relations in sync?
What's the best way, in Django, to set and keep up-to-date a many-to-many field that is (for a lack of a better term) a composite of many-to-many fields from other models? To give a concrete example, I have a Model representing a Resume. class Resume(models.Model): owner = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="resume", ) description = models.TextField(default="Resume description") skills = models.ManyToManyField(Skill, related_name="resume") The Resume object is referenced by another model called WorkExperience: class WorkExperience(models.Model): ... skills = models.ManyToManyField(Skill, related_name="work") owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False, default=1, related_name="work_experience", ) resume = models.ForeignKey( Resume, on_delete=models.CASCADE, null=False, default=1, related_name="work_experience", ) Notice that there's a fair amount of redundancy here, with both Resume and WorkExperience pointing to the same owner etc. That said, both of these Models (Resume & WorkExperience) have a field called Skills. That reference another Model called Skills. What I'd like is to have the Resume skills to point to the same skills as the ones in WorkExperience. Any suggestions on how to do this? I also have a Model called EducationExperience which also references Skills and has a foreign key relation to Resume. Is there any way to keep the skills in Resume be in sync with both the skills in WorkExperience … -
Pytest Django: access database but not in a transaction
According to the documentation of pytest.mark.django_db https://pytest-django.readthedocs.io/en/latest/helpers.html#pytest-mark-django-db-request-database-access, using pytest.mark.django_db Each test will run in its own transaction This makes it tricky to test certain behaviours with multiple sessions [say, with others started in other threads]. Specifically, if production code uses autocommit, which is the default, changes due to database statements become visible to other sessions immediately. However, in the test, changes in the main session won't be visible to others since the first is wrapped in a transaction. However, if I don't use pytest.mark.django_db, then running the test I get the error: RuntimeError: Database access not allowed Is it possible to have database access, but not in a transaction? -
"detail": "Authentication credentials were not provided." test.py
I am writing a test in test.py like this class TodoListCreateAPIViewTestCase(APITestCase): url = reverse("todolist:add") def setUp(self): self.username = "john" self.email = "john@snow.com" self.password = "you_know_nothing" self.user = User.objects.create_user(self.username, self.email, self.password) self.token = Token.objects.create(user=self.user) self.api_authentication() def api_authentication(self): self.client.login(username=self.username, email=self.email , password=self.password) self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) def test_create_todo(self): self.client.force_login(user=self.user) response = self.client.post(self.url, {"list_name" : "Clean the room!"} format='json', HTTP_AUTHORIZATION='jwt {}'.format(self.token)) self.assertEqual(201, response.status_code) and this always gives 401 in return. how I can authenticate properly user here. any kind of help would be highly appreciated .