Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to extract the non gridded table from the scanned documents using Python/Django?
I wanted to extract data from scanned documents containing non-gridded tables are there any ideas and source codes that can help me? here is an example of input document -
Add new item in many to many field via api in Django
I'm calling an API to update the my liked_products many to many model in Django but, when calling the prod ID to add the item to the list, I get the error: AttributeError at /api/customer/like_product/ 'ReturnDict' object has no attribute 'liked_products' Here is my API: @csrf_exempt def updated_liked_products(request): customer = get_user(request) if not customer: return JsonResponse({'invalid token'}) customer_details = CustomerDetailSerializer(CustomerDetails.objects.get( customer=customer)).data customer_details.liked_products.add(request.data['prodId']) customer_details.save() return JsonResponse({"success": 'updated'}) Customer Details Model: age = models.IntegerField(default="21", blank=True) address = models.CharField( default='', max_length=254, null=True, blank=True) nick_name = models.CharField( default='', max_length=254, blank=True) average_order = models.FloatField(default="0.0", blank=True) completed_orders = models.IntegerField(default="0", blank=True) customer = models.ForeignKey( Customer, on_delete=models.CASCADE) customer_type = MultiSelectField( choices=CUSTYPE, default=CUSTYPE, max_length=100) current_selfie = models.ImageField( upload_to='sefies/', blank=True, default='') email_confirmed = models.BooleanField(default=False) last_signin = models.DateTimeField(default=timezone.now) liked_products = models.ManyToManyField('Product') needs_help_with = MultiSelectField( choices=CATEGORIES, max_length=1000, default='') phone = models.CharField( I am using Postman to update the data like this so I can see the liked product field but, cannot access it.: -
how to customize field number in jquery.formset django
hi i built an app for a mobile store , each single IMEI has its unique IMEI , i want to entry IMEI's while i add mobiles class Mobile(models.Model): mobile = models.CharField(max_length=50,unique=True) class MobileStorage(models.Model): mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Imei(models.Model): imei = models.CharField(max_length=50,verbose_name='IMEI',unique=True) mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) whenever i add a new MobileStorage for example quantity =15 , then they have 15 unique IMEIs , i need to generate 15 fields instead of increasing fields manually ? class MobileStorageForm(forms.ModelForm): mobile = forms.ModelChoiceField(queryset=Mobile.objects.all(),empty_label='mobiles') class Meta: model = MobileStorage fields = [ 'mobile','quantity' ] class ImeiForm(forms.ModelForm): class Meta: model = Imei fields = ['imei'] MobileStorageInlineFormSet = inlineformset_factory( MobileStorage,Imei,form=ImeiForm,fields=('imei'),extra=1,can_delete=False ) <script> $(function(){ $('.tb1 tr:last').formset({ prefix:'{{imei.prefix}}', addText:'add', addCssClass:'btn btn-success', deleteText:'delete', deleteCssClass:'delete-row btn btn-danger' }) }) </script> i know i should change jquery.formset.js but i dont know how todo it ? for example {{form.quantity | add_class:'form-control' | attr:'id:quantity'}} in my template provide id:quantity then generate the number of quantities fields ?!thanks for your advice -
Django Queryset : How to print second value in queryset?
I'd like to print only second value in queryset. please refer below code. views.py: def all_chatroom(request, user_obj): current_user = user_obj conversations = models.Conversation.objects.filter(participants=user_obj) return render( request, "conversations/all.html", {"conversations": conversations, "current_user": current_user}, ) templates>all.html: {% extends "partials/base.html" %} {% block page_name %} 메세지 목록 {% endblock page_name %} {% block content %} <div class="container"> {% for conversation in conversations %} <div class="border"> {{conversation.participants.all}} </div> {% endfor %} </div> {% endblock content %} and the printing value for the template is <QuerySet [<User: master>, <User: test1>]> <QuerySet [<User: master>, <User: test2>]> for this example, I want to print test1 and test2. how can I print only second value in queryset? please kindly help me. -
Django Rest - How to retreive more than one record from API and pass all of them to loop though in template?
Most of tutorials that I found was about creating APIs and not about using existing ones. I know that I am missing some huge, crucial thing. Could you please point me to it? I want to receive from OMDB API several hits after posting title to search. My current code in views.py looks like this: class MoviesList(APIView): def get(self, APIView): movies = Movie.objects.all() serializer = MovieSerializer(movies, many=True) return Response(serializer.data) def post(self, request): title = request.POST.get("Title") api_key = "111111" url = f"http://www.omdbapi.com/?t={title}&type=movie&apikey={api_key}" response = requests.get(url) serializer = MovieSerializer(data=response.json()) if serializer.is_valid(): serializer.save() movie_details = { 'title': response.json()['Title'], 'genre': response.json()['Genre'], 'plot': response.json()['Plot'], 'year': response.json()['Year'], 'runtime': response.json()['Runtime'], } return render(request, 'movie_database/results.html', movie_details) else: print(serializer.errors) print("Something went wrong.") And it is working. With this code I receive one result and I can pass that to my template. And use values like "title" and "genre". But I know that by changing in "url" t={title} to s={title} I can receive 10 results (I tested it in browser by hand and it is working). How I can utilize that and loop through them in my template? After looking for over 1 hour for answer I know that my basic approach is wrong but I am unable to find … -
Django models: 'ModelFormOptions' object has no attribute 'private_fields'
Even though in the class based view fields = '__all__'. I'm still getting this error FULL CODE forms.py class UploadAlbum(forms.ModelForm): musicFiles = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Album exclude = ('music','date',) views.py class Rcollection(LoginRequiredMixin,CreateView): model = UploadAlbum template_name = 'release/collection.html' fields = '__all__' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. print(form) return super(Rcollection, self).form_valid(form) FULL STACKTRACE kingsley@Number2-Ubuntu:~/Documents/RedRiver$ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 11, 2020 - 15:43:21 Django version 3.0.7, using settings 'RedRiver.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /app/creator/release/rcollection/ Traceback (most recent call last): File "/home/kingsley/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/kingsley/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/kingsley/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kingsley/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/kingsley/.local/lib/python3.6/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "/home/kingsley/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/kingsley/.local/lib/python3.6/site-packages/django/views/generic/edit.py", line 168, in get return super().get(request, *args, **kwargs) File "/home/kingsley/.local/lib/python3.6/site-packages/django/views/generic/edit.py", line 133, in get return self.render_to_response(self.get_context_data()) File … -
Error during template rendering.Invalid filter: 'bootstrap'
I'm using django3.0 with ubuntu20.04 os.I created a job portal project but when I run my code. it gives an error like- Invalid filter: 'bootstrap' here code is given below- templates/accounts/login.html:- {% extends 'base.html' %} {% load static %} {% load bootstrap %} {% block content %} <section class="home-section section-hero inner-page overlay bg-image" style="background-image: url('images/hero_1.jpg');" id="home-section"> <div class="container"> <div class="row align-items-center justify-content-center"> <div class="col-md-12"> <div class="mb-5 text-center"> <h2 class="text-white font-weight-bold">LOGIN</h2> </div> </div> </div> </div> </section> <section class="site-section" id="next-section"> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-5 mb-5 mb-lg-0"> <p>Already have your account?</p> <form action="" method="POST">{% csrf_token %} {{ form|bootstrap }} <div class="row form-group"> <div class="col-md-12"> <input type="submit" value="Login" class="btn btn-primary btn-md text-white"> </div> </div> </form> </div> </div> </div> </section> <section class="py-5 bg-image overlay-primary fixed overlay"> <div class="container"> <div class="row align-items-center"> <div class="col-md-8"> <h2 class="text-white">Looking For A Job?</h2> <p class="mb-0 text-white lead"> Lorem ipsum dolor sit amet consectetur rebates the times of the win impedes.</p> </p> </div> <div class="col-md-3 ml-auto"> <a href="{% url 'accounts:signup' %}" class="btn btn-warning btn-block btn-lg">Sign Up</a> </div> </div> </div> </section> {% endblock %} Invalid filter: 'bootstrap' {{ form|bootstrap }} settings.py:- import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development … -
TinyMCE HTMLField and Django TextField don't show up in production
When I visit my Modelform in the admin all of the fiels are shown just fine. However, once I go to the admin on my web-app in production, both the HTMLField and textfield doesn't show any inputfields. If it would just be the TinyMCE HTMLField it would be less confusing, but having the common TextField bugged as well is weird. What do I miss? forms.py from django import forms from tinymce import TinyMCE from django.contrib.admin.widgets import AdminDateWidget from .models import Post, Comment class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class PostForm(forms.ModelForm): # Add Tiny MCE Widget to Admin Interface content = forms.CharField( widget=TinyMCEWidget( attrs={'required': False, 'cols': 30, 'rows': 10} ) ), # Add DateTime Picker Widget to Admin Interface publish_date = forms.DateField(widget=AdminDateWidget()) class Meta: model = Post fields = ('title', 'overview', 'content', 'thumbnail', 'categories', 'publish_date') models.py from django.db import models from django.contrib.auth import get_user_model from tinymce.models import HTMLField # Post Model class Post(models.Model): title = models.CharField(max_length=28, blank=False) stock_name = models.CharField(max_length=35, blank=False) stock_website = models.CharField(max_length=60, blank=False) overview = models.TextField(max_length=140, blank=False) # doesn't show up in production content = HTMLField() # doesn't show up in production [...] This is how it looks like in Production: vs development having the very same code … -
Django: admin site showing logs
i written a configuration in my project to log some actions and i can show it on some url in HTTPResponse can you suggest me a way to show this logs in Django-admin site with adding some extra html pages and adding extra with urls in the admin site. import os LOGGING ={ 'version':1, 'loggers':{ 'django':{ 'handlers':['file','file2', 'file3'], 'level':'DEBUG', 'filters': ['request'] } }, 'handlers':{ 'file':{ 'level':'INFO', 'class': 'logging.FileHandler', 'filters': ['request'], 'filename':'./logs/infologs.log', 'formatter':'simpleRe', }, 'file2':{ 'level':'DEBUG', 'class': 'logging.FileHandler', 'filename':'./logs/debuglogs.log', 'formatter':'simpleRe', }, 'console':{ 'level' : 'INFO', 'class': 'logging.StreamHandler', 'filters': ['request'], 'formatter':'request_format', }, 'file3':{ 'level':'WARNING', 'class': 'logging.FileHandler', 'filters': ['request'], 'filename':'./logs/warlogs.log', 'formatter':'simpleRe', }, }, 'formatters':{ 'simpleRe': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'request_format': { 'format': '%(remote_addr)s %(username)s "%(request_method)s ' '%(path_info)s %(server_protocol)s" %(http_user_agent)s ' '%(message)s %(asctime)s', }, } }``` -
Clicking the page number in the search results list causes an error
An error occurred when clicking the page number below the list displayed as a result of the list view. Perhaps the pagination setting is wrong? Or is it a template problem? I tried to investigate various causes, but could not find the cause Because I still don't understand the class view properly It doesn't seem to solve this simple problem. I would be very grateful if someone could tell me the cause and solution of this Perhaps it's wrong to customize get_queryset to display the search results for a list view with the pagination option set? thanks for let me know list view class go_to_skil_note_search_page(LoginRequiredMixin,ListView): model = MyShortCut paginate_by = 10 def get_template_names(self): return ['wm/myshortcut_list_for_search2.html'] def get_queryset(self): print("go_to_skil_note_search_page excute check :::::::::::::::::::::::::") query = self.request.GET.get('q') print("query ::::::::::::::: ", query) if(query != None): print("user list check :::::::::::::::::::::::::") object_list = MyShortCut.objects.filter(Q(author=self.request.user) & Q(title__contains=query) | Q(filename__contains=query) | Q(content1__contains=query) | Q(content2__contains=query)).order_by('created'); print("result : ", object_list) return object_list else: qs = MyShortCut.objects.all()[:10] return qs template {% extends "layout.html" %} {% load staticfiles %} {% load bootstrap4 %} {%block title %}Search Note{% endblock %} {%block extra_css %} {% endblock %} {%block content4 %} <br><hr> <table class="table table-bordered"> <tr> <td width=""> <br> <div class="container"> <div class="row"> <div class="col"> … -
Error while sending data to freelancer.pk using sdk . Below is the error in djando python server
Traceback (most recent call last): File "C:\Users\talha.virtualenvs\freelancerWeb\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\talha.virtualenvs\freelancerWeb\lib\site-packages\django\utils\deprecation.py", line 96, in call response = self.process_response(request, response) File "C:\Users\talha.virtualenvs\freelancerWeb\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /extract_list.htmlenter code here Exception Value: 'Bid' object has no attribute 'get' -
Why does my model migration not reflect any changes in production?
I deployed my web-app on Digitalocean and use PyCharm to code and update the project remotely. In my PyCharm terminal I connected to my server and run makemirgations + migrate respectively. When I now visit my admin in production and check the according form, the model migrations are not reflected. What do I miss? Remote PyCharm terminal root@ubuntu-s-1vcpu-1gb-fra1-01:/home/jonas/blog source env/bin/activate (env) root@ubuntu-s-1vcpu-1gb-fra1-01:/home/jonas/blog cd stocksphere (env) root@ubuntu-s-1vcpu-1gb-fra1-01:/home/jonas/blog/stocksphere python manage.py makemigrations Migrations for 'blog': blog/migrations/0002_auto_20200711_1439.py - Alter field coverage on author - Alter field education on author - Alter field profile on author - Alter field profile_picture on author (env) root@ubuntu-s-1vcpu-1gb-fra1-01:/home/jonas/blog/stocksphere# python manage.py migrate Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions Running migrations: Applying blog.0002_auto_20200711_1439... OK blog/migrations.py on the production server: # Generated by Django 3.0.8 on 2020-07-11 14:39 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ] operations = [ migrations.AlterField( model_name='author', name='coverage', field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='blog.Category'), ), migrations.AlterField( model_name='author', name='education', field=models.CharField(blank=True, max_length=200), ), migrations.AlterField( model_name='author', name='profile', field=models.CharField(blank=True, max_length=500), ), migrations.AlterField( model_name='author', name='profile_picture', field=models.ImageField(blank=True, upload_to=''), ), ] But still the model fields require to be blank=False when I go to www.mysite.com/admin: -
Alpha Vantage API with Django - Parsing data
I'm building some sort of Stock Market Web App using django framework. I'm getting the data from Alpha Vantage API and I got stuck when parsing the data I need. 1 - I can successfully call the API but I always get an error when trying to get the data I need see the code I'm using on views.py: def home(request): import requests import json import pandas as pd from alpha_vantage.timeseries import TimeSeries url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=B3SA3.SA&outputsize=compact&apikey=XXX" api_request = requests.post("GET", url) try: api = api_request.content.json() except Exception as e: api="Erro, tente novamente" return render(request,'home.html', {'api': api}) On home.html I'm using this code to whether show the info or an error: {% if api %} {% if api == "Erro, tente novamente."%} Houve um problema com a busca da ação, tente novamente. {% else %} {% for key,value in api.items %} {{key}}: {{value}}<br/> {%endfor%} {% endif %} {% endif %} With this code, I get the following and as you can see there are two separate dictionaries Meta Data and Time Series (Daily): {'Meta Data': {'1. Information': 'Daily Time Series with Splits and Dividend Events', '2. Symbol': 'B3SA3.SA', '3. Last Refreshed': '2020-07-10', '4. Output Size': 'Compact', '5. Time Zone': 'US/Eastern'}, 'Time Series … -
Editing models.py file and migrating changes to database in the same python code
I am looking to edit a models.py file for an app, and then migrate the changes to the database (postgreSQL) in the same python code. In the view definition that is supposed to perform this, I am doing the following: Open models.py Append the new table's model to the existing models Close models.py Run makemigrations Run sqlmigrate Run migrate It works fine up to Step no.5. I can see the migration files being created under the app's migrations folder, but when it is time to migrate the changes to the database, I get this: Operations to perform: Apply all migrations: admin, auth, contenttypes, portfolio, sessions, travello Running migrations: No migrations to apply. I tried running the migrate command (python manage.py migrate) from the command line too, gives the same error. -
Getting Django models help_texts in a React App
I'm building a SPA with Django / DRF for the backend and React / material-ui for the frontend. I'm using Django models help_texts in the DRF APIs. Some directly from the models, others overrided in the serializers. What would be a DRY method to get the help_texts in the React App? I can imagine: Having the help_texts in (json) files being loaded in Django on one side and in React in the frontend. Having an extractor that would extract the help_texts from Django serializers when building the App that would be reused in the React App. Need then to define a proper mapping of the various help_texts in React. Other methods suggested? Thanks for your suggestions! -
Why does FileField save a None value as a blank string and not Null?
I have a model that uses a FileField: class MyModel(models.Model): title = models.CharField(null=True) file = models.FileField(null=True) If I create a model with file=None, this doesn't show up in the queryset (db is postgresql): MyModel.objects.create(title=None, file=None) qs = MyModel.objects.filter(file=None) returns <QuerySet []> It seems that the FileField is saving a None value as a blank string in the database ('') as the row contains (1, null, ,). For example, MyModel.objects.filter(file='') will return the object. What's going on here? Is this by design, or is it an error in my code or Django? If it's by design, what is the rationale for saving a null value as a blank string. This seems to be an antipattern? -
PostgreSQL commands not working in virtualenv
I want to use PostgreSQL as my database in my Django project(my os is windows). I can't run PostgreSQL's commands in the command prompt while venv is activated and out of venv I have access to those commands because I've added PostgreSQL bin directory path to the PATH environmental variable. How can I do this with virtualenv so I can run those commands? Thank you. -
Correct way of using elasticsearch with DRF
I am using a test example of elastic search here the link of docs https://django-elasticsearch-dsl-drf.readthedocs.io/en/0.1.8/quick_start.html with django rest. I did the same as the docs did but it is not working on the case of mine. In addition, in the docs run the server on 8000 port if I am running the server with this port Connection error failed error throws but If I run on 9200 port it works but it returns 404 in the image shown below here is my code: book.py @BOOK_INDEX.doc_type @registry.register_document class BookDocument(Document): """Book Elasticsearch document.""" id = fields.IntegerField(attr='id') title = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField( analyzer='keyword' ) } ) description = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField( analyzer='keyword' ) } ) summary = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField( analyzer='keyword' ) } ) publisher = fields.TextField( attr='publisher_indexing', analyzer=html_strip, fields={ 'raw': fields.TextField( analyzer='keyword' ) } ) publication_date = fields.DateField() state = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField( analyzer='keyword' ) } ) isbn = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField( analyzer='keyword' ) } ) price = fields.FloatField() pages = fields.IntegerField() stock_count = fields.IntegerField() tags = fields.TextField( attr='tags_indexing', analyzer=html_strip, fields={ 'raw': fields.TextField( analyzer='keyword', multi=True ) }, multi=True ) class Django: """Meta options.""" model = Book # The model associate with this … -
DJANGO - reverse accessor for profile.user clashes with reverse accessor for same field?
I am getting the following error: dsapi.Profile.user: (fields.E304) Reverse accessor for 'Profile.user' clashes with reverse accessor for 'Profile.user'. HINT: Add or change a related_name argument to the definition for 'Profile.user' or 'Profile.user'. dsapi.Profile.user: (fields.E305) Reverse query name for 'Profile.user' clashes with reverse query name for 'Profile.user'. All of my research has shown to create a related_name for each of the issues. But in my case, it's telling me that the reverse accessor has an issue with itself. Does anyone have any thoughts here? Below is the problematic code in my models.py file. import uuid from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class DsapiModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) class Meta: abstract = True class Profile(DsapiModel): """ Extend User model using one-to-one link Save a query using users = User.objects.all().select_related('profile') """ user = models.OneToOneField(User, on_delete=models.CASCADE) favorite_sites = models.ManyToManyField(Site) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
AttributeError on successful redirection in django?
Redirection on successful POST request. def product_page_view(request, prod_slug, color=None, size=None): ... ... prod = Product.objects.filter(slug=prod_slug).first() seller = prod.seller ... .... order_form = Buy_now_form() if request.method == "POST": order_form = Buy_now_form(request.POST) if order_form.is_valid(): # Function for processing POST request and return order order = buy_now_view(request, prod.slug, color, size) # Redirection return redirect(reverse('product-shipping', kwargs={'order_id':order.order_id})) ... url's are ... path('products/<slug:prod_slug>/<str:color>/<str:size>/', product_page_view, name="product-page-view-color-size"), path('products/<int:order_id>/shipping/', shipping_view, name="product-shipping"), ... Though, function is redirecting successfully, but with AttributeError and following traceback Traceback (most recent call last): File "/home/dixitgpta/byghouz/byghouz_env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/dixitgpta/byghouz/byghouz_env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/dixitgpta/byghouz/byghouz_env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dixitgpta/byghouz/project/products/views.py", line 575, in product_page_view seller = prod.seller Exception Type: AttributeError at /products/54795882652377/shipping/ Exception Value: 'NoneType' object has no attribute 'seller' -
Jquery-datatables-editor form not rendering properly in Django
I have a bit of issue regarding how datatables editor is showing via the modal. Please see the image below to understand the kind of issue it is. The form padding is poor, width is unresponsive and has a scroll-X even on a big screen. Also, when I scroll the form, its content overlays the form title as you can see in the red circle Has anyone come across this styling issue with this form? If someone has, what strategy can one adopt to fix these issues? I have tried the #customForm in the documentation, I experienced the same issue. html {% load static %} <table id="employeesDataTable" cellpadding="5" class="display" style="width:100%"> <thead> <tr> <th><input type="checkbox" class="selectAll" name="selectAll" value="all"></th> <th>Full name</th> <th>Post</th> <th>Beat</th> <th>Deployed</th> <th>Email</th> <th>Phone</th> <th></th> </tr> </thead> </table> <script src="{% static 'data/js/data.js' %}"></script> js $(document).ready(function() { var editor; editor = new $.fn.dataTable.Editor({ ajax: "/api/employees/editor/", table: "#employeesDataTable", idSrc: 'id', fields: [{ label: "fullname:", name: "fullname", 'className': 'full block' }, { label: "gender:", name: "gender", }, { label: "date of birth:", name: "date_of_birth", type: 'datetime', }, { label: "permanent address:", name: "permanent_home_address", }, { label: "present address:", name: "present_home_address", }, { label: "email:", name: "email", },{ label: "phone number:", name: "phone_number", },{ … -
Field 'id' expected a number but got 'productId'
I got an unexpected error while I was trying to compare the id on the database of Model Product with that of the id sent by the user click event. I assume that both the id must be of the same value and type but still Django say that they expect something different. View.py def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] customer = request.user.customer product = Product.objects.get(id=productId) <!-- this line of code --> To address the click event I have used JS with Fetch API fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ 'productId': productId, 'action': action }) }) .then((response) => { return response.json() }) .then((data) => { console.log('data:', data) location.reload() }) The url is also defined correctly. What might be the issue that I am not being able to trace? Help -
Django unittest how to determine the test sequence?
For example: A book with a foreignkey auth(django user). I try to write: class UserTestCase(TestCase): def test_create(self): User.objects.create_user(username="John", password="pass123456", email="12345678@outlook.com", first_name="John") class BookTestCase(TestCase): def test_create(self): book=Book() book.auth = User.objects.get(username="John") if __name__ == "__main__": TestCase.main() but it can't work.It ended with an error django.contrib.auth.models.User.DoesNotExist: User matching query does not exist. -
No module named 'tinymce' while running makemigrations on Digitalocean deployment
So I am trying to run makemigrations to set up my models + db in terms of deploying my app on Digitalocean. However, it raises the below error that never appeared in development: (env) jonas@ubuntu-s-1vcpu-1gb-fra1-01:~/blog/stocksphere$ sudo python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/usr/local/lib/python3.6/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/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 'tinymce' (env) jonas@ubuntu-s-1vcpu-1gb-fra1-01:~/blog/stocksphere$ settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Custom Apps 'blog', 'tinymce', 'calculator', 'contact', ] urls.py urlpatterns = [ path('admin', admin.site.urls), path('calculator', render_calculator, name='calculator'), path('about', render_about), path('policies', render_policies), path('disclaimer', render_disclaimer, name='disclaimer'), # tinymce url(r'^tinymce/', include('tinymce.urls')), # include other urls.py files from sub apps path('', include('contact.urls')), path('', include('blog.urls')), ] I already tried this solution without success. When I re-install django-tinymce and pip freeze … -
How do I perform string actions on some CharField() or TextField right there in the model definition?
I am working on one of my first Django projects and on one of the models, I needed a field that returns a list that I can loop through and use in my templates. I have been trying to make it happen right there in models.py because I learned from the tutorials that it is best to perform all data manipulation or logic in the models file and nothing of such should be done in the templates as the template is just for rendering already parsed data. I tried: class Profile(): '''More user information.''' user = models.ForeignKey(User, on_delete=models.CASCADE) user.first_name = models.CharField(max_length=25) user.last_name = models.CharField(max_length=25) interests = models.CharField(max_length=200) user.interests = [interest.strip() for interest in interests.split(',')] In the code snippet above, I tried splitting comma separated values input by the user to try and make a list of it but I got the error:AttributeError: 'TextField' object has no attribute 'split'. Since the models.Charfield() and models.TextField() don't return a string, how do I go about this? I use the sqlite db on my local.