Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error in my Django code in model.py part
I am learning to make models in django. But when I'm trying to do the migrations I get an error message as the owner part has an error in get_full_name of the first class and also in the return of the movie class. The errors that come out are the following: between line 23,20 theForeignKey has not `` get_full_name'` member and that both rate as rate_count are not as defined variables. I leave the code here. `from django.db import models from django.contrib.auth import get_user_model from django.core.validators import MaxValueValidator User= get_user_model()` class MoveList(models.Model): #modelo de lista para ver name= models.CharField('Nombre de la Lista', max_length=50, unique=True) owner = models.ForeignKey(User) movies = models.ManyToManyField('movies.Movie') def __str__(self): return "'{list}' de {owner}".format( list =self.name, owner =self.owner.get_full_name() ) class Movie(models.Model): #Modelo de peliculas name= models.CharField('Nombre de la pelicula',max_length=100) release_date = models.DateField('Fecha de estreno') rate = models.PositiveIntegerField('Total de claificaciones de la pelicula',blank=True, null=True) rate_count = models.PositiveIntegerField('Veces que se ha calificado a la pelicula',blank=True) tags = models.ManyToManyField('movies.Tag') studio = models.ForeignKey ('movies.Studio',on_delete=models.SET_NULL, null=True) director =models.ForeignKey('movies.Director',on_delete=models.SET_NULL, null=True) def average_rate(self): """"devuelve la calificación""" if self.rate_count == 0: return 0 else: return rate/rate_count def __str__(self): return self.name -
What is the most extensible way to manage Django UI choices that correspond to Python functions?
I am trying to create a static shared list of functions and their descriptions to display in a Django forms MultipleChoiceField. I want this to be extensible in case I add more file options later on, but I don't want to have to change the code in multiple places beyond writing the new function and adding it to a CHOICES list in my tasks.py file. I can't seem to reference the functions (a, b, and c) from my CHOICES list outside the class. I have tried TaskClass.a in the list, but I keep getting: Unresolved reference 'a' • What's the best way to do this? tasks.py CHOICES = [ ('This is function A.', a), ('This is function B.', b), ('This is function C.', c) [ class TaskClass(): def a(self): ... def b(self): ... def c(self): ... form.py from tasks import CHOICES class MyForm(forms.Form): function_choices = [] # Convert function choices to list format needed for MultipleChoiceField for i, tuple in enumerate(CHOICES): function_choices.append((i+1, tuple[0])) forms.MultipleChoiceField( choices=function_choices, widget=forms.CheckboxSelectMultiple, label='Functions to Call:' ) -
Jinja2 not processing html entities that have already been escaped
I have some API endpoints that store user input from one application which is then read out in a Django application using jinja2 templates. As such input is validated and escaped. The API returns data like this: {"id": 123, "comment": "&lt;script alert(&quote;I tried to XSS&quote;)&gt;"} When the jinja template renders this data because of the auto-escaping it literally renders &lt;script alert(... on the page. I would like it to render these tags normally such that < and > are displayed properly as text. I DO NOT however want to enable |safe as data comes from multiple uncontrolled sources and there is still the potential for injection. Is this possible? -
Django file download pass value from template view
I have a template view in django, On that template i have a download button: <a href="{% url 'smarts_cfg:template-download' cfg_template.pk %}" class="btn btn-primary">Download file</a> URL: path('<int:pk>/edit/download/', smarts_cfg_views.CgfFileDownload.as_view(), name='template-download'), View: class CgfFileDownload(View): def get(self, request, pk): content = MODEL_NAME.objects.get(pk=pk).name response = HttpResponse(content, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=%s' % 'testing.txt' return response It works as intended. What i want to do is before pressing the button and downloading the file, i want user to fill a field on the template and i want to pass this information to the download view (without saving it in the database). What is the best way to do it? thanks! -
Multi-tenancy in Django & Postgres
I am using django-multi-tenant schema to design my database. The url-name is suppose to be a key value but in my application it remains same for every tenant. I want to work around a way that would allow me to save a duplicate url for every tenant entry. Is there a way possible? -
How to merge two differently ordered queryset from same model together one after another in django
I have tried work_orders = WorkOrder.objects.all() active_wo = work_orders.filter(status=OPEN).order_by('-raised_on') completed_wo = work_orders.filter(status=COMPLETE).order_by('-completed_on') But when i merge these above querysets together as work_orders = completed_wo | active_wo` all i want to get is either active_wo objects followed by completed_wo or viceversa i am not getting proper ordered queryset as i expected. i am getting work_orders in ordered by its pk Please advice me a solution i need queryset as output as i have many filtering yet to do. -
Django inconsistent
I have django installed on a webserver and is meant to render bundles created by vue via webpack. I don't run vue on the server, thought, just upload the final stats and dist folder. I've uploaded a change today, installed the necessary loaders(webpack-loader in particular). On loading the url, sometimes it works and renders the page as on local, then other times, it just brings up the error below: webpack_loader' is not a registered tag library Why the inconsistency? The server was indeed restarted after install just to make sure. -
Issue with creating new html/css elements inside jinja loops (Django)
I am trying to create new html/css elements inside a jinja loop while within a form , where i am filling data that I brought from a django view. All the normal browser side stuff like pop-up on button clicks is good. But only the last button successfully makes a GET request whereas every button must do. This is my form here : <form method="GET" action="{% url 'search_results' %}"> {% csrf_token %} {% for name,quali,field,address,pro,c in data %} <div class="ser_tile"> <img src={{pro}} id="user_dr" > <button class="btn_tile" id="btn1" data-toggle="modal" data-target="#{{c}}">Visit Page</button> <button class="btn_tile" id="btn1" data-toggle="modal" data-target="#b{{c}}">Book Appointment</button><br/><br/> <span > Name: {{name}}&nbsp;&nbsp;&nbsp; <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star"></span><br/> Degree: {{quali}}<br/> Specialist: {{field}}<br/> Hospital: Pradyumna Bal Memorial Hospital<br/> Address: {{address}} </span> </div><br> <div class="modal fade" id="{{c}}" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Profile</h4> </div> <div class="modal-body"> <center> <div class="modal_cov"></div> <img class="modal_ico" src={{pro}}><br/><b>{{name}}</b><br/>Pradyumna Bal Memorial Hospital <hr/> </center> <div> <table> <tr> <td class="td"><b> Specialist:</b></td> <td> {{field}} </td> </tr> <tr> <td><b> Ratting:</b></td> <td> 3 </td> </tr> <tr> <td><b>Available On:</b></td> <td> Monday(10:30AM : 5:00PM), Thursday(10:30AM : 1:00PM) , Saturday(10:30AM : 1:00PM) </td> </tr> … -
How to write update function with graphene-django
I am imprementing update function of the attribute of User with graphene-django Of course we implement it as a mutation, mutate can be written with kwargs, We have to define all elements in Arguments class and field settings after all. how can we update only one element, for example? Currently, I can not update without passing all elements How can I write these well with kwargs? I want to change that there are three rewriting places for changing elements.(setting filed, arg, return) thank you class UpdateUser(graphene.Mutation): user = graphene.Field(UserType) username = graphene.String(required=True) first_name = graphene.String(required=True) last_name = graphene.String(required=True) #???password = graphene.String(required=True) email = graphene.String(required=True) class Arguments: username = graphene.String(required=True) first_name = graphene.String(required=True) last_name = graphene.String(required=True) #???password = graphene.String(required=True) email = graphene.String(required=True) @login_required def mutate(self, info, **kwargs): user = info.context.user for k, v in kwargs.items(): user.k = v # user.set_password(password) user.save() return UpdateUser(username=username, first_name=first_name, last_name=last_name, email=email ) -
Problems with Django logout
I was following a tutorial, but the logout is not working, I have something like this. (Python 3.7) from django.contrib.auth import views as auth_views urlpatterns = [ # Auth url(r'^logout/', auth_views.logout, name='logout'), ] I get this error (doesn't run): AttributeError: module 'django.contrib.auth.views' has no attribute 'logout' I also checked that there is a function called auth_logout() on that same path, but it needs a request to work, and I have no idea how to do that. It runs without the parameter and when I call the url it does logout, but I get an exception: The view django.contrib.auth.logout didn't return an HttpResponse object. It returned None instead. Any help is welcome. Thanks. -
How to access response json dictionary in python djago
below is what I got in my console log. I would like to access fields data including employee, pro_ID, pro_section, pro_description... I appreciate all the helps. {pk: 3, model: "polls.project", fields: {…}} fields: employee:[2] percent:0.02 pro_ID:"000363-A" pro_description:"PROGRAM/PROJECT REVIEWS" pro_no:"1.6" pro_section:"1.6 Program Management" user:2 __proto__: Object model: "polls.project" pk : 3 __proto__ : Object -
Get file path from a remote server
Hi I'm having a hard time in getting the file path from a remote server. Is there any one from here that could be able to help me? What I want to achieve is to play an audio file that has been save in a remote server. This is what my code looks like right now. This is not yet working. <audio controls> <source src="user@host:/file/path/from/remote/server/{{record.filename}}" type="audio/ogg"> </audio> What I want to know is how could I be able to get this path user@hostname:/file/path/from/remote/server I'm using Django with Python. Thanks a lot for anyone that could help! -
Reject null value
I have the model: class PotentialUser(models.Model): pass class Lead(models.Model): user = models.ForeignKey(to=User, null=True, unique=True) potential_user = models.ForeignKey(to=PotentialUser, null=True, unique=True) And I want to allow null in user field and in potential_user field but not allow null to both fields. How can I achieve it? I have only one idea, in the models set unique_together and create one lead with null user and null potential_user. But is there a better way? -
Is it possible to use pipenv for django-cookiecutter?
I know the docs specify virtualenv, but thought I would try: pipenv install -r path/to/local_requirements.txt It fails when trying to instal rcssmin==1.0.6 and rjsmin==1.0.12. It also tells me that I need to install Microsoft Visual C++ 14.0 but it's already installed on my system. I'm new to cookiecutter so these issues could be unrelated. Error message below. $ pipenv install -r requirements/local.txt Creating a virtualenv for this project... Pipfile: C:\Users\Jim Wombles\dev\PAMG\Pipfile Using c:\python36\python.exe (3.6.6) to create virtualenv... Already using interpreter c:\python36\python.exe Using base prefix 'c:\\python36' New python executable in C:\Users\JIMWOM~1\VIRTUA~1\PAMG-G~1\Scripts\python.exe Installing setuptools, pip, wheel...done. Setting project for PAMG-GBO_NxgA to C:\Users\Jim Wombles\dev\PAMG Virtualenv location: C:\Users\Jim Wombles\.virtualenvs\PAMG-GBO_NxgA Creating a Pipfile for this project... Requirements file provided! Importing into Pipfile... Pipfile.lock not found, creating... Locking [dev-packages] dependencies... Locking [packages] dependencies... Updated Pipfile.lock (582bd7)! Installing dependencies from Pipfile.lock (582bd7)... An error occurred while installing rcssmin==1.0.6! Will try again. An error occurred while installing rjsmin==1.0.12! Will try again. ================================ 83/83 - 00:01:04 Installing initially failed dependencies... Collecting rcssmin==1.0.6 ----------- 0/2 - 00:00:00 Using cached https://files.pythonhosted.org/packages/e2/5f/852be8aa80d1c24de9b030cdb6532bc7e7a1c8461554f6edbe14335ba890/rcssmin-1.0.6.tar.gz Building wheels for collected packages: rcssmin Running setup.py bdist_wheel for rcssmin: started Running setup.py bdist_wheel for rcssmin: finished with status 'error' Complete output from command c:\users\jimwom~1\virtua~1\pamg-g~1\scripts\python.exe -u -c "import setuptools, … -
How to make a django model "commentable" using django-threadedcomments
I am using Django 2.0.8 and Python 3.5 for a project. I have different models in my project, some of which, I want to allow commenting on. I am using the threaded comments django app to provide commenting functionality. Assuming I have a model Foo (see below): from django.db import models from django.conf import settings class Foo(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, null=False, default=1, on_delete = models.PROTECT) # ... How could I use mixins (or any other mechanism for that matter), to make the object Foo "commentable" (i.e. an object which can be commented upon?). To clarify, I am aware that a simplistic/trivial way to do this would be: Create a CommentType class Add a comment field (FK to Comment class) to object Foo Add a comment type field (FK to CommentType class) to object Foo However, I don't want to go down that particular route for reasons that should be obvious. I prefer to go down the OOP route. -
Best way to create 'optional' models in a Django reusable app
I'm trying to create a reusable app where I define some abstract models, and some concrete versions of those models that the user can use if they don't want to inherit the models themselves. If the user does want to create their own subclasses then I don't want Django to create these concrete models. This is the solution I have at the moment: myapp/abstract.py class AbstractModel1: class Meta: abstract = True field1 = models.CharField(max_length=255) class AbstractModel2: class Meta: abstract = True field1 = models.CharField(max_length=255) field2 = models.ForeignKey(getattr(settings, 'ABSTRACTMODEL1_OVERRIDE', 'myapp.ConcreteModel1')) myapp/models.py if not hasattr(settings, 'ABSTRACTMODEL1_OVERRIDE'): class ConcreteModel1: pass if not hasattr(settings, 'ABSTRACTMODEL2_OVERRIDE'): class ConcreteModel2: pass Then in the user's app, they can either use the concrete models as provided, or if not then they can create their own subclasses of the model like so: userapp/models.py class CustomModel1(AbstractModel1): extrafield1 = models.CharField(max_length=255) userapp/settings.py ABSTRACTMODEL1_OVERRIDE = "userapp.CustomModel1" Is this the best way to achieve this? Am I setting myself up for difficulties when trying to migrate changes in the subclassed models? What if the user wants to use the provided concrete classes first then migrate to a custom class? -
How to validate a raw html form in django
Hi! Im trying validate a custom made html form. I can save the form very easily , and i can also validate it, but on a very shitty way: class signup(View): def post(self, request, *args, **kwargs): name = request.POST['name'] email = request.POST['email'] age = request.POST['age'] password = request.POST['password'] name_splitter = name.split(' ') name_counter = 0 for word in name_splitter: name_counter = name_counter + 1 if name_counter < 2: error = error + 14 # email --> if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email): error = error + 26 # password --> if not re.match(r"[A-Za-z0-9@#$%^&+=]{8,}", password): error = error + 52 if error != 0: return redirect('/opret?e=' + str(error)) else: user = User(name=name, email=email, age=age, password=password) print(user) user.save() # Start session --> return redirect('/') So is there a way i can create another function, and validate it this way? Best regards a very frustrated boy -
What is the best way to set up a mail server alongside with a Django app?
I have a Django application running on a dedicated server where users log in and do their stuff. Now, I want to set up a mail server in this machine that can be used to send/receive mail and I am wondering what is the best way to do so. I have set up a mail server using rainloop client in a different machine and it is similar to what I want to achieve. Still, I have been reading Django docs on this topic and there seems not to be anything similar... So, I'm wondering what is the best way to set up a webmail client to be used through a Django app? Is there a way where I can set rainloop for example and set up a link that gets you to the client from Django? Or is there any way to set it directly on Django? -
Getting selected record and Outparameter Message from Stored Procedure in Python?
I have a Models.py which call the Mysql Stored Procedure. like this. def get_preschedule_fet(self): cursor = connection.cursor() parameters = (self.action, self.employee_gid, self.date, self.create_by, 1, '') cursor.callproc('sp_FETSchedule_Get', parameters) columns = [x[0] for x in cursor.description] rows = cursor.fetchall() cursor.execute('select @sp_FETSchedule_Get_5') out_put = cursor.fetchone() rows = list(rows) df_preschedule = pd.DataFrame(rows, columns=columns) dd = df_preschedule.loc[df_preschedule['schedule_employee_gid'] == pd.to_numeric(self.employee_gid)] return dd,out_put But I did not get the out_put Message and i get the selected data's. Plz help how to access both the Record via Fetch all and fetch one? I am Using Django and Mysql Stored Procedure. -
Getting every object from a formset, even those not modified
I am working with an inline formset of products associated with a shipment. When modifying the products associated, I encounter a little problem. The shipment needs to have the total amount of products and the total value of all the products. This is not a problem when creating a shipment, but when I try to modify it, I can't seem to find a way to access all of the items available in the formset, only those who are changed/new and those deleted. Anyone know of a way? this is the shipment model class ddt_in(models.Model): class Meta: verbose_name = 'Bolla In' verbose_name_plural = 'Bolle In' data = models.DateField() numero = models.CharField(max_length=50) fornitore= models.ForeignKey(laboratori,on_delete=models.CASCADE) quantita = models.IntegerField(null=True, blank=True, default=0) importo = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) doc_filename = models.FileField('File',upload_to="uploads/ddt_in/", blank=True, null=True) def __str__(self): return self.id this is the item model class ddt_in_item(models.Model): class Meta: verbose_name = 'Bolla In Items' verbose_name_plural = 'Bolle In Items' ddt = models.ForeignKey(ddt_in,on_delete=models.CASCADE, null=True, blank=True) prodotti_var = models.ForeignKey(prodotti,on_delete=models.CASCADE, null=True, blank=True,verbose_name='Prodotto') quantita = models.IntegerField('Q.tà') costo_acquisto = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) iva = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) scade = models.DateField(null=True, blank=True) def __str__(self): return self.id And this is the view: if request.method == 'POST': formset = ItemFormset(request.POST, instance=ddt_instance) ddt_form = Ddt_inForm(request.POST, … -
ngnix static files are not loading - django
I am trying to deploy my django project to AWS EC2, every thing is fine except static files, my static and media files are not loading. Here is my ngnix conf: upstream sample_project_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/home/ubuntu/django_env/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name <my public IP>; client_max_body_size 4G; access_log /home/ubuntu/logs/nginx-access.log; error_log /home/ubuntu/logs/nginx-error.log; location /static/ { alias /home/ubuntu/bingle/static/; } location /media/ { alias /home/ubuntu/bingle/media/; } location / { # an HTTP header important enough to have its own Wikipedia entry: # http://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # enable this if and only if you use HTTPS, this helps Rack # set the proper protocol for doing redirects: # proxy_set_header X-Forwarded-Proto https; # pass the Host: header from the client right along so redirects # can be set properly within the Rack application proxy_set_header Host $http_host; # we don't want nginx trying to do something clever with # redirects, we set the Host: header above already. proxy_redirect off; # set "proxy_buffering off" *only* for Rainbows! when doing # Comet/long-poll stuff. It's … -
Modify data before render template in Django
What I need to do it's just replace some items from model before render. So just in each business.address replace '||' with ", ". I'm trying to do like that: def category(request, q): businesses = Business.objects.filter(category_string__icontains=q)[:50] for b in businesses: if '||' in b.address: b.address.replace('||', ', ') print(b.address) But I still see the same string without replacing. What's the reason? -
How do I configure Django to look at the correct Sass installation?
I've taken over a project and I'm having some difficulty getting the server running. I'm getting the error: 'module' object has no attribute 'compile' When I go into a shell: >>> from django_libsass import SassCompiler >>> import sass <module 'sass' from '/home/.../venv/local/lib/python2.7/site-packages/sass.so'> >>> print sass.compile(string='a { b { color: blue; } }') Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'module' object has no attribute 'compile' pip freeze reports that the following are installed: libsass==0.13.5 django-libsass==0.7 sass==2.3 which sass shows /usr/bin/sass which is version 3.4.21. I take it it might be an issue with my settings. Nothing explicitly sets any paths but I do have this: STATIC_PRECOMPILER_COMPILERS = ( ('static_precompiler.compilers.libsass.SCSS', { "sourcemap_enabled": True, "load_paths": ["/path"], "precision": 8, }), ('static_precompiler.compilers.libsass.SASS', { "sourcemap_enabled": True, "load_paths": ["/path"], "precision": 8, }), ) -
How do a change a dynamic localhost port?
Mismatch I am currently testing my website on a local webserver. The localhost port localhost:[port] keeps changing everytime I run the python3 manage.py unittest. As a result of the localhost:port changing on every test, it cannot match the url [localhost:'port'] with the redirect url that I have entered in the Oauth credentials. How am I able to run my unittests and have the browser use a certain port every time? I'm currently following the taskbuster django tutorial http://www.marinamele.com/user-authentication-with-google-using-django-allauth taskbuster If you scroll down on that page to the following section "indicating that the redirect URI at http://localhost:8081 is not valid. This is because we registered a different url, http://127.0.0.1:8000, and not the one that is used by tests." Then my problem will become apparent. To summarise 1.I've registed the callback url to be http:127.0.0.1:8081 Everytime I run the unit test, the web server runs on the follwoing 'http:127.0.0.1:53000' or a variant of that number. How do I get the test to run on a designated port. -
Django - Usage of inline JS with Hidden Form Best Practices?
I'm currently learning Django and bought an online course. In this course the lector uses the code as following: <div class="col-4"> <a href="javascript:{document.getElementById('upvote').submit()}"><button class="btn btn-primary btn-large btn-block "><span class="oi oi-caret-top"></span>Upvote: {{ product.votes_total }}</button> </a> </div> And then what he triggers is: <form id="upvote" method="post" action="{% url 'upvote' product.id %}"> {% csrf_token %} <input type="hidden" > That somehow feels not right for me. Is this a "best practice" approach?