Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to create the django_migrations table with DateTime Field
I was migrating my Django app from local system to production server. Configurations on local server are as below: Django2.2 MySQL 5.7.27-0ubuntu0.16.04.1 mysqlclient-1.4.2.post1 sqlparse-0.3.0 On production server, configurations are as below: Django2.2 MySQL 5.5.53 mysqlclient-1.4.2.post1 sqlparse-0.3.0 Only difference between local and production configurations is of MySQL server version. There is a model with below code: class Tracking404Model(models.Model): url = models.CharField(max_length=512, null=False, blank=False) timestamp = models.DateTimeField(null=False, blank=False) After running migration, I ran the commnd python manage.py sqlmigrate app-name migration-file-number to check MySQL syntax generated, which is as below: CREATE TABLE `404_tracking` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `url` varchar(512) NOT NULL, `timestamp` datetime(6) NOT NULL); Show create table statement output on Local: mysql> show create table 404_tracking\G *************************** 1. row *************************** Table: 404_tracking Create Table: CREATE TABLE `404_tracking` ( `id` int(11) NOT NULL AUTO_INCREMENT, `url` varchar(512) NOT NULL, `timestamp` datetime(6) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 1 row in set (0.00 sec) Migrations ran just fine on local, tables were created and I was able to perform all mysql operations. Basically everything was just fine. When running migrations on production, I am getting below error: raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable … -
How to send signal from django to java script trigger
I want create a signal in my django and javascript can find out this signal and do specific action. -
html data is not rendering property in html using python django
i could not display the html data sent from python in the html page. when i open the html in view source mode, it thing data is rendered as messed html code <table border="1"> <tr> <th>servername</th> <th>cpu</th> <th>memory</th> <th>cdrivespace</th> <th>ddrivespace</th> <th>fdrivespace</th> <th>gdrivespace</th> <th>pdrivespace</th> <th>kdrivespace</th> {{ data }} </table> python view data = callFileReaderMain( form.cleaned_data['session_key'] ) return render(request,'marketplace_output.html',{'data' : data }) view source code <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title>marketplace output server details</title> </head> <body> <table border="1"> <tr> <th>servername</th> <th>cpu</th> <th>memory</th> <th>cdrivespace</th> <th>ddrivespace</th> <th>fdrivespace</th> <th>gdrivespace</th> <th>pdrivespace</th> <th>kdrivespace</th> &lt;tr&gt;&lt;td&gt;W01GCTIAPP01A&lt;/td&gt;&lt;td&gt;3.0&lt;/td&gt;&lt;td&gt;93.0&lt;/td&gt;&lt;td&gt;42.0&lt;/td&gt;&lt;td&gt;40.0&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;/tr&gt; </table> </body> </html> -
import django.http from HttpResponse ^ SyntaxError: invalid syntax
I am trying to run this but getting syntax error import django.http from HttpResponse ^ SyntaxError: invalid syntax import django.http from HttpResponse def index(request): return HttpResponse("Hello") -
Efficient replacement of source urls with django static urls
In django when we load image we use tag something like this: <img alt="background" src="{% static "img/inner-6.jpg" %}" /> and I use templates and build backend to those templates to learn django (for now) so when I start project all the images source urls and css file urls and javascript urls are given like : <img alt="background" src="img/inner-6.jpg" /> so I have to replace all of them with the above one which is time consuming and non-productive. Can someone please tell me the efficient way to do this (like notepad text replacement system or something like that). How do experience django developers deal with this kind of problems? Thanks in advance. (I have searched a lot about it before asking on stackoverflow but couldn't find anything) -
Django is complex select query possible for this?
I have the following model used to store a bidirectional relationship between two users. The records are always inserted where the smaller user id is user_a while the larger user id is user_b. Is there a way to retrieve all records belonging to a reference user and the correct value of the status based on whether the reference user id is larger or smaller than the other user id? Perhaps two separate queries, one where reference user = user_a and another where reference user = user_b, followed by a join? class Relationship(models.Model): RELATIONSHIP_CHOICES = ( (0, 'Blocked'), (1, 'Allowed'), (-2, 'Pending_A'), (2, 'Pending_B'), (-3, 'Blocked_A'), (3, 'Blocked_B'), ) user_a = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, related_name='user_a',null=True) user_b = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, related_name='user_b',null=True) relationship_type = models.SmallIntegerField(choices=RELATIONSHIP_CHOICES, default=0) -
How to fetch the selected dropdown values in the editable form in the dropdown using django
Dropdown value is stored in separate table,how to retrieve the dropdown value in the editable form views.py def edit(request, id): form = DeptForm(request.POST) form1 = DesigForm(request.POST) dt = Department.objects.all() dg = Designation.objects.all() dept = request.POST.get("depart") Department.id = dt desig = request.POST.get("design") Designation.id = dg print(Designation) edit_record = Emp_Profile.objects.get(pk=id) print(edit_record) context = { 'edit_record': edit_record } print(context) print(edit_record.department) return render(request, 'registration/register_edit.html', context,{'form' : form, 'form1' : form1}) def update(request, id): form = DeptForm(request.POST) form1 = DesigForm(request.POST) dt = Department.objects.all() dg = Designation.objects.all() if request.method == "POST": First_name = request.POST['First_name'] lname = request.POST['lname'] depart = request.POST.get("depart") Department.id = dt print(depart) uname = request.POST['uname'] design = request.POST.get("design") Designation.id = dg print("design") print(design) mnumber = request.POST['mnumber'] Emp_Profile.objects.filter(pk=id).update( first_name=First_name, last_name=lname, Mobile_Number=mnumber, username=uname, ) return redirect('/accounts/profile/') return render(request,'register_edit.html',{'form':form, 'form1':form1}) In this department and designation is two separate table,while storing it is stored in another table called "Emp_Profile".while editing,the selected value of department and designation should come with dropdown. -
How to retrieve the save checkbox value in the editable form in django
Data is save to DB, Retrieve the data in enabled checkbox. How can I write code for edit the form in views.py file In models username field is the foreign key of Emp_Profile model and Process is the foreign key of Client_Process table Models.py class Emp_Process(models.Model): username = models.ForeignKey(Emp_Profile, on_delete=models.CASCADE) process = models.ForeignKey(Client_Process, on_delete=models.CASCADE) class Meta: db_table : 'emp_process' html file {% extends 'client_pannel.html' %} {% block content %} <br><br> <br><br> <div class="data-table-area mg-b-15"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="sparkline13-list"> <div class="sparkline13-hd"> <div class="main-sparkline13-hd"> <label>{{ emp.first_name }} {{ emp.last_name }} - {{ emp.designation }}</label> </div> </div> <div class="sparkline13-graph"> <div class="datatable-dashv1-list custom-datatable-overright"> <table id="table" data-toggle="table" data-pagination="true" data-search="true" data-show-columns="true" data-show-pagination-switch="true" data-show-refresh="true" data-key-events="true" data-show-toggle="true" data-resizable="true" data-cookie="true" data-cookie-id-table="saveId" data-show-export="true" data-click-to-select="true" data-toolbar="#toolbar"> <thead> <tr> <th >Client</th> <th>Process</th> </tr> </thead> <tbody> {% for client in form %} <tr> <td> <input type="checkbox" name="cname[]" value="{{ client.id }}"> {{ client.Name }} </td> <td> {% for process in client.clients %} <input type="checkbox" name="process[]" value="{{ process.id }}"> {{ process.process }}<br /> {% endfor %} </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </div> </div> </div> {% endblock %} -
How to solve the datetime.datetime issue after running migrate in django?
Whenever I run python manage.py migrate, I get following error. How to resolve this issue? I am not understanding. Error value = self.get_prep_value(value) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\models\fields\__init__.py", line 966, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' __init__.py def get_prep_value(self, value): from django.db.models.expressions import OuterRef value = super().get_prep_value(value) if value is None or isinstance(value, OuterRef): return value return int(value) -
unable to install Django 2.2.4 for python3.7.4 on Linux mint 19.1
I want to install Django web framework version 2.2.4 on the Linux.I'm using Linux mint 19.1 with python2(default), python3.6.8(default) and python3.7.4(sudo installed from source). I am using command 'pipenv --python3.7 install django==2.2' to install but it's not working. I tried this tutorial to install Django- link to the youtube tutorial $ python3.7 -V Python 3.7.4 $ pip3 -V pip 19.2.1 from /usr/local/lib/python3.7/site-packages/pip (python 3.7) ~ dev/try_django$ pipenv --python3.7 install django==2.2.4 Usage: pipenv [OPTIONS] COMMAND [ARGS]... Try "pipenv -h" for help. Error: no such option: --python3.7 -
Django taking image from Python program
I have previously written some python code which takes some information, and presents it into a chart. An example is in the link below. The python program creates the chart, then places the numbers in the chart in the relevent location. There is some randomness as to where they are placed in the smaller squares. My question is I would like to implement this in Django. Being new to Django, my thought process is I should be calling the Python code, which would create the image from the Django database, and then displaying it. I have worked out how to call the code, however there is little information about how to do so on the click of a button. This has made me question if calling the Python code is the correct way to do this? -
How to fetch id from bottom-up approach in django ORM
How to fetch id of Process and Client model in Emp_Process using Client_Process Models.py class Process(models.Model): Name = models.CharField(max_length=50) def __str__(self): return self.Name class Meta: db_table : 'process' class Client(models.Model): Name = models.CharField(max_length=50, unique=True) def __str__(self): return self.Name class Meta: db_table : 'client' class Client_Process(models.Model): process = models.ForeignKey(Process, on_delete=models.CASCADE) client = models.ForeignKey(Client, on_delete=models.CASCADE) class Meta: db_table : 'client_process' class Emp_Process(models.Model): username = models.ForeignKey(Emp_Profile, on_delete=models.CASCADE) process = models.ForeignKey(Client_Process, on_delete=models.CASCADE) class Meta: db_table : 'emp_process' -
How to avoid path django.urls.path() funtion interpreting ? in url?
I want to set an optional request parameter in my view. But ? interprets to %3F. I have tried the following code: app_name = "account" urlpatterns = [ ... path('profile/<int:user_id>/', UserProfileManager.as_view(), name='user_profile'), path('profile/<int:user_id>/?edit=<str:edit>', UserProfileManager.as_view(), name='user_profile'), ... ] <a href="{% url 'account:user_profile' member.id 'true' %}"> Edit your profile </a> -
How to upload audio recorded by recorder.js to django backend for some analysis
This is the javascript file of the recorder.js to record and upload the audio to server how to extract that audio in django backend i want that audio file to be used in librosa library to extract some features function createDownloadLink(blob) { var url = URL.createObjectURL(blob); var au = document.createElement('audio'); var li = document.createElement('li'); var link = document.createElement('a'); //name of .wav file to use during upload and download (without extendion) var filename = new Date().toISOString(); //add controls to the <audio> element au.controls = true; au.src = url; //save to disk link link.href = url; link.download = filename+".wav"; //download forces the browser to donwload the file using the filename link.innerHTML = "Save to disk"; //add the new audio element to li li.appendChild(au); //add the filename to the li li.appendChild(document.createTextNode(filename+".wav ")) //add the save to disk link to li li.appendChild(link); //upload link var upload = document.createElement('a'); upload.href="/show/"; upload.innerHTML = "Upload"; upload.addEventListener("click", function(event){ var xhr=new XMLHttpRequest(); xhr.onload=function(e) { if(this.readyState === 4) { console.log("Server returned: ",e.target.responseText); } }; var fd=new FormData(); fd.append("audio_data",blob, filename); xhr.open("POST","show/",true); xhr.send(fd); }) li.appendChild(document.createTextNode (" "))//add a space in between li.appendChild(upload)//add the upload link to li //add the li element to the ol recordingsList.appendChild(li); } -
Create a function that identifiies object type and passes form depending on what type the object is
I have a model named product, and depending on the type of product I would like to pass a form. So, for example, if the product type is "Clothing", then render a form to select a size (S, M, L, etc...) I've tried creating a view that passes the product to a template, and then made a function within the view called is_clothing that says product type is clothing. # models.py PRODUCT_TYPE = [ ('C', 'Clothing'), ('A', 'Accessory'), ('F', 'Furniture'), ] class Product(models.Model): ... type = models.Charfield(blank=True, choices=PRODUCT_TYPE) # views.py def product_view(request, slug): productvariant = get_object_or_404(ProductVariants, slug=slug) form = ProductSizeForm # Function that defines whether product type is clothing def is_clothing(): product.type == "Clothing" context = { 'product' : productvariant, 'form' : form } return render(request, "products/product-page.html", context) <!--TEMPLATE--> {% if product.is_clothing %} {{ form }} {% endif %} As I said I was hoping to render the sizes form if the product type is clothing, but I'm not getting any results. Any ideas? -
Facing trouble in running python manage.py runserver
I am trying to run python manage.py runserver and till today I never faced any issues. Whenever I run python manage.py runserver I get this- $ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). August 11, 2019 - 05:34:42 Django version 2.1.5, using settings 'try_django.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f0b20e6d6a8> Traceback (most recent call last): File "/home/user/anaconda3/lib/python3.7/site-packages/django/utils/module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) ValueError: not enough values to unpack (expected 2, got 1) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/user/anaconda3/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "/home/user/anaconda3/lib/python3.7/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/home/user/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/user/Dev/try_django_new/src/try_django/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/user/anaconda3/lib/python3.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "/home/user/anaconda3/lib/python3.7/site-packages/django/core/handlers/wsgi.py", … -
Add range and ><= operators to django form
I am building enterprise software which someone can use to input order data from a customer. Sometimes customers order something with length 1000+ or will order something within a range of 400-600 for example. How can I display these options in a dynamic form which inputs an integer into a model? Will my model have to have max_length min_length, max_width, min_width etc or is there a better way? I've considered creating non-required fields and dynamically displaying the form depending on a dropdown menu choice near every dimension with (greater than, equal to, less than). This will make me create around 6 new fields for a basic l/w/h input. For example: If someone wants a range they can click on the side dropdown near the dimension and select range, which will then show a new input box which submits data to max_DIMENSION. Or when a user chooses > then the database saves that field as greater than. I expect to be input a range with 2 values, or a >/=/< with a single value. -
Cannot Import Name LoginView
I am trying to create a modal form in my django project. I am trying to use bootstrap modal forms and I am following an example: https://pypi.org/project/django-bootstrap-modal-forms/ When I import in views.py: from bootstrap_modal_forms.generic import BSModalCreateView I get an error "cannot import name LoginView" - but I'm confused because I do not have LoginView anywhere in my project. Why is this happening? This is my first time trying to use Class Based Views. I know this isn't a lot of detail, but I am completely confused here. -
Set a secret key with command line in Django for saleor installation on windows
I'm trying to install saleor on Windows, in the SECRET_KEY part throws an error saying that my SECRET_KEY cannot be empty, I suppose it must be entered by commands. What command is used in Windows to set a SECRET_KEY in Django and then continue to the next step of installing saleor? -
how to open a database created with docker in django
I have a question about how to open a database created with docker using https://github.com/cookiecutter/cookiecutter in pgAdmin. In the folder /home/lyon/Documentos/tienda/.envs/.local there is a file called .postgres and contains the following data: # PostgreSQL # ------------------------------------------------------------------------------ POSTGRES_HOST=postgres POSTGRES_PORT=5432 POSTGRES_DB=tienda POSTGRES_USER=debug POSTGRES_PASSWORD=debug but the connection is useless :( How can I see my database? Thank you -
How to run a combination of query and filter in elasticsearch?
I am experimenting using elasticsearch in a dummy project in django. I am attempting to make a search page where the user may provide a title, summary and a score to search for. The search should match all the information given by the user, but if the user does not provide any info about something, this should be skipped. I am running the following code to search for all the values. s = Search().using(client).query("match", title=title_value)\ .query("match", summary=summary_value)\ .filter('range', score={'gt': scorefrom_value, 'lte': scoreto_value}) When I have a value for all the fields then the search works correctly, but if for example I do not provide a value for the summary_value, although I am expecting the search to continue searching for the rest of the values, the result is that it comes up with nothing as a result. Is there some value that the fields should have by default in case the user does not provide a value? Or how should I approach this? -
Problem in saving formset in django Updateview
I am new in Django and Stackoverflow, so please accept my apology if my codes is not standard. I try to create a blogging website. Users can create and update posts and each post can have one or more categories or no category. I use form for Post and Formset for Category. However, in Updateview for some reason I couldnt save the formset!!!! models.py class Post(models.Model): title = models.CharField(max_length=128) text = models.TextField(blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Category(models.Model): name = models.CharField(max_length=128, unique=True) description = models.TextField(blank=True) posts = models.ManyToManyField(Post, blank=True,related_name='categories') class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name forms.py class PostUpdateForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'text', 'published_date'] CATEGORY_CHOICES = [('', 'Choose from the list')] for c in Category.objects.all(): CATEGORY_CHOICES.append((c, c)) class CategoryUpdateForm(forms.ModelForm): class Meta: model = Category fields = ['name'] labels = {'name': 'Category'} help_texts = {'name': 'Choose category for your post'} widgets = { 'name': forms.Select(choices=CATEGORY_CHOICES) } CategoryFormset = forms.modelformset_factory(Category, form=CategoryUpdateForm, extra=1, max_num=3, can_delete=True) views.py class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post template_name = 'blogging/post_update.html' form_class = PostUpdateForm formset_class = CategoryFormset def form_valid(self, form): form.instance.author … -
How to make a button by clicking on which the font will change
Я хочу , добавить такие кнопки в мою admin panel , чтобы по нажатию на такую кнопку я мог писать более крупным шрифтом , или мелким . Также хотелось бы добовлять изображения. And you need to add a button with which you can add images. enter image description here Can you please drop the code, or where you can see it, or maybe there is a separate application. admin.py from .models import Articles, CommentModel admin.site.site_header = 'Admin Dashboard' class ArticleAdmin(admin.ModelAdmin): list_display = ('title', 'date') prepopulated_fields = {'slug': ('title',)} list_filter = ('date',) readonly_fileds = ('body_preview',) admin.site.register(Articles,ArticleAdmin) models.py class Articles(models.Model): title = models.CharField(max_length= 200) post = models.TextField() slug = models.SlugField(unique=True, verbose_name='URL') date = models.DateTimeField() img = models.ImageField(upload_to='', default="default_value",verbose_name='Каритинка 260х180') tags = TaggableManager() article_like = models.IntegerField(default='0') article_dislike = models.IntegerField(default='0') view = models.IntegerField(default='0') datesArticle = models.DateTimeField(auto_now=True) class Meta: ordering = ['-datesArticle'] def __unicode__(self): return self.title def __str__(self): return self.title def get_absolute_url(self): return "/news/%s/" % (self.slug) -
Can you create instances of two foreign keys referencing the same model in one model?
I'm trying to create two instances of a model class called Team. I want to create two fields stored in my GameId Model called home and visitor. These two foreign keys are referenced from the same model called Team. Should I use a foreign key or many to many field relationship? Background of models: One team can have many gameids One gameid should have 2 teams class GameId(models.Model): week = models.CharField(max_length = 100) day = models.CharField(max_length = 100) home = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='home') visitor = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='visitor') gameid = models.CharField(max_length = 100, blank=True) slug = models.SlugField(max_length=100, unique=True, blank=True) -
TypeError: got an unexpected keyword argument 'model' (Django)
I'm creating a data migration for the purpose of instantiating several Mineral objects for the database. Upon running python manage.py migrate in the console I get the error: TypeError: Mineral() got an unexpected keyword argument 'model'. I can't find anything resembling this keyword that Django is raising. What is causing this error which is preventing model instances from being created? #models.py from django.db import models # Create your models here. class Mineral(models.Model): name = models.CharField(unique=True, max_length=60, null="") image_filename = models.CharField(max_length=65, null="") image_caption = models.CharField(max_length=410, null="") category = models.CharField(max_length=50, null="") formula = models.CharField(max_length=280, null="") strunz_classification = models.CharField(max_length=110, null="") color = models.CharField(max_length=195, null="") crystal_system = models.CharField(max_length=130, null="") unit_cell = models.CharField(max_length=140, null="") crystal_symmetry = models.CharField(max_length=130, null="") cleavage = models.CharField(max_length=170, null="") mohs_scale_hardness = models.CharField(max_length=70, null="") luster = models.CharField(max_length=75, null="") streak = models.CharField(max_length=60, null="") diaphaneity = models.CharField(max_length=80, null="") optical_properties = models.CharField(max_length=85, null="") refractive_index = models.CharField(max_length=125, null="") crystal_habit = models.CharField(max_length=240, null="") specific_gravity = models.CharField(max_length=70, null="") group = models.CharField(max_length=20, null="") def __str__(self): return self.name # retrieve_json.py import json def pull_json(file): with open(file, 'r') as json_file: data = json.load(json_file) return data from django.db import migrations import os.path from ..data.retrieve_json import pull_json def load_mineral_data(apps, schema_editor): Mineral = apps.get_model('minerals', 'Mineral') mineral_data = pull_json(os.path.abspath('minerals/data/minerals.json')) for m in mineral_data: Mineral.objects.create(**m) class Migration(migrations.Migration): …