Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create multi page pdf report from class objects using XHTL2PDF
I would like to create a multi-page pdf report that creates a new page for each class instance. I store each instance in a list called objects and would like to duplicate each pdf created as a new page in the full pdf report. Right now when I generate the pdf I can get a 1 page report that includes the [0] index. I would like to know how to loop through all indexes of this class and create a new page for each instance. def generate_pdf(request, *args, **kwargs): for x, y in enumerate(Store_Objects.objects): template = get_template('payback/pdftemplate2.html') context = { "store_name": Store_Objects.objects[x].store_name } html = template.render(context) pdf = render_to_pdf('payback/pdftemplate2.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') return response return HttpResponse ("Could not Render PDF") I would like to know how to create a page break and duplicate the exact pdf template but with attributes from the next instance. I'm assuming it has something to do with the return response but I can't figure out what needs to be there to create a new page and continue the loop. -
Cannot set AUTH_USER_MODEL
I have a trouble when trying to extend the 'User' model. In order to make this I've used the settings.AUTO_USER_MODEL from django.conf.settings But that's not working -
Django 2.3: I committed my secret key to a private repository. Can I just edit the secret key myself and then add .env file to .gitignore?
So in being a newb to Django I accidentally committed my secret key to a private repository that I have for my website. Considering that I intend to use this site for business purposes, I want to make sure that it is secure as possible. Do I need to generate a whole new Django Key? Or could I possibly just edit lets say, 10 characters of the secret key, add the edited secret key to my .env file, add the .env to my .gitignore file and call it a day? I recognize this is not the best approach. I will most likely completely generate a new secret key but I thought this might be an effective quick fix. I figure that by doing it this way the new secret key is still randomly generated and the old one is still available on github but useless to anyone who happens to scrape it. FYI I am using python-decouple with a .env file which is where I save all my secret variables (aws info, secret key, db info, etc.). I have separate settings files (production.py, development.py, common_settings.py) where both production.py and development.py import all of the data from common_settings.py. I just happened … -
Django won't render form in multiple templates?
New to Django. Crispy form renders beautifully on register page. Exact copy and paste doesn't render the form on login page? All help is greatly appreciated. I've also tried removing Crispy from the equation with no luck. main_project/urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views from website import views as website_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('home/', website_views.home, name='site-home'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout') ] users/forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) email = forms.EmailField() address = forms.CharField(max_length=100) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] users/views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm # Create your views here. def register(request): if request.method == 'POST': register_form = UserRegisterForm(request.POST) if register_form.is_valid(): register_form.save() username = register_form.cleaned_data.get('username') email = register_form.cleaned_data.get('email') messages.success(request, f'Account created for {username}') return redirect('website-home') else: register_form = UserRegisterForm() return render(request, 'users/register.html', {'register_form':register_form}) users/register.html AND users/login.html {% extends 'base.html' %} {% load crispy_forms_tags %} <!-- Extra Styling? --> {% block extrahead %} {% endblock extrahead %} <!-- Include Navbar? --> … -
Split models and forms into a subfolder structure Django 2.0+
I want to have the following structure for models and forms inside my app: project/ --------app_name/ -----------------forms/ -----------------------__init__.py -----------------------a.py -----------------------b_folder/ --------------------------------__init__.py --------------------------------b1.py --------------------------------b2.py -----------------models/ -----------------------__init__.py -----------------------a.py -----------------------b_folder/ --------------------------------__init__.py --------------------------------b1.py --------------------------------b2.py Splitting the app into different apps doesn't really make sense in this particular case. At the moment everything fit into models.py and forms.py but they are around 10k lines each. The idea will be to be abble to split those monolith into small entities to simplify the code maintenance of the all project. For the models parts it seems to work: I was able to runserver without any error. It starts crash when I apply the same method to the forms. Here is the __init__.py content forms/__init__.py from .a import * from .b_folder import * forms/b_folder/__init__.py from .b1 import * from .b2 import * models/__init__.py from .a import * from .b_folder import * models/b_folder/__init__.py from .b1 import * from .b2 import * Now, how to import the following? forms/b_folder_b1.py #how to import the model a or b1? from app_name.models import AModel, BOneModel I get the following error: ImportError: cannot import name 'BOneModel' from 'app_name.models' (/project/app_name/models/__init__.py) -
error:Reverse for 'centreupdate' with keyword arguments '{'pk': 2}' not found. 1 pattern(s) tried: ['NewApp/centreupdate/(?P<slug>[-\\w\\d]+)']
I wanted to use a field value instead of primary key in my url, I looked up on the internet and found some code to do so.I want to use slug in the centreupdate url, but I am not even able to access the centrelist url.What am I doing wrong? Thanks in advance. models.py class Centre(models.Model): name= models.CharField(max_length=50, blank=False, unique=True) address = models.CharField(max_length =250) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.") contact = models.CharField(max_length=100, blank=False) phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) # validators should be a list slug = AutoSlugField(unique_with='id', populate_from='name') def __str__(self): return self.name def get_absolute_url(self): return reverse("index") urls.py url(r'^createcentre/$', views.centre.as_view(), name='centreinfo'), url(r'^centrelist/$', views.CentreListView.as_view(), name='centrelist'), url(r'^centreupdate/(?P<slug>[-\w\d]+)',views.CentreUpdateView.as_view(),name='centreupdate'), url(r'^centredelete/(?P<pk>\d+)/$',views.CentreDeleteView,name='centredelete'), -
how to print objects that are in a list that and list is in dictionary
I have a django 1.11 and python 2.7. I want print this objects or know how to access to information Okay this is situation: Okay in my dictionary insert a list, in this list insert a object and node my code is this def __init__(self): BAJO = "Bajo" MEDIO = "Medio" ALTO = "Alto" OUTCOMES = [BAJO, MEDIO, ALTO] net = pysmile.Network() dicCompetencias = {} ALL_COMPETENCES = [] for p in Competencias.objects.raw('SELECT idCompetencias from test_app_competencias where idmapasfk_id = 9 '): lstCompetences = [] lstCompetences.append(objCompetencias(p.idCompetencias).Datos) lstCompetences.append(self.create_cpt_node(net, str(p.idCompetencias), str(p.nombre),OUTCOMES)) dicCompetencias[p.idCompetencias] = lstCompetences print dicCompetencias The ouput {32: [, 0], 33: [, 1], 34: [, 2], 35: [, 3], 36: [, 4], 37: [, 5]} how to see there objects i tried when methods str and repr maybe bad. -
How do I have a profile picture revert to "default" if it is externally deleted?
So I have created a blog with Django, where users who register have a basic default profile picture. The issue is, if I were to delete their profile picture using my hosting site (PythonAnywhere, for example), it doesn't go back to the default image, but rather just an unloaded file. class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = 'default.jpg', upload_to = 'profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) @receiver(models.signals.pre_save, sender=Image) def auto_delete_file_on_change(sender, instance, **kwargs): #Deletes old file from filesystem when corresponding MediaFile object is updated with new file. if not instance.pk: return False try: old_file = sender.objects.get(pk=instance.pk).file except sender.DoesNotExist: return False new_file = instance.file if not old_file == new_file: if os.path.isfile(old_file.path): os.remove(old_file.path) I want to know how to make it so if their profile picture is deleted externally, it defaults to the default.jpg stored in the profile_pics folder inside a media folder. -
uncaught exception: could not load memory initializer wildwebmidi.js.mem
I'm trying to adapt a midi web player to my own project. It works perfectly when I try it local, but when I launch it in localhost, throws me the error of the title. I don't know what I'm doing badly but I've tried some solutions that didn't work. My project is based on django. -
Hidden Button Not Hiding with setInterval
I have a Django app where a user enters an Elasticsearch query and it generates a downloadable document. I have a Download Report button that is supposed to appear once the report is done being generated. However, it shows up at first then checks if the report is generated before disappearing until the report is done. What do I need to modify in my code for the button to hide until the report is done, and not show up before? Note: I am aware my button is not functional and not pointing to anything, I'm still trying to work on that. views.py def check_progress(request): """ Returns status of document generation """ fn = request.POST["filename"] file = "/app/created_files/" + fn if not os.path.exists(file): return JsonResponse({"report_in_progress": 1}) else: return JsonResponse({"report_in_progress": 0}) check.html <!-- templates/django_audit/check.html --> {% extends 'base_login.html' %} {% block title %}Please wait{% endblock %} {% load static %} {% block content %} <script type='text/javascript' src="{% static "bootstrap/js/jquery/1.7.1/jquery.min.js" %}"></script> <script type="text/javascript"> $(document).ready( function() { var fn = $('#fn').val() var checkInterval = setInterval(isFileComplete, 3000); //3000 is 3 seconds function isFileComplete() { $.ajax({ url: '/check_progress/', type: 'POST', data: { 'filename': fn, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, dataType: 'json', success: function (data) { if … -
Ejabberd Django External Authentication not working
I'm working on a Django Website which needs a Chat System, therefore I wanted to implement an XMPP Server which authenticates against the Django Backend. I've been using different Ejabberd External Authentication scripts like django-xmpp, django-ejabberd-bridge and one which can be found at https://www.ejabberd.im/files/contributions/ejabberd_auth_bridge.py.txt But yet none of them has worked. The script provided by django-xmpp crashes during login to the XMPP Server with the error An error has occurred during eJabberd external authentication: unpack requires a buffer of 2 bytes Traceback (most recent call last): File "/home/dcpacky/Public/plutus.live/userdashboard/management/commands/ejabberd_auth.py", line 105, in handle data = self.from_ejabberd() File "/home/dcpacky/Public/plutus.live/userdashboard/management/commands/ejabberd_auth.py", line 40, in from_ejabberd (size,) = struct.unpack(">h", input_length) struct.error: unpack requires a buffer of 2 bytes And then the authentication script crashes. The same error occures using django-ejabberd-bridge but since django-xmpp is based of django-ejabberd-bridge, it's probably the same error origin. When I've been using the implementation found in the Ejabberd documentation, which is linked above, the following error occurs. Traceback (most recent call last): File "/home/dcpacky/Public/plutus.live/userdashboard/management/commands/ejabberd_auth.py", line 126, in handle size = struct.unpack('>h', length)[0] TypeError: a bytes-like object is required, not 'str' I tried around using functions like str(), encode(), decode() and so on but yet wasn't able to get it working. … -
Pass variable from view to form in Django
I am building a simple task management system, where a Company can have multiple projects, and each company has employees. I want a form that allows managers to add users to projects, with the constraint that the available users belong to the company. I am passing the variable company_pk from the view to the form, but I am not sure how to set/access the variable outside the init finction. class AddUserForm(forms.Form): def __init__(self, company_pk=None, *args, **kwargs): """ Intantiation service. This method extends the default instantiation service. """ super(AddUserForm, self).__init__(*args, **kwargs) if company_pk: print("company_pk: ", company_pk) self._company_pk = company_pk user = forms.ModelChoiceField( queryset=User.objects.filter(company__pk=self._company_pk)) form = AddUserForm(company_pk=project_id) As mentioned, I want to filter the users to only those belonging to a given company, however I do not know how to access the company_pk outside of init. I get the error: NameError: name 'self' is not defined -
Trying to have display a csv file without downloading Django Rest Framework
I'm trying to display a csv file like I would normally do with Json or XML with Django Rest. Here's an example of what I have. For some reason when I press the 'csv' button it automatically downloads it. I want to view it in separate page like I normally do with the 'Json' and 'xml' option. I am using the djangorestframework-csv package. This is what I have in my settings for the project. REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework_xml.renderers.XMLRenderer', 'rest_framework_csv.renderers.CSVRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework_xml.parsers.XMLParser', 'rest_framework_csv.parsers.CSVParser', ) -
How to implement two QuerySets in .HTML (Noob-Question)
I'm new to Django and trying to understand how it works. Basically I'm building this simple Blog and I have one Question regarding the implementation of the QuerySets in my .HTML file. This is how my code looks like: Models.py class Post(models.Model): [...] class Highlight(models.Model): [...] Views.py from django.shortcuts import render from django.utils import timezone from .models import Post from .models import Highlight def post_list(request): posts = Post.objects.all return render(request, 'blog/post_list.html', {'posts': posts}) def highlight_list(request): highlights = Highlight.objects.all return render(request, 'blog/post_list.html', {'highlights': highlights}) Urls.py from django.urls import path from . import views urlpatterns = [ path('', views.post_list, name='post_list'), path('', views.highlight_list, name='highlight_list'), ] post_list.html {% for post in posts %} {{ post }} {% endfor %} {% for highlight in highlights %} {{ highlight }} {% endfor %} The problem is, it only shows the objects from the class Post. Is it somehow possible to include both QuerySets from both classes? If yes, what am I doing wrong? :x Thank you! -
How to execute view differently if it is coming from a different URL?
So I want to make a message app in Django. There is a view that used for deleting message. It just hides the message if user clicks delete. It changes the boolean field of message 'hide' to True if executed. I have two different template, Inbox and Outbox. I want to have delete feature for booth of these. But want to use the same view. I just want to check if the request is comming from Outbox, then I will change to_hide. If the request is comming from Inbox I will change frm_hide. But I don't know how to catch the URL in view and condition them to perform different function. Message Model class Msgs(models.Model): to = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_user') frm = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_user') title = models.CharField(max_length = 255) body = models.CharField(max_length=2000) date = models.DateTimeField(auto_now=True) to_hide = models.BooleanField(default=False) frm_hide = models.BooleanField(default=False) def __str__(self): return f'{self.frm} to {self.to}: {self.title}' ## Delete/Hide View @login_required def deletemsg(request, msg_id): msg = Msgs.objects.get(pk=msg_id) msg.frm_hide = True msg.save() return redirect('/msgs/inbox/') # inbox url: http://127.0.0.1:8000/msgs/inbox/ # outbox url: http://127.0.0.1:8000/msgs/outbox/ -
Django channels can't log exceptions in console
Django-Channels can't show exception error in console When an exception raise in any section of my consumer. it just show "WebSocket DISCONNECT /ws/test/ [127.0.0.1:7907]" in console when exception occurred. I run project with debug=True setting with this command: python3 manage.py runserver I use base settings for django-channles: # CHANNELS # ------------------------------------------------------------------------------ ASGI_APPLICATION = "config.routing.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } and have a very simple consumer: class Test(WebsocketConsumer): def connect(self): print(self.scope['headers']) self.accept() def receive(self, text_data=None, bytes_data=None): print(text_data) -
django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'handshake: reading inital communication packet', system error: 0")
I am developing an app in django to push it on Heroku, and while trying to migrate a database in mysql to heroku, I pip installed mysql..something and as I try to run the server, I got this error: django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'handshake: reading inital communication packet', system error: 0") (I had my virtual environment on). The strange thing is that the package installed python even if I had that already installed. I found out that it unistalled django and several modules I previously installed. I re-installed the modules but now as I run the server I get that error above. If I run the server from another app directory, the database runs fine. Is it maybe related to something I had installed in my directory and maybe was apparently overwritten by the strange package? here is my pip freeze result: certifi==2019.6.16<br> dj-database-url==0.5.0<br> Django==2.2.3<br> django-heroku==0.3.1<br> gunicorn==19.9.0<br> mysql-connector-python==8.0.16<br> mysqlclient==1.4.2.post1<br> protobuf==3.6.0<br> psycopg2==2.8.3<br> PyMySQL==0.9.3<br> python-decouple==3.1<br> pytz==2019.1<br> six==1.12.0<br> sqlparse==0.3.0<br> whitenoise==4.1.2<br> wincertstore==0.2<br> -
Font-Awesome CSS file not working but Font-Awesome CDN works. Why?
I am building my own website and am hosting my static files in an AWS S3 bucket. Everything on my site seems to work except for the CSS file that contains all of the font-awesome CSS information. In this case, my social media icons and all of the other icons that font-awesome has to offer wouldn't work even though I triple checked that the path was correct (Checked in aws as well as through inspection on chrome. The paths matched) I recently added the font-awesome CDN and now they all appear. While I am happy that I resolved the issue, I would really like to know why the CSS didn't work. I downloaded the CSS file from bootstrapmade so everything should work just like they created it. Could anyone tell me why this might be the case? I have run into this a few times and am wondering if there is something that I am missing. I am currently using Django 2.3 with Python 3.7.3. <!-- Libraries CSS Files --> <link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' rel='stylesheet' type='text/css'> <link href="{% static 'static/lib/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet"> <link href="{% static 'static/lib/owlcarousel/owl.carousel.min.css' %}" rel="stylesheet"> <link href="{% static 'static/lib/owlcarousel/owl.theme.min.css' %}" rel="stylesheet"> <link href="{% static 'static/lib/owlcarousel/owl.transitions.min.css' %}" rel="stylesheet"> -
How to migrate to dockerfile if the database is in another container?
Such situation: There is a container with a dB and Django container of the application which through-link connects to a dB and starts itself: FROM deb_base COPY vfnd vfnd CMD ["python", "./vfnd/manage.py", "runserver", "0.0.0.0:8001"] The bad thing is that you have to run python vfnd/manage.py migrate manually every time I launch the containers. Tried the following code: FROM deb_base COPY vfnd vfnd RUN ["python", "./vfnd/manage.py", "migrate"] CMD ["python", "./vfnd/manage.py", "runserver", "0.0.0.0:8001"] However, when you try to build the image, you receive an error on this command Step 3/4 : RUN ["python","./vfnd/manage.py","migrate"] ---> Running in 5791de6fc147 Traceback (most recent call last): File "/usr/share/Python-3.7.3/lib/python3.7/site-packages/django/db/backends/b ase/base.py", line 216, in ensure_connection self.connect() File "/usr/share/Python-3.7.3/lib/python3.7/site-packages/django/db/backends/b ase/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/usr/share/Python-3.7.3/lib/python3.7/site-packages/django/db/backends/p ostgresql/base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "/usr/share/Python-3.7.3/lib/python3.7/site-packages/psycopg2/__init__.py ", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "pg_1" to address: Name or service not known How can I implement my idea -
How to post data in textarea inside table in Django?
I have multiple text area inside side a table which has the same id. How can I post textarea value in views? Note:-i want to post textarea data with template table row id but I don't know how. -
Django memcached does not cache view when redirecting from same view
I currently have memcached installed on my Django server. I have two views: index and results. From the index I use a post form method to redirect me to the results view based on the search. The memcached works fine here. The results view gets cached correctly. However this only works from the index view. In the results view I give the user the option to search again which redirects the user back to the results view on same input, but this view is not cached. I used a time.sleep() timer to see if the page was being cached. I've tried messing around with urls.py as I currently have a regular expression for the url match, but no luck here. I'm not exactly sure where the error could be persisting from. @cache_page(61*1) def index(request): if request.method == 'POST': return redirect(results, input_1=some_input) @cache_page(61*1) def results(request, input_1): time.sleep(2) # Using this to test view cache if request.method == 'POST': return redirect(results, input_1=some_input) The code above is stripped down, but it gets the idea of what I'm trying to do across. Thank you for your help. -
How to get image name in django without extension name
How can i get image name without extension name I'm using this code but output= imagename.jpg . {{ post.image.name }} I want like this output=imagename -
django, pass mutliple files to api, including other parameters
I am new to Django. I am building a Django REST API to call NLP models. So the way i am seeing it is that I would have 100 xml files and some 6 different models that I would be running on them. So I would have to send the 100 xml files in byte array form, including the information about these 6 models that I want to run, through API. My question is what is the best approach I should take Is it ok to convert all xml to byte [] and pass them to API in json format along with model information in one API call? I am worried that might be a lot to send our the one api call. The xml files are of size 100 to 200k Should I copy the files to the server aside of calling REST API and once copied, I pass on the model informaton thrugh API. -
Django - get auto_now field in pre_save signal
I'm using Django 2.1.5. There is a model with 'auto_now' field: class BaseModel(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True, unique=True, primary_key=True) updated_at = models.DateTimeField(db_index=True, auto_now=True) updated_by = models.CharField(max_length=200) responded_at = models.DateTimeField(db_index=True, null=True, blank=True) responded_by = models.CharField(max_length=200, null=True, blank=True) Now, I have a pre_save signal for that model, and I want to update there the responded_at and responded_by fields to be equal to updated_at and updated_by. In that signal - the updated_by value is already the new one, as supposed to be in the end of the request, but the updated_at is not. It's the old (current) value. I want, if possible, to be able to get the value that supposed to be in updated_at field after the save. The reason I'm using pre_save signal and not post_save is because I'm updating the instance inside it. -
Is there any way to set the font color to models.CharField for a snippet in Wagtail?
I'd like to set the font color as the user wishes. For example, typing "I'd like to set to RED." in the charfield, I wanna make only "RED" the red color. I was looking at to use richtext somehow, but seems impossible. What should I do?