Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mod_wsgi.Input object has no attribute stream Error
when I try to send an e-mail from my Contact page, I get this error. How Can I Solve? I am getting this error on ubuntu server and in addition, these codes work in localhost without any problems. I tried very hard, but I could not find a solution because I did not know very well about servers. I would be grateful if you could help AttributeError at /iletisim/ 'mod_wsgi.Input' object has no attribute 'stream' Request Method: POST Request URL: https://xxxx.com/iletisim/ Django Version: 3.2 Exception Type: AttributeError Exception Value: 'mod_wsgi.Input' object has no attribute 'stream' Exception Location: /var/www/contact/views.py, line 22, in iletisim Python Executable: /usr/bin/python3 Python Version: 3.6.9 Python Path: ['/var/www', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Wed, 28 Apr 2021 00:42:52 +0300 MY VIEW.PY from django.shortcuts import render,redirect from .models import * from .forms import * from log.forms import * from django.contrib import messages def iletisim(request): iletisim_log_form = IletisimLogModelForm(request.POST or None, request.FILES or None) iletisim_form = IletisimModelForm(request.POST or None, request.FILES or None) if iletisim_form.is_valid(): form = iletisim_form.save(commit=False) if iletisim_log_form.is_valid(): logform = iletisim_log_form.save(commit=False) logform.log_kullaniciadi = form.iletisim_adisoyadi logform.log_epostasi = form.iletisim_epostasi logform.log_konusu = form.iletisim_konusu logform.log_icerigi = form.iletisim_icerigi sock = request._stream.stream.stream.raw._sock logform.log_ipportiletisim = sock.getpeername() logform.save() form.save() messages.success(request, 'Gonderildi...') return redirect('sonuc') return render(request, … -
Django employer employee relationship
I'm having bit of a trouble with how to structure One Employer to many Employees relationship in Django when employees need to login too. My initial set is only employers are users and employees don't login and here is that setup: from django.contrib.auth.models import User class Company(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) company_name = models.CharField(max_length=100, blank=False, null=True) ... class Employee(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, related_name='employees') full_name = models.CharField(max_length=50, null=True, blank=True) .... But now I made a mobile app and employees need to login as well. I'm managing the auth with JWT, Back-end (Django) with Graphene (So GraphQL) and mobile app with Apollo client. Question is: How do I create a User account (in auth_user table, which is what JWT uses for authentication) for employees while still maintaining the foreignKey relationship to the company? -
TemplateSyntaxError at /register/ Invalid block tag on line 20: 'endblock'. Did you forget to register or load this tag?
{% extends "django_blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom-mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted" >Already Have An Account? <a class="ml-2" href="#">Sign In</a> </small> </div> {% endblock content %} It was working before I added crispy form. Whenever I reload /register the error appears -
LOGIN_REDIRECT_URL not redirecting
I'm using Django, Mysql and Docker, with a custom user model for Django. After entering correct login details the LOGIN_REDIRECT_URL='searcher-home' variable in settings.py isn't redirecting to the home page as expected, instead it attempts to redirect to the default path of /accounts/profile/. Does anyone know what could be causing this? I've looked elsewhere for answers, but all issues I've found are either looking for LOGIN_URL which isn't what I need, or are using custom LoginViews, which I'm not. Any insight would be appreciated. -
Django X-editable
and thank you for always saving me in my project :D I am using django to develop my app and here is the page I have basically displaying a table : Html code here : <table class="logtable" > <tr> <td> Year </td> <td name="yearr">{{ yearr }}</td> </tr> <tr> <td> Plant </td> <td>{{ plant }}</td> </tr> <tr> <td>Responsible</td> <td>{{responsible}}</td> </tr> <tr> <td>Produced sales in Km per week</td> <td>{{produced}}</td> </tr> <tr> <td>Sold sales per Week (m)</td> <td>{{sold}}</td> </tr> <tr> <td>Number of customers </td> <td>{{customers}}</td> </tr> <tr> <td>Number of produced references </td> <td>{{references}}</td> </tr> <tr> <td>Shipment destinations </td> <td>{{destinations}}</td> </tr> <tr> <td>Plant shifts </td> <td>{{shifts}}</td> </tr> </table> I would like to to be able to double click a td to change its value and save into the database, I think x-editable allows me to do that, can someone help me on how to do it ? Thank you -
JSON parse error - Expecting value: line 1 column 1 (char 0) - DELPHI Rest Datasnap
I'm trying to make a POST request in the delphi language, as a client and Django as a server. But when doing the POST is giving the error: { "detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)" } All the authentication part is working correctly, I can make GET requests without problems. Source code used to add my json to the body of the request. sJson := '{"id":9,"grupo":"TESTE","id_empresa":26,"prioridade":0}'; RESTRequest.Body.ClearBody; with RESTRequest.Params.AddItem do begin name := 'body'; Value := sJson; Kind := pkREQUESTBODY; ContentType := ctAPPLICATION_JSON; end; RESTRequest.Execute; Result.Value := RESTResponse.content; Result.StatusCode := RESTResponse.StatusCode; Result.Mensagem := RESTResponse.StatusText; Making the same request through PostMan everything goes well, but not when I do it through my application. Would anyone know the resolution of this ?? -
Not getting any data in my django template
I have a URL that calls my Create View with a primary key. For some reason the html template never gets any data. Have tied printing out pk, table.pk etc. but no data seems to make it to the view... my view looks like this: class SegmentAddView(LoginRequiredMixin,CreateView): model = Program template_name = 'segment_add_view.html' form_class = SegmentForm context_object_name = 'program_info' The models are as follows: class Program(models.Model): air_date = models.DateField(default="0000-00-00") air_time = models.TimeField(default="00:00:00") service = models.CharField(max_length=10) block_time = models.TimeField(default="00:00:00") block_time_delta = models.DurationField(default=timedelta) running_time = models.TimeField(default="00:00:00",blank=True) running_time_delta = models.DurationField(default=timedelta) remaining_time = models.TimeField(default="00:00:00",blank=True) remaining_time_delta = models.DurationField(default=timedelta) title = models.CharField(max_length=190) locked_flag = models.BooleanField(default=False) deleted_flag = models.BooleanField(default=False) library = models.CharField(null=True,max_length=190,blank=True) mc = models.CharField(max_length=64) producer = models.CharField(max_length=64) editor = models.CharField(max_length=64) remarks = models.TextField(null=True,blank=True) audit_time = models.DateTimeField(auto_now=True) audit_user = models.CharField(null=True,max_length=32) class Segment(models.Model): class Meta: ordering = ['sequence_number'] program_id = models.ForeignKey(Program, on_delete=models.CASCADE, related_name='segments', # link to Program ) sequence_number = models.DecimalField(decimal_places=2,max_digits=6,default="0.00") title = models.CharField(max_length=190, blank=True) bridge_flag = models.BooleanField(default=False) seg_length_time = models.TimeField() seg_length_time_delta = models.DurationField(default=timedelta) seg_run_time = models.TimeField(default="00:00:00",blank=True) seg_run_time_delta = models.DurationField(default=timedelta) seg_remaining_time = models.TimeField(default="00:00:00",blank=True) seg_remaining_time_delta = models.DurationField(default=timedelta) author = models.CharField(max_length=64,null=True,default=None,blank=True) voice = models.CharField(max_length=64,null=True,default=None,blank=True) library = models.CharField(max_length=190) summary = models.TextField() audit_time = models.DateTimeField(auto_now=True) audit_user = models.CharField(null=True,max_length=32) I have a button in my detail screen that does this: <button type="submit" value="add_segment" … -
Django Models: How to pass the id of a class, and the non-null object fields of a class to another class?
This is a conceptual question, not an error necessarily. How do I differentiate between drawing the autogenerated id of a class and drawing the name of non-null object fields in a class? For example, in my class Source, I have: class Source(models.Model): profile = AutoOneToOneField(User, on_delete=models.CASCADE, null=True) project= AutotOneToOneField(Project, on_delete=models.CASCADE, null=True) team =AutotOneToOneField(Team, on_delete=models.CASCADE, null=True) department = AutoOneToOneField(Department, on_delete=models.CASCADE, null=True) def __str__(self): return self.profile + self.project + self.team + self.department and the goal is to have the source either be from a profile, project, team, or department, and I want to associate that source with a a sourceID, but I also want to be able to know the type of source. In my class, VideoPost: class VideoPost(models.Model): sourceID = models.ForeignKey(Source, on_delete=models.CASCADE) postID = models.ForeignKey(Post, on_delete=CASCADE) I want to draw the sourceID, but in my class Following: class Following(models.Model): profile = AutoOneToOneField(User, on_delete=models.CASCADE) account_types = models.ForeignKey(Source, on_delete=models.CASCADE) #need to create an account type account_ids = models.PositiveIntegerField() following_objects = GenericForeignKey('account_types', 'account_ids') def __str__(self): return self.profile + 'is following' I want to draw the type of source (in account_types). How do I differentiate and return the values desired? -
Add divs with Django template tags on button press
I have a simple form defined in forms.py: SAMPLE_STRINGS = [('','Select...'),'aa','ab','bb','c0'] class MyCustomForm(forms.Form): chosen_string = forms.ChoiceField(choices=SAMPLE_STRINGS, label='Please select a string', required=True) chosen_number = forms.IntegerField(label='Please select an integer', widget=forms.NumberInput(attrs={'placeholder': 0})) I want to allow the user to add boxes (divs) containing the above form. One standalone div, with Django's template tags, would look like this: <div class="box" style="height:auto; background-color: #eee;"> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} </form> </div> I know that, if there is a button <button class="add_box">New Box</button>, the corresponding jQuery script to add new elements would look like this: $('#button_id').click(function(){ $('#canvas').append(' ...*HTML of element*... '); }); However, this jQuery doesn't seem to work when the element to be appended doesn't contain pure HTML/CSS but also Django templates. My views.py: def my_form_func(response): form = MyCustomForm(response.POST or None) return render(response, "main/my_custom_form.html", {"form": form}) my_custom_form.html: <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( ".box" ).draggable().resizable(); } ); // adding div and form on button click - this part causes error $('.add_box').click(function(){ $('#canvas').append('<div class="box" style="height:auto; background-color: #eee;"><form method="get" action="">{% csrf_token %}{{form.as_p}}</form></div>'); }); </script> <html> <button class="add_box">New Box</button> <div id="canvas" style="background-color: #444; height: 90%"> <div class="box" style="height:auto; background-color: #eee;"> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} </form> </div> </div> … -
DJANGO form adding in a phone number to user profile registration
So the current issue I am having is that I currently have a form to create a user we are now adding in a phone number option for this it is currently creating the user and user profile but the user profile does not have the phone number saved the only way ive been able to get it in is manually via django admin page I've tried a few variations but none have works so far I appreciate any assistance I can get #this is in my forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] #fields = UserCreationForm.Meta.fields+ ('username', 'email', 'password1', 'password2') def clean(self): email = self.cleaned_data.get('email') username = self.cleaned_data.get('username') if email and User.objects.filter(email=email).exclude(username=username).exists(): raise forms.ValidationError('Email addresses must be unique.') return super().clean() class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['phone_number'] this is my views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) profile_form = UserProfileForm(request.POST) #added if form.is_valid() and profile_form.is_valid(): #addded profile form form.save() profile_form.save() #added messages.success(request, 'Account created!') return redirect('login') else: form = UserRegisterForm() profile_form = UserProfileForm() #added return render(request, 'user/register.html', {'form': form, 'profile_form': profile_form}) this is my register.html <form method="post"> {% csrf_token %} <fieldset class="form-group"> <legend … -
how can i add the input to the link in the action for a sech bar?
I am currently writing some script in HTML that creates a search bar. The page seems to redirect to https://schedule.nylas.com/?, but I want it to redirect to the input in the search box. i.e the input in the search box is icecreamshop and it goes to https://schedule.nylas.com/icecreamshop <form autocomplete="off" action="https://schedule.nylas.com" + input> <div class="autocomplete" style="width:300px;"> <input id="myInput" type="text" name="" placeholder="store"> </div> <input type="submit"> </form> -
django not applying css and widget after form fail
I am trying to apply CSS to input fields after form failure. The ModelForm where I am applying the original CSS and widget is: class MyAppForm(ModelForm): class Meta: widgets = { 'date_field': DateInput(attrs={"type": "date"}) } def __init__(self, *args, **kwargs): super(MyAppForm, self).__init__(*args, **kwargs) for i, f in self.fields.items(): f.widget.attrs['class'] = 'custom-css' The template where I'm redisplaying the form looks like this: {{ myapp_form.date_field.errors }} <label for="{{ myapp_form.date_field.id_for_label }}">{{ myapp_form.date_field.label }}</label> {{ myapp_form.date_field }} After the form is redisplayed, the date field displays as text input is custom-css are not applied to the input elements. How can I get widgets and CSS to apply after error? -
Suggestion on model test
I’ve been thinking about changing my simple model creation test from this. def test_create_user(self): user = User.objects.create_user( email='normal@user.com', password='foo', # other fields ) assert user.email == 'normal@user.com' # assert other fields To this def test_create_user(self): user = UserFactory.create() assert isinstance(user, User) I’m not sure if they represent the same thing, but I think the second one is easier to read. I would like to know suggesting about this kind of test, since I’m pretty new to testing thing. Thanks for your attention. -
App not compatible with buildpack Django heroku
Would anyone be able to give me a tip Heroku? Very new at this as well as Django. I am trying to follow these steps on Dev using django_heroku that is imported on the settings.py file. Small snip of settings.py: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os import django_heroku django_heroku.settings(locals()) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') This is my requirements.txt: Django==2.2.8 gunicorn django-heroku django-crispy-forms==1.8.1 django-summernote==0.8.11.4 pytz==2019.3 sqlparse==0.3.0 ProcFile: web: gunicorn mysite.wsgi --log-file - Using the Heroku pipeline as mentioned in the blog post when I do a git push heroku master: Enumerating objects: 237, done. Counting objects: 100% (237/237), done. Delta compression using up to 8 threads Compressing objects: 100% (137/137), done. Writing objects: 100% (237/237), 67.80 KiB | 6.16 MiB/s, done. Total 237 (delta 100), reused 216 (delta 92), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz … -
Collation Error When creating Django Database Models
I have followed the various tutorials from philly and others to setup django with django-mssql-backend but have had no luck. I think the connection is working but when it is trying to parse the tables I get a collation error that it cannot get past. The specs of what I'm running are as follows: django-mssql-backend: 2.8.1 django: 3.2 pyodbc: 4.0.30 'server':{ 'ENGINE': 'sql_server.pyodbc', 'NAME': 'database', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'hostname of server', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'unicode_results': True, }, } When I attempt to run the migration class creator or: python manage.py inspectdb --database=devops_02 I get the following error in the output: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models … -
StaticLiveServerTestCase Server Error 500
Main urls.py file: urlpatterns = [ path( 'admin/', admin.site.urls ), path( '', include( 'employee.urls' ) ), path( '', include( 'epos.urls' ) ), path( '', include( 'supplier.urls' ) ), ] epos.urls: urlpatterns = [ path( '', home_view, name='home' ), home_view: @login_required def home_view(request): # Get all categories categories = Category.objects.all() # Get the first category which will be selected by default selected_category = categories.first() # Get the order_items for the selected category (first category) products = Product.objects.filter( category=selected_category.id ) user = request.user tax = Tax.objects.latest('id') context = { 'categories': categories, 'user': user, 'title': "EPOS", 'products': products, 'selected_category': selected_category, 'tax': tax } return render(request, 'epos/epos.html', context) Test case: class LoginTests(StaticLiveServerTestCase): fixtures = ['fixtures/employee/employee_data.json'] def setUp(self): self.browser = webdriver.Chrome() self.browser.get(self.live_server_url) self.browser.maximize_window() def tearDown(self): self.browser.quit() def test_login_when_clocked_in(self): import ipdb;ipdb.set_trace() login_button = self.browser.find_element_by_xpath( '//button[normalize-space()="Login"]' ) clock_in_out_button = self.browser.find_element_by_xpath( '//button[normalize-space()="Clock In/Out"]' ) pin_input = self.browser.find_element_by_id( 'pin' ) pin_code = 'some pin' employee_name = 'some name' pin_input.send_keys(pin_code) clock_in_out_button.click() time.sleep(10) login_button.click() When the test logs in I am redirected to the main webpage which is localhost:46497/ but instead of the page I am getting Server Error 500. This error occurs only when testing. In addition, if I add another path e.g. localhost:46497/analytics it opens the webpage as expected. … -
Django forms: new fields whenever field value is changed?
In my forms.py I have a simple form defined, with an integer and a choice field: SAMPLE_STRINGS = [('','Select...'),'aa','ab','bb','c0'] class MyCustomForm(forms.Form): chosen_string = forms.ChoiceField(choices=SAMPLE_STRINGS, label='Please select a string', required=True) chosen_number = forms.IntegerField(label='Please select an integer', widget=forms.NumberInput(attrs={'placeholder': 0})) Currently both fields appear on the form. My goal however is to show just the ChoiceField by default, but when the user selects an option different from the default "Select..." option, append the IntegerField to the form as well. I am aware of the .changed_data property and the .has_changed() method, but both of these seem to only activate upon a "submit" button press which is not what I intend. Ideally, I would like the IntegerField to immediately when the user changes the ChoiceField from the default "Select..." to anything else, e.g. "aa". How could I achieve this - if it is even possible? My views.py now only has the following: def form_interactivity(response): form = MyCustomForm(response.POST or None) # ? # print(form.changed_data, form.has_changed()) return render(response, "main/form_interactivity.html", {"form": form}) -
Django-Heroku-PostGres: KeyError: 'psql' during Git push Heroku main
I'm trying to deploy my Django app in Heroku. I'm also using PostGreSQL and Github. I've been using a bunch of random tutorials to set this up and try to debug the results, so I apologize if there are "inconsistencies". When I run git push heroku main, I get the error remote: KeyError: 'psql' Error while running '$ python manage.py collectstatic --noinput: Here's the traceback. remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/tmp/build_e87847fa/manage.py", line 22, in <module> remote: main() remote: File "/tmp/build_e87847fa/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 363, in execute remote: settings.INSTALLED_APPS remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ remote: self._setup(name) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 790, in exec_module remote: File "<frozen … -
TemplateDoesNotExist at /post/new/ When i host the django project on heroku
I created an app with django on my local machine and it works perfectly with all the templates and html files going to the correct locations but when i tried to host it on heroku, it loads the home page but when i try to create a new blog it says templates does not exist. This is the error I keep getting: Request Method: GET Request URL: https://ifecrudapp.herokuapp.com/post/new/ Django Version: 3.2 Exception Type: TemplateDoesNotExist Exception Value: blog/post_form.html Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/template/loader.py, line 47, in select_template Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.4 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'] Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /app/templates/blog/post_form.html (Source does not exist) django.template.loaders.filesystem.Loader: /app/blog/templates/blog/blog/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/blog/templates/blog/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/users/templates/blog/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/crispy_forms/templates/blog/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/templates/blog/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/templates/blog/post_form.html (Source does not exist) -
How can I call manage.py within another python script?
I have a shell script that calls ./manage.py a few times, and would like to create the same functionality within a python 3.9.2 script. I have tried subprocess.run and os.system but get hung up for various reasons. Currently the shell script looks like ./manage.py dump_object water_testing.watertest '*' > ./water_testing/fixtures/dump_stevens.json ./manage.py dump_object tp.eqsvc '*' >> ./water_testing/fixtures/dump_stevens.json ... Any suggestions? -
Display django debug toolbar in production
I installed django-cahalot with redis backend on my django application. It is working fine on my local machine. Problem is this I am unable to see any improvement on my production server. I need to display django-debug-toolbar on my production server to analyze the bottlenecks. Thanks -
Display office files or pdf files using ViewerJS in a Django template
I'm trying to use ViewerJS in a Django 3.1 application in order to display office documents or pdf's within a Django template. The url I created is http://localhost:8000/static/js/ViewerJS/index.html/#..media/files/Materials.pdf This generates this: That is, it lifts the index.html file but no more than that. When I look at the developer console -> networks I see that many items of viewer js are not found, I understand that this is why the presentation fails. ViewerJS is located in static/js/ViewerJS In the template I have tried these two ways: <a href="/static/js/ViewerJS/media/archivos/Materiales.pdf" class="btn">Preview</a> <iframe src = "/static/js/ViewerJS/index.html/#../media/archivos/Materiales.pdf" width='700' height='550' allowfullscreen webkitallowfullscreen></iframe> If you know of another solution by which I can do what I need and it is not ViewerJs, it is welcome. But neither works. -
Django overriding display names for foreign key field in modelform
Suppose below models: from django.db import models class Status: name = models.CharField(max_length=50) order = models.PositiveIntegerField() def __str__(self): return self.name class Article: headline = models.CharField(max_length=100) status = models.ForeignKey(Status, on_delete=models.CASCADE, null=True) I want to create admin form for Article model, but don't want to use results of __str__ method of Status model as display name in status choices form field. It can be achieved by overriding label_from_instance method ModelChoiceField as below: from django import forms from blog.models import Status, Article class StatusModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, status): label = f"{status.order}: {status.name}" return label class ArticleForm(forms.ModelForm): status = StatusModelChoiceField(queryset = Status.objects.all()) class Meta: model = Article fields = ('headline', 'status') Problem with this method is that, it doesn't take into account Article model's status field definition. For example, although status field is nullable in Article model, it is required in ArticleForm. I should tell explicitly that it is not required (status = StatusModelChoiceField(queryset = Status.objects.all(), required=False)). If status field would have limit_choices_to, it also won't be considered in my form dynamically. So, I just want different display names than default __str__. How can I achieve this goal in more DRY manner? -
pixi.js не загружает картинку (pixi.js does no add image)
Всем привет, использую django и никак не выходит загрузить картинку в PiXi.loader, в settings прописан путь на статические файлы в html например выводит картинку, а вот в pixi уже нет, в инете не нашёл, вот аналог Pixi.js can't load images because Django "can't find them" Hello everyone, I use django and I can't load the image in PiXi.loader, the path to static files in html is written in settings, for example, it outputs the image, but in pixi it no longer exists, i try make this Pixi.js can't load images because Django "can't find them" my code: https://i.stack.imgur.com/uVYYB.png -
How to sort django form fields automaticly
I have django ModelForm like this class MyForm(forms.ModelForm): def make_this_fields_first(my_firlds): #what I can do here? class Meta: model= MyModel fields = '__all__' In view I want to make like this: my_form_obj = MyForm() my_form_obj.make_this_fields_first(['field6','field3'])