Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python django model object showing None and null in template
I have this table. class MyTable(BaseModel): key = m.CharField(max_length=20,null=False,unique=True) pre_json = m.JSONField(blank=True, null=True) post_json = m.JSONField(blank=True, null=True) And I use this model through ListView/UpdateView in list html template {{obj.pre_json}} in edit html template {% render_field form.pre_json class="form-control" %} Upper one shows None in template Lower one shows null in textarea as placeholder. Why this two are shown? or can I erase these? I want to stop this -
CSV Getting decoded in wrong format in Django
I am trying to read a csv file located in AWS S3 Bucket using DefualtStorage. from django.core.files.storage import DefaultStorage def upload_file_view(request): form = CsvModelForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = CsvModelForm() print(Csv.objects.all()[1]) obj = Csv.objects.all()[1] with storage.open("{}".format(Csv.objects.all()[1].file_name), 'rb') as f: reader = csv.reader(f.read().decode('utf-8')) for row in reader: print(row) However the row is getting printed with each word on a different line ['U'] ['s'] ['e'] ['r'] ['n'] ['a'] ['m'] ['e'] ['', ''] [' '] ['N'] ['a'] ['m'] ['e'] How am I supposed to fix this? -
Add urls to django rest swagger
I have a django rest swagger In urls.py I have something like this router = routers.DefaultRouter() router.register('', ProductListView, basename='product-list') schema_view = get_swagger_view(title="Star Shop") urlpatterns = [ path('admin/', admin.site.urls), path('api/', schema_view), path('api/', include(router.urls)) ] I'm trying to include in swagger API for products Can someone help me please -
What are the best practices to consume Kafka messages in Django
I am working on an IoT project that uses MQTT protocol to transport the sensor data from embedded devices to an App. For this i have created, A MQTT broker to send the data from the device. A custom bridge that push data from MQTT broker to my Kafka broker Django server to push the messages via websocket to the App Right now, What i need is to consume the Kafka messages from django, save to the DB and then push this data to client via websockets. But i don't have much idea regarding how to consume Kafka messages from Django. So far the solution in my mind is using custom management command, start a kafka consumer, push the data to DB and then to websockets. Is this a good approach? If not, what would be a good solution to solve this? -
HTMLButtonElement.onclick not working django
I am new to django. And I encountered an error. There are two button in a form one as submit functionality and other has onclick(to claculate values and display it in one of the input). but the onclick="fare()" not working where as static folder is linked. Please help how to call the function this is what I am getting in console Do I have to write same login in python? help me with the best way. -
How to create a queue for each of the django applications?
My project consists of three applications, amocrm, vk, tg. Everyone needs to add their turn. But I don't understand how it works. This is necessary because each of the queues in these applications will be to avoid exceeding the limit of requests to services, and some long-running tasks. If everything is sent to 1 queue, I lose a lot in performance and speed Django 4.0.2, Celery 5.2.3, RabbitMQ 3.9.13 -
How to fix Django Summernote using relative path for src url in image integration?
I am new to the Django framework, and inherited a projet which I am trying to fix. Right now my project runs in a docker at url localhost:8000 until deployment in on a remote server. I have the django-summernote extension installed for fancy text editing and image integration, but it doesn't work as expected: Summernote Editor in Django admin works fine, and correctly displays uploaded images But on my content pages, the html integration of my provides an incorrect src url (which return an error ofc) src="/media/django-summernote/2022-02-27/90a1f1ec-ed16-4cc2-a9f8-b0bb30ea4ab8.png" The expected html integration should be : src="http://localhost:8000/media/django-summernote/2022-02-27/90a1f1ec-ed16-4cc2-a9f8-b0bb30ea4ab8.png" I checked and the image file does exist in the folder, the expected url below does actually shows the picture alright as well. The rest of the website uses images integration just fine when not related to summernote. I figure this has something to do with settings.py or even router (which tbh is still a bit complex in my head). settings.py MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py urlpatterns = [ ... path("summernote/", include("django_summernote.urls")), ] -
Is there a way to put JSON data to django models?
So what I want to do here is that take a CSV file as input from an HTML form, then convert the CSV to JSON and put the JSON values into a Django model. Is there a way to do this? Any help would be appreciated. Thank you in advance! -
Default permissions for files that are automatically created in a Linux directory
I have a problem with an application developed in python using the django framework, it uses the FPDF library to export a file which is then used by the application to attach it to an automated email. When this app exports the PDF and saves it to the media directory, the file doesn't inherit permissions from its parent directory and only has read/write permissions, this doesn't allow Django to find the file so it can be attached to the mail. I was searching on the internet and found people with the same problem, they were recommended to use the ACL configuration to manage default permissions, I tried many times with different methods but it did not work. I don't know what I could have done wrong (I kept having the same error). Dfter having made the ACL configuration the files continued to be exported with the same permissions and when applying the command chmod 777 -R * these did not change their permissions, I had to disable the ACL configuration for it to allow me to apply that command. This is the error that appears: Internal Server Error: /treasury/sendMailsSupplierView/SBOJOZF Traceback (most recent call last): File "/var/www/johannasenvironment/venvjoh/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner … -
python Django returing <WSGIRequest: GET'> instead of data
I some have trouble representing API data to my templates. Some info: The API data is send to context_processors.py in my app dir. from ttn.context_processors import my_function while True: my_function(SomeClass().return_data()) time.sleep(5) and here is my context_processors funtion: def my_function(complex_data): all_data = complex_data return {'data': all_data} complex_data looks like: {0:{}, 1{}} etc.. Here is where I want to represent the data in my base.html: <div class="div-side"> {% if data %} <p>{{data}}</p> # this one return wsgirequest: get /myapp/ <ul> {% for dicts in data %} <li>dicts</li> # just for test {% for d in dicts %} <li>{{ d.name }} <span>{{d.someDigit|floatformat:'2'}}</span> <span>{{d.somePercent|floatformat:'2' }} %</span> </li> {% endfor %} </ul> {% endfor %} {%else%} <p>no info</p> {%endif%} </div> My views which render to base.html: def home_page(request): a = len(get_news_objects()) return render(request, 'base.html', {'a': a} ) Basically I'm not able to represent my data at my .html page because context_processors.py, returns this "wsgirequest: get /myapp/". What am I missing? How can I send the data instead of wsgirequest: get /myapp/ ? From my settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'project.context_processors.my_function', # ], }, }, ] -
nuxtjs auth not calling server after successful login
I'm trying to set up social logins with nuxt and django, as far as I understand it works like this: user clicks on "login with google" google returns a code nuxt calls a view on my server and sends that code the server sends the code to google which responds with the user info my server registers the user (or logs him in), generates a token and sends it back to nuxt nuxt authenticates the user I can see the google login page properly, I can click on my account, but then my local nuxt page refreshes and I don't see any request being made to my server. Is my understanding of the flow wrong? Here's my setup in nuxt: google: { clientId: '<secret_key>', codeChallengeMethod: '', responseType: 'code', redirectUri: 'http://localhost:3000/', endpoints: { token: 'social-login/google/', // some backend url to resolve your auth with google and give you the token back userInfo: 'user-info/' // the endpoint to get the user info after you received the token }, } And I'm trying to login with: this.$auth.loginWith('google') EDIT: if it helps, I'm trying to follow this guide: https://medium.com/swlh/how-to-build-google-social-login-in-django-rest-framework-and-nuxt-auth-and-refresh-its-jwt-token-752601d7a6f3 -
Is there any way to get back to a page from which it was redirected to in django?
Detailed Explanation: Suppose there is an html page in django named as Page 1 and the other one as Page 2 which is a login page. Now there is a button on both of these pages. The button on Page 1 redirects to the page for login. Is there any way to get back to that page from where this page i.e. Page 2 is redirected from? Please Note: The login page i.e. the Page 2 is simply redirected to a Account.html page, I want to set a condition so that it will redirect back to previous page, i.e., from where the Page 2 was redirected from. -
table diagnostic_patient has no column named test_id
I tried to post multiple instance in one post request.But got this error table diagnostic_patient has no column named test_id.From selected key the id will save into test_id column and name will be save in test_name column. models.py class Test(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=0) def __str__(self): return self.name class Patient(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length = 254) age = models.DecimalField(max_digits=6, decimal_places=0) gender = models.CharField(max_length=100) phone = models.DecimalField(max_digits=6, decimal_places=0) test_id = models.IntegerField() test_name = models.CharField(max_length=100) t = models.ForeignKey(Test, on_delete=models.CASCADE, related_name='selected') total_price = models.DecimalField(max_digits=6, decimal_places=0) advance = models.DecimalField(max_digits=6, decimal_places=0) due = models.DecimalField(max_digits=6, decimal_places=0) role = models.CharField(max_length=100,default='Patient') serializers.py class TestSerializer(serializers.ModelSerializer): class Meta: model = Test fields = ['id', 'name','price'] class PatientSerializer(serializers.ModelSerializer): selected = TestSerializer(many=True) class Meta: model = Patient fields = ['name', 'email', 'age', 'gender', 'phone', 'selected', 'total_price', 'advance', 'due', 'role'] def create(self, validated_data): tracks_data = validated_data.pop('selected') a = Patient.objects.create(**validated_data) for track_data in tracks_data: Patient.objects.create(**track_data) return a json post data: { "name":"df", "email":"d@gmail.com", "age":"21", "gender":"Male", "phone":"234", "total_price":86, "advance":0, "due":86, "selected":[ {"id":8,"name":"sdf","price":34}, {"id":9,"name":"dg","price":52} ] } -
Remove HTML tags in Django messages
Basically I have a view with Django where I add some messages like this: from django.contrib import messages def myView(request): #some stuff messages.error(request, "My message here") return render(request, "myApp/myTemplate.html", context = data) And then I print them in the template like this: {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif %} But the problem is that the messages framework is adding HTML tags to the message and when the message is printed, the <ul> and <li> tags are added. So after the template is rendered it looks like this: <div><ul class="errorlist"><li>My message here</li></ul></div> I would like to know if there is a way to avoid the message getting these html tags added. Also, I would need it outside of the template too, so in the unit tests I can do something similar to: messages = list(response.context["messages"]) self.assertEquals(len(messages), 1) self.assertEquals(str(messages[0]), 'My message here') Is there any way to achieve this? Currently using Python3 and Django 4 Note that I would like to completely avoid the framework to add the tags, so I do not need to use striptags filter. -
Django Can't access URL Pk from FormView Class
I am putting together a simple medical-related project that includes allowing user to order lab tests on a patient. From the patient screen they select Order Tests. The UrlPattern, which includes the Patient pk, brings up the OrderTestsView which is a FormView. The kwargs in this view have no pk even though it is in the Url. I use a FormView because I need to access the list of tests selected in the Forms MultipleModelsChoice. But I need the patient information before the Order form is selected because I have to display who the patient is at the top of the order screen. Normally I would use get_context_data to do all of this, but the kwargs are blank. Not sure why FormView ignores the pk parameter, but how do I fix this? urls.py path('order-tests/<pk>/', OrderTestsView.as_view(), name='order-tests'), forms.py class TestOrderForm(forms.Form): choice = forms.ModelMultipleChoiceField(Universal_Test_File.objects.all().order_by('test_name'), to_field_name="service_id") view.py class OrderTestsView(FormView): model = Universal_Test_File form_class = TestOrderForm success_url = '/list_tests/' template_name = "lab/order_tests.html" patient = get_object_or_404(Patient, pk) ***## CANNOT ACCESS PK*** def form_valid(self, form): choice = form.cleaned_data.get("choice") if choice: for test in choice: print(test.service_id, test.test_name) -
MultiValueDictKeyError at /authors/postform/
i have bulit a books management app in django-rest framework with UI in html css and bootstrap. But when i'm trying to add new authors to the database doing a post request i'm getting this multivalue dict error even though i checked the name in the form. traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/authors/postform/ Django Version: 3.2.9 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'genebox', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) During handling of the above exception ('Name'), another exception occurred: File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Online Test\GeneBOX full stack (27th)\myproject\genebox\views.py", line 58, in author_save name = request.POST['Name'] File "C:\Python39\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /authors/postform/ Exception Value: 'Name' ```urls.py``` urlpatterns = [ path('', views.home, name='home'), path('authors/', views.Author_list, name='all_author'), path('authors/postform/', views.author_save, name='authsave'), path('books/', views.Book_list, name='all_books'), path('authorcsv/', views.author_csv, name='author_csv'), path('bookcsv/', views.book_csv, name='book_csv') ] models.py class Authors(models.Model): Gender_choice = ( ('M', 'Male'), ('F', 'Female'), ('Other', 'Others'), ) Name = models.CharField(max_length=70) Age = models.IntegerField() Gender = models.CharField(max_length=20, choices=Gender_choice) Country … -
getting AttributeError 'str' object has no attribute 'data' when makinh request to Django-based Server from Flutter application
Hello fellow developers! I am trying to make a request to my Django-based server. lets first look at the endpoints that are causing trouble url.py path("getBookings/<str:Role>/<str:id>/", views.getBookings), path("archiveBooking/<str:Role>/<str:id>/", views.archiveBooking), these endpoints work fine when I make a request to them via localhost i.e. when I run the server with python manage.py runserver they also work fine when I try to make a request via my heroku-deployed application. But when I try to make a request via flutter, the following error shows up, I/flutter (10506): Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] I/flutter (10506): Server time: Sun, 27 Feb 2022 12:53:22 +0000 I/flutter (10506): Installed Applications: I/flutter (10506): ['django.contrib.admin', I/flutter (10506): 'django.contrib.auth', I/flutter (10506): 'django.contrib.contenttypes', I/flutter (10506): 'django.contrib.sessions', I/flutter (10506): 'django.contrib.messages', I/flutter (10506): 'django.contrib.staticfiles', I/flutter (10506): 'fyp_api.apps.FypApiConfig', I/flutter (10506): 'rest_framework'] I/flutter (10506): Installed Middleware: I/flutter (10506): ('whitenoise.middleware.WhiteNoiseMiddleware', I/flutter (10506): 'django.middleware.security.SecurityMiddleware', I/flutter (10506): 'django.contrib.sessions.middleware.SessionMiddleware', I/flutter (10506): 'django.middleware.common.CommonMiddleware', I/flutter (10506): ' here is my views.py code for the two concerned endpoints: @api_view(['GET']) def getBookings(request, Role, id): #Data = request.data #Role = Data['role'] #Role = request.META.get('HTTP_ROLE') BSerializer = '' if(Role == 'expert'): try: #eID = Data['eID'] eID = id #eID = request.META.get('HTTP_EID') expertExists = Experts.objects.filter(expertID = eID).exists() if(expertExists): exp = Experts.objects.get(expertID = eID) … -
SQL - How do I create a linkage table?
I'm building the following data model in Django / SQL Table 1 (Entity) - things that can do things Entity ID: Enum: (Person, or Business) Table 2 (Person) Entity ID: Person ID: Firstname Lastname Table 3 (Ltd Co.) Entity ID: Ltd Co. ID: Company Name Company No. I'm trying to link a Person, who has a Limited Co., with an Agent (who is also a Person) that also has a Limited Co. So 4 different entitites, two of which are type Person, and two of which are type Limited Co. Do I need another Linkage Table? E.g. Profile Person Profile Ltd Co Agent Person Agent Ltd Co Entity 1: Type Person Entity 3: Type Business Entity 2: Type Person Entity 4: Type Business Q. How do I create this Linkage Table in a Django Model / or SQL? Q. Is a Linkage Table the right approach? -
Django form buttons
I have an order form that should display product sizes as buttons, but the buttons do not register to be selected unless a user clicks exactly on the letter for the size ('S', 'M', etc.) in the exact center of the button. Clicking the space between the letter and the border of the button marks it as selected, but when you click Add to cart, it deselects itself. class OrderForm(forms.Form): def __init__(self, instance, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.instance = instance self.fields['size'] = forms.ModelChoiceField( queryset=self.instance.sizes.all(), widget=forms.RadioSelect()) The HTML is as follows: {% for choice in order_form.size %} <button type="button" class="size-btn">{{ choice }}</button> {% endfor %} Sizes is a simple model: class Size(models.Model): size = models.CharField(max_length=10) def __str__(self): return self.size This way the rendered HTML is a mess: <button type="button" class="size-btn"> <label for="id_size_0"> <input type="radio" name="size" value="2" id="id_size_0" required>S </label> </button> How do I fix the buttons so that they get selected even if clicked outside of the very center, in the size letter? Thanks. -
(mismatching_state) CSRF Warning! State not equal in request and response in django and google-api
I'm creating a web page in django which uses google api in order to send a pdf file to google drive. Everything was working perfectly on my local machine but as soon as i put it on production i got an error ((mismatching_state) CSRF Warning! State not equal in request and response.) as you can see down below. Here is the function which sends the request: def send_drive(file_name, file_path): CLIENT_SECRET_FILE = '/home/djuka/reusabletechnologies/project_app/reBankMini/reBankMiniApp/client_secret_156600557463-8e2qka5c4t646t7t4ksmbluo3aovv4q6.apps.googleusercontent.com.json' API_NAME = 'drive' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/drive'] service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) # Upload a file file_metadata = { 'name': file_name, 'parents': ['1WpY7cw3S5RAPvCfFyPMDkw0I3vIZfQ_c'] } media_content = MediaFileUpload(file_path, mimetype='application/pdf') file = service.files().create( body=file_metadata, media_body=media_content ).execute() print(file) And Create_Service() function is in Google.py: import pickle import os from google_auth_oauthlib.flow import Flow, InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload from google.auth.transport.requests import Request from datetime import datetime def Create_Service(client_secret_file, api_name, api_version, *scopes): print(client_secret_file, api_name, api_version, scopes, sep='-') CLIENT_SECRET_FILE = client_secret_file API_SERVICE_NAME = api_name API_VERSION = api_version SCOPES = [scope for scope in scopes[0]] print(SCOPES) cred = None pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle' # print(pickle_file) if os.path.exists(pickle_file): with open(pickle_file, 'rb') as token: cred = pickle.load(token) if not cred or not cred.valid: if cred and cred.expired and cred.refresh_token: cred.refresh(Request()) … -
How to get exact value of choice field in django
I have a choice field in Django model ) COMMITTEE_STATUS = ( ("p", "Pending"), ("a", "Active"), ("c", "Completed"), ) but the issue is when I am accessing these data in template I am getting p,a and c instead of actual peening, active and complete -
Finding api documentation flask
Have been given the task to ID all APIs in the source code since the previous dev was fired immediately..now i know that flask or django have certain templates to define API and specify parameters so i intend to write a script to simply look for such patterns , recursively across folders ..is the community aware of any tools / projects which do this across programming languages.. please nite, iam NOT speaking of swagger or api documentation..this tool NEEDs to be able to scan through code and generate necessary API docs -
Cannot assign "<User: Euler>": "Article.authorr" must be a "User" instance
I want to change the model field from the charfield to the user's forignkey And I do not want my information to be deleted First I added the fields, then I transferred the data, then I deleted the previous fields def change_names_of_field(apps, schema_editor): Article = apps.get_model('blog', 'Article') article = Article.objects.all() for s in article: **s.authorr = User.objects.get(username=s.author)** if Category.objects.filter(title=s.category).values_list("title", flat=True) == []: Category.objects.create(title=s.category) s.categoryy = Category.objects.filter(title=s.category) s.update = s.created s.published = s.created s.status = "p" s.save() class Migration(migrations.Migration): dependencies = [ ('blog', '0002_alter_article_created'), ] operations = [ migrations.AddField( model_name='Article', name='authorr', field=models.ForeignKey(User,on_delete=models.CASCADE,null=True), preserve_default=False, ), ... ... ... migrations.RunPython( change_names_of_field, ), ... ... ... -
bad request in django when unity send it but its OK when is use postman
I develop a service for our online games. when I'm testing by Postman everything is OK but when I'm tried test by end-user application djago send Bad_request 400 40. what happened ?! -
How to create ManyToMany object in django view?
I am trying to create product api. Here I have delivery_option filed which has a manytomamy relation with my product. when I am trying to create product I am getting some error like TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use delivery_option.set() instead. How to create the many to many field in django? @api_view(['POST']) @permission_classes([IsVendor]) def vendorCreateProduct(request): data = request.data user = request.user.vendor print(data['deliveryOption']) product = Product.objects.create( user=user, name=data['name'], old_price = data['price'], discount = data['discount'], image = data['avatar'], countInStock = data['countInStock'], subcategory = Subcategory.objects.get_or_create(name=data['subcategory'])[0], description=data['description'], delivery_option = data['deliveryOption'], ) serializer = ProductSerializer(product, many=False) return Response(serializer.data)