Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Migrate django models to an MySQL read-only database?
I'm completely new to the Django development. In my work, My manager has given me a task of migrating the existing Models of my Django projects to a Read-only Database of MySQL server. additional details - 1) I have created a User in MySQL with read only privileges. Kindly help me in solving this problem. Thanks in advance. -
Django admin-site redirect if ValidationError during saving
my question is about saving new object in admin-site in Django. i dont want to raise error if user with email already exist, but i want to directly redirect to admin/edit page.. and edit that user i tried to rewrite clean method in form, but that was not right i think. i have a model like: class Users(models.Model): first_name = models.CharField(max_length=30) email = models.EmailField(unique=True) ... My form: class UserForm(forms.ModelForm): class Meta: model = Users admin: class UserAdmin(admin.ModelAdmin): form = UserForm Is there a way to do that? -
Django & timezone, beginning of the day : should I make_aware() in my function one or two times?
I have a simple function that returns the beginning of the day in Django (by default, today's day) : import datetime from django.utils.timezone import make_aware def DayBeginning(DateTime="Now"): if DateTime == "Now": DateTime = make_aware(datetime.datetime.today()) year = DateTime.year month = DateTime.month day = DateTime.day return make_aware(datetime(year, month, day, 0, 0, 0, 0)) I am afraid that if I call "make_aware" two times, I might offset the result. Did I do it right or not ? (my timezone is 'Europe/Paris') PS : Feel free to criticize my code, I am a newbie developer -
Why use media url for image uploads by user?
I am new to django, while learning about Handling Media Files in Django, I have read that we use media files configuration concept. Now while making a model I have designed my class with variable img=models.ImageField(upload_to='pics' ) When I have already mentioned that I have to upload images in pics folder, so why we are using media files configuration -
How to load multiple different page templates using a single view
I have a standard view and url in my Django project: views.py def app(request): template = loader.get_template('index.html') return HttpResponse(template.render(context, request)) urls.py: urlpatterns = [ path('', views.app, name='app'), ] I have c.50 additional page templates that I would like to serve from the /app/ directory. E.g. 'app/page1.html', 'app/page2.html', etc. Each of these templates is a basic .html file with no special functions, ie. they don't need individual context or other processing in views.py I know I can create 49 more entries in views.py and urls.py to define the reference to each of these templates, but is there a quicker way to load the them without going through this? For example, in pseudocode is there a wrapper I can put in the view so that '/app?page=page2.html' loads page2.html and avoids a new view.py and urls.py entry? -
pyodbc is not working with django 1.2.4 in Ubuntu machine
I am working on django project which is running with MySQL smoothly but I want to use MSSQL instead of MySQL.I have installed some packages such as pymssql,pyodbc and django-mssql etc. but failed. I got the following error: sqlalchemy.exc.DBAPIError: (Error) ('01000', u"[01000] [unixODBC][Driver Manager]Can't open lib 'SQL Server' : file not found (0) (SQLDriverConnect)") None None Django==1.2.4 sqlalchemy==0.6.6 x -
Multiple Search Fields not working as expected
I have 3 search field(event_name, event_loc, event_date), while one of them filled it return all table data, while it has to be return one. views.py def searchEvent(request): if request.is_ajax(): q_event_name = request.POST.get('event_name') q_event_loc = request.POST.get('event_loc') q_event_date = request.POST.get('event_date') # return JsonResponse(dict(events=list(Event.objects.values('name', 'info')))) return JsonResponse( serializers.serialize('json', Event.objects.filter( Q(name__icontains=q_event_name) | Q(info__icontains=q_event_loc) | Q(start_event_dt__icontains=q_event_date))), safe=False) custom.js $.ajax({ url: '/searchevent/', data: { 'event_name': event_name, 'event_loc': event_loc, 'event_date': event_date }, dataType: 'json', type: 'POST', success: function (data) { data = JSON.parse(data); event_html = ''; for(var i in data){ event_name = data[0]['fields']['name']; event_html = event_html + '<div class="col-md-4">' + ' <h5 class="card-title text-center pt-3">' + event_name + '</h5>' + '</div>'; } document.getElementById("event-container").innerHTML = event_html; } }); for example, I have two event in my DB name=aaa, loc=bbb, date=2019-01-01 name=ccc, loc=ddd, date=2018-01-01 in the search bar when I searched for only name field with aaa, it returns all of the two event, which i expected to return me only first event. -
how to save selectMultiple in django
i Try to save a multiplechoicefield in my database. but when I save it's only one item who are saved models.py class Reservation( models.Model): date_de_reservation = models.DateTimeField('Date de reservation', auto_now = True) type_enseignement = models.CharField('Type enseignement', max_length = 10, choices = (("cm", "CM"), ("td", "TD"), ("tp", "TP"), ("tc","TC")), ) date_du_jour_reserve = models.DateField("Date du jour reservé") plage_horaire = models.ForeignKey("Plage_Horaire", on_delete = models.CASCADE ) cours = models.ForeignKey(Cours, on_delete = models.CASCADE) enseignant = models.ForeignKey(Enseignant, on_delete = models.CASCADE) sallecours = models.ForeignKey(SalleCours, on_delete = models.CASCADE, blank = True, null = True) option = models.ForeignKey(Option,on_delete = models.CASCADE ) valide = models.BooleanField(blank = True, default = False) analyse = models.BooleanField(blank = True , default =False ) class Plage_Horaire(models.Model): debut = models.TimeField("Heure de début", unique = True) fin = models.TimeField("Heure de fin", unique = True) def __str__(self): return "{0}--{1}".format(self.debut, self.fin) forms.py class Reservation_Form(forms.ModelForm): faculte=forms.ModelChoiceField(label="Faculte", queryset=Faculte.objects.all()) departement=forms.ModelChoiceField(label="Département", queryset=Departement.objects.all()) filiere=forms.ModelChoiceField(label="Filière", queryset=Filiere.objects.all()) niveau = forms.ModelChoiceField(label = 'Niveau', queryset = Niveau.objects.all() ) option=forms.ModelChoiceField(label="Option", queryset=Option.objects.all()) semestre=forms.ModelChoiceField(label='Semestre', queryset=Semestre.objects.all()) plage_horaire = forms.ModelMultipleChoiceField(label="", queryset = Plage_Horaire.objects.all()) views.py -
How to get the full file path of the browsed file in Django
I have a browse control in Django application, which is reading only the file of the browsed file.What I required is full file path of the browsed file. I have tried the different attributes for the browse control and its not working. To read the text of file control: request.POST["BrowseControlName"] It was returning the only file name not the absolute file path -
Passing the error message on web page using django
how can i pass the Error exception messages onto the webpage. I m using Atom text editor and django views.py try: netconnect = ConnectHandler(**devices) except (AuthenticationException): re = print ('Authentication failed ' + ipInsert) return render(request,'first_app/forms.html', {'form': form, 'reprinting':re}) pass forms.html {% if request.POST %} <pre>{{ reprinting }}</pre> {% endif %} its priting None rather then printing the error message in code. NOTE:-although the described error message is printing on command line in text editor for full code refer the link : full code -
Having issues with getting my back-end data to the front-end (Django)
I am creating a blog in which I need a comment section(first project ever, 3 weeks into Python/Django). So far I've created 2 models(Blog which is the main and Comment which is linked with a foreign key to the Blog) but for some reason, I can't find the proper way to display the information from the Comment model into my HTML section. I've tried with dictionaries, rewrote the models and the views multiple times(due to different youtube videos that I found) but nothing seems to work properly. These are my models : class Blog(models.Model): title = models.CharField('Blog\'s title', max_length=100, blank=False) slug = models.SlugField('Enter your blog\'s url', blank=False) date = models.DateTimeField('Date and time on publication', blank=False) content = models.TextField(blank=False) thumb = models.ImageField(blank=True, null=True, default='default_blog_icon.jpg') def __str__(self): return self.title def snippet(self): return self.content[:50] + ' ' +'...' class Comment(models.Model): post = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comments') user = models.CharField(max_length=200) body = models.TextField(max_length=200) created = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) def approved(self): self.approved = True self.save() def __str__(self): return self.user The views : def index(request): blogs = Blog.objects.all().order_by('-date') comments = Comment.objects.all() args = {'blogs': blogs, 'comments': comments} return render(request, "blog/index.html", args) def blog_details(request, slug): slug_url = Blog.objects.get(slug=slug) return render(request, 'blog/blog_details.html', {'blog_info': slug_url}) And the HTML : … -
Is there a type of request to a server, to enable overriding content?
So, I am building a website using "angular 8" and I want to make a request to the server, such that i can override a text field in the database. I want the admin to be able to override some of the content of the text fields in the server. When i make a "put" request to the server, what happens is that it doesn't override the content, rather it just adds to it and I am not sure exactly how to override it. With what sort of a request or etc.. Thank you in advance if you need further information, please specify and I will provide everything. -
How to create a custom function inside django model?
I have a django model class UserInfluencerGroupList(models.Model): list_name = models.CharField(max_length=255) influencers = models.ManyToManyField(Influencer, blank=True) user = models.ForeignKey(MyUser, on_delete = models.CASCADE) def __str__(self): return self.list_name and my views function is: def get_lists(request,user_email): """Get all the lists made by user""" try: user_instance = MyUser.objects.get(email=user_email) except MyUser.DoesNotExist: return HttpResponse(json.dumps({'message':'User not found'}),status=404) if request.method == 'GET': influencers_list = UserInfluencerGroupList.objects.all().order_by('id').filter(user=user_instance) influencers_list = serializers.serialize('json',influencers_list, fields =['id','influencers','list_name'], indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True) return HttpResponse(influencers_list,content_type='application/json',status=200) else: return HttpResponse(json.dumps({'message':'No lists found'}), status=400) Apart from the usual data from list I also want to calculate the total_followers, total_likes and total_comments of each influencer in the list. The influencer model has fields for total_likes, comments and followers. How should I write a function to calculate and display it along with all the other data that the list is returning -
Tastypie annoate / groupby returns a "pk" error
When using django's annotate to get a "group by" it makes sense it returns objects without PK. As it wouldn't make sense to group by a field, sum up some other fields, and get single row PK IDs. I assume I'm doing this wrong in tastypie. But I couldn't see a way of doing group bys from the documentation. So I've added a queryparam "groupby" to my custom resource class. In the "apply_filters" I let tastypie do its usual thing, then I step in and apply a django "group by": return q.values('type').annotate(*(Sum(x) for x in fields_to_aggregate)).order_by() This returns a Queryset of objects, that only have "type" field, and the correctly summed up fields. The error I get from tastypie is: Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/tastypie/resources.py", line 228, in wrapper response = callback(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/tastypie/resources.py", line 468, in dispatch_list return self.dispatch('list', request, **kwargs) File "/usr/local/lib/python3.6/dist-packages/tastypie/resources.py", line 500, in dispatch response = method(request, **kwargs) File "/srv/attrib-backend/backend/api/utils.py", line 69, in get_list for obj in to_be_serialized[self._meta.collection_name] File "/srv/attrib-backend/backend/api/utils.py", line 69, in <listcomp> for obj in to_be_serialized[self._meta.collection_name] File "/srv/attrib-backend/backend/api/utils.py", line 114, in full_dehydrate data[field_name] = method(bundle) File "/usr/local/lib/python3.6/dist-packages/tastypie/resources.py", line 1093, in dehydrate_resource_uri return self.get_resource_uri(bundle) File "/usr/local/lib/python3.6/dist-packages/tastypie/resources.py", line 837, in get_resource_uri return … -
Django annotation
How can I count child objects in queryset? I have model: class SomeTree(Model): parent = ForeignKey('self', on_delete=SET_NULL) level = IntegerField(default=0) qs = SomeTree.objects.filter(level=0).annotate(childes_count=???) I need to count direct child objects for object. Is it possible in Django ORM? -
Can`t manually delete record from sqlite table, because related table with __old does not exists
I want to manually delete records from sqlite table(witch was created with Django 1.10, Table from i want to delete records called main.storage_claim, it has relation to main.storage_claimlist), but got error: Error deleting record: no such table: main.storage_claimlist__old. I dont know why it want this table. I have only main.storage_claimlist without __old. Btw, i`m using DB Browser for SQLite as gui tool for working with sqlite. Can someone explain what the heck is __old? -
in Celery/Django : cannot find reference 'control' in celery.task.control
I'm trying using celery in my project . when i use from celery.task.control import revoke the PyCharm highlight control and warn me cannot find reference 'control' in __init__.py and also PyCharm add broken line under revoke and warn me Unresolved reference revoke . but when i run project celery working great and not any problem with calling task or revoke them . my question is why PyCharm warn me and is it possible in future any problem happen about that? thank you. celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hamclassy.settings') app = Celery('hamclassy') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() project/init.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] -
how to decode ldap3 thumbnailPhoto to display it in template?
i'm trying to load a picture from active directory into a django template, the result from active directory is "b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00\x00\x00\x00\x00\x00\xff\xdb\x00C\x00\x02\x01\x01\x01\x01..." i've seen the php methode and tried to implement it using python with no success, i also tried the base64.decode, to save it in an image file and convert it using pil then load it, base64.decodebase64, i even tried to convert it using javascript and load it in src but all these methods didn't work, I've read a lot of articles but none helped me, it'll be nice to help me with it. -
How to create a one to many relationship which point from a table to the same table?
I have a table employees with employee_id as a primary key, some of the employees are managers and managers can also have managers. So I wanted to add a manager_id field to the table employees which is the employee_id of the manager of the employee. I tried to create a one to many relationship between the table and itself but without success. In the employees class I have added the following: id_manager = models.ForeignKey(employees, on_delete=models.PROTECT) NameError: name 'employees' is not defined I am pretty new to django, any idea how to code this? Thanks. -
How to pass and object using POST in django
I have the following template {% extends 'base.html' %} {% block content %} <div class="lista-libro"></div> <form method="GET"> {{ filter.form }} <button type="submit" class="btn btn-primary">Buscar</button> </form> <form action="s" method="POST"> {% csrf_token %} {% for libro in filter.qs %} <input type="radio" name="libro" value="{{libro}}" unchecked> {{libro.titulo}}<br> {% endfor %} <input type="submit" value="Agregar"> </form> </div> {% endblock content %} Libros is my app and libro is defined by the model: # libros/models.py class Libro(models.Model): titulo = models.TextField(default='Algebra', max_length=45) precio = models.SmallPositiveInteger() But I don't know how to pass it to another page I tried: #libros/views.py class Ventas2PageView(ListView): model = Libro template_name = 'ventas2.html' def libroVenta(request): current_user = request.user user_id = current_user.id try: libro_elegido = request.POST[libro.id] libro_precio = request.POST[libro.precio] except: pass else: context = {"libroId": libro_elegido, "userid": user_id, "libroPrecio": libro_elegido_precio} return HttpResponse(context) My urls file is urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('ventas/', VentasPageView.as_view(), name='ventas'), path('acerca/', AcercaPageView.as_view(), name='acerca'), path('ventas/s', Ventas2PageView.as_view(), name='ventas2'), ] What am I doing wrong. In my template ventas2.html I tried to access my data using context[something] but doesn't work. I don't really can interpret the errors given to me by the console. Could you guys help me. -
Django rest framework error on empty view: the response content must be rendered before it can be iterated over
I'm having a hard time finding the cause of this. I have a heartbeat view with token authentication, it just returns status=200 and I'm getting the response content must be rendered before it can be iterated over error. It's related to token authentication but for the life of me, I can't figure it out. urlpatterns = [ path('heartbeat/', views.HeartbeatView.as_view(), name='heartbeat')] class TokenAuthentication(authentication.BaseAuthentication): def authenticate(self, request): auth_token = request.META.get('HTTP_AUTHTOKEN') if not auth_token: return Response('No token', status=450) try: auth_token_inst = AuthToken.objects.select_related('user').get(token=auth_token) if not auth_token_inst: return Response('Not a valid token', status=451) if auth_token_inst.is_active is False: return Response('Expired token', status=452) user = auth_token_inst.user auth_token_inst.ExtendExpireDate() except AuthToken.DoesNotExist: return Response('No token', status=450) return (user, None) class HeartbeatView(APIView): authentication_classes = (TokenAuthentication,) def get(self, request): """ Update token with heartbeat """ return HttpResponse(status=200) [15/Jul/2019 07:10:31] ERROR [django.request:228] Internal Server Error: /heartbeat/ Traceback (most recent call last): File "/home/ubuntu/virtenv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ubuntu/virtenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/virtenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/virtenv/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ubuntu/virtenv/lib/python3.5/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/ubuntu/virtenv/lib/python3.5/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/home/ubuntu/virtenv/lib/python3.5/site-packages/rest_framework/views.py", line 455, … -
How to overwrite get method in Django Rest Framework's API View
I am trying to build an API View that returns some data from my database depending on what I send as a request. I have a model BuildingGroup that has many buildings which have many cool and heat objects. These heat and cool objects have a year and a value. When I send a specific year I want to list all of the heat/cool values of that year in that BuildingGroup. I think it should be simple, but I don't know if I am going into the right direction. I am trying to overwrite the get method of Django's APIView like so: class BuildingGroupYearHeatObjects(APIView): def get(self, request, pk): data = request.data year = request.data['year'] ...here should go more code..... return Response(year) I get a key error here: KeyError: 'year' My url path('demand/heat/<int:pk>/',BuildingGroupYearHeatObjects.as_view(), my request: def test_api_local(method='post', data={}): payload = { 'id' : '1', 'year' : 2022 } r = requests.request(method, APP_ENDPOINT , json=payload) print(r.text) return r test_api_local(method='get', data={ 'id' : 1, 'year' : 2022}) So my question is if I actually going the right way and also why do I get a key error? I only get the key error when I refresh the API view in the browser. But … -
Django Database design improvement
i have designed an application that has an abstract base class that describes a generic device with some common fields (Name, Date, etc...) and many inherited classes that describes the protocol and the properties of them, like: SNMP (Community, auth, etc...) HTTP (endpoint, etc...) In addition i have many tables that contains the data collected over those described protocol and references the parent device, like below: SNMP_detections (id, collected_data, datetime, parent_obj [FK to SNMP]) HTTP_detections (id, collected_data, datetime, parent_obj [FK to HTTP]) So, i was thinking about optimize the current database layout, specially the measurement tables, i'm interested in how i can use only a single table and reference from there the parent device (that can be HTTP or SNMP)... Any suggestion? -
NoReverseMatch: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name
I use the built-in module in Django for tracking with user forgot password I learned tutorial Django was 1.8 and I am with 2.2 now. I try to use that module but it not working from django.contrib.auth.views import ( PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView ) urlpatterns = [ url(r'^change-password/$', views.change_password, name='change_password'), url(r'^reset-password/$', PasswordResetView.as_view(), name='reset_password'), url(r'reset-password/done', PasswordResetDoneView.as_view(), name='password_reset_done'), url(r'reset-password/confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url(r'reset-password/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] Exception Value: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Exception Type: NoReverseMatch -
python/Django syntax error in Exception handling
In the code below i m getting syatax error in Error handling statements' i m using ATOM text editor. django for web interface and netmiko libaray for my backend code. from django.shortcuts import render from first_app.forms import CmdForm from django.http import HttpResponse from netmiko import ConnectHandler from netmiko.ssh_exception import NetMikoTimeoutException from paramiko.ssh_exception import SSHException from netmiko.ssh_exception import AuthenticationException import datetime, time, sys #some code here# cmd = request.POST.get('command', '') try: netconnect = ConnectHandler(**devices) Exception(AuthenticationException): print ('Authentication failed' + ipInsert) continue getIP = netconnect.send_command(ipInsert) Error File "K:\Work\DevNet\first_project\first_app\views.py", line 31 Exception(AuthenticationException): ^ SyntaxError: invalid syntax thanx for the help