Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django audit log user media file access
I would like to be able to capture an audit log in my database of media file access (download) by users. I'm new to Django so at a loss as to where to start looking at for this, or if this is even possible? Has anyone had any experience or have an ideas they can share as to possible ways I can look into achieving this? -
How to use a django web application as a widget?
I am developing a feedback system using django framework. I want to use this app as a widget for any other website. (Pretty much similar to 'disqus' comment system widget). How can I change my django web app to a ready-to-use widget? -
Django DeleteView not finding DB Object
My DeleteView Post is returning a Page not found (404) error. It isn't clear to me why. #url.py path('<int:pk>/<int:yr>/<int:id>/deleteit/', views.DeleteIt.as_view(), name='delete-it'), #view.py class DeleteIt(DeleteView): model = MyModel def get_success_url(self): client_id = self.object.client_id year_id = self.object.year_id return reverse_lazy('itemview', kwargs = {'pk': client_id, 'yr': year_id}) #templates - - POSTing tempalte <form action="{% url 'delete-it' pk=url_pk yr=url_yr id=item_id %}" method="post" style="display: inline;"> [The pk and yr keys are from a context generator.] So, when I make the post request from my template the URL is http://127.0.0.1:8000/MyApp/1/1/3/deleteit/ The URL is /pk/yr/id/ where id is the id of the MyModel object in the database. The object exists and it has all the right keys. When I make the POST the object isn't deleted (which I believe is a result of not having a successful url call for the delete. There is no error trace - but the console says: [23/May/2018 22:53:32] "GET /MyApp/1/1/ HTTP/1.1" 200 13946 Not Found: /MyApp/1/1/3/deleteit/ [23/May/2018 22:55:10] "POST /MyApp/1/1/3/deleteit/ HTTP/1.1" 404 1797 My understanding is that the get_success_url isn't called because the error is thrown. The DeleteView seems very straight forward - so not sure how it is coded wrong. Any thoughts would be appreciated. -
what does on_delete=models.PROTECT and on_delete=models.CASCADE do on Django models?
I'm quite familiar with Django, but recently noticed there exists a on_delete=models.CASCADE and on_delete=models.PROTECT option with the models, on_delete=models.CASCADE and on_delete=models.PROTECT both are doing same things. Or both are same (I used the only on_delete=models.CASCADE, When I remove the parent entry it will remove all related entries ) I have searched for the documentation for the same but couldn't find anything more than, Django 2.0 A many-to-one relationship. Requires two positional arguments: the class to which the model is related and the on_delete option. To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self', on_delete=models.CASCADE). -
How to work with characters encoding in a Django project?
I'm working in a Django Project and I get a mess when I have to work with different encodings. Is not there a way to work without having to worry about this? I try to fix it by putting unicode(), but this does not always work... and I have to put it in all my functions. That's awful! :( I do not have any experience about this and I'm just looking for some advice that can help me. Normally the problems are with accents and the Spanish letter 'ñ'. Thank you very much. Python: 2.7 Django: 1.8 -
python- Related Object Does Not Exist at /admin/login/
I'm having a problem logging into my localhost:8000/admin/ page, after entering the correct username and password, I get the "Related Object Does Not Exist at /admin/login/" error and it says the "User does not exist" but it being the admin is my main cause for worry. I removed the "django.contrib.sites" package following advice I got on a previous error. I'm using django 2.0.2 and python 3.6. settings.py: # Application definition INSTALLED_APPS = [ 'nutrients.apps.NutrientsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'profile', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'nutrition.urls' CMS_TEMPLATES = ('index.html', 'Left sidebar template') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(__file__), 'templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'nutrition.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } any help on this would be appreciated. -
Django model design choices
Django database question: Is it better to have one extended Model or go on the Parent- Children architecture? Example: Say i want to make a Pet Model with the following fields: id name owner And i would have 10 or 20 kinds of pets, like: fish,dog, cat each of them having specific fields (nr of fins for fish, etc.) Is there a common practice in Django? Do we make one model with all fields and simply fill n/a where not applicable or do we make one parent model = Pet and several children models such as fish, cat etc? I'm also asking this in conjuction to generic class based forms and how easy it would be to create/update/delete this objects - when having 10 such children, can you dynamically create generic forms? -
User Activity Logging
I want to track all user activities on my web page like scrolls, button clicks etc. The main code is in Django. Which libraries should I use to track these events? -
save data after validation in django
Story is: User can attach some tags to an article< so two model created. one for articles and one for tags. class tag(models.Model): title = models.CharFiled(max_length=50) class article(models.Model): title = models.CharField(max_length=200) body = models.TextField() tags = models.ManyToMany(tag) So in the form a multiple input is showen that it's choice is tags that previously saved in database. with javascript we can chamge this input to accept new tags and send them aside selected previous tags to the ClassView but these new tags will not be saved and KeyError and ValidationError occured. Need is an input that accept previous and new tags and assign to current article when form submited. consdier that we can override methods of django's classes. Note: New tags must be save if only and only form validation is true and if other field in form such as title of article is not valid, these new tags should not be saved. Example: tags input in new question form in stackoverflow: https://stackoverflow.com/questions/ask -
Django on IIS (Internal Server Error)
HTTP Error 500.0 - Internal Server Error C:\Python34\python.exe - The FastCGI process exited unexpectedly This is the error im getting.. im using python 3.4.2 but for some reason it still doesnt work I was following a youtube video and did everything exactly the way he did it.. Anyone got any idea as to what is going on? -
Django datepicker
I have a django app that i want to use a datepicker on a field. I have used jquery before on one of my app on an older version of django 1.7 and it works pretty well. Now i am building another django app using django version 1.11. For some reason the datepicker is not working. Below is my code appreciate any assistances <!--forms.py--> class ContactForm(forms.ModelForm): class Meta: model =contacts fields = ('First_Name','Middle_Name','Last_Name','Date_of_Birth') <!--views.py--> def addcontact(request): if request.method=='POST': form =ContactForm(request.POST) if form.is_valid(): form.save(commit=False) form.save() return HttpResponse('You have Successfuly added a contact') else: form =ContactForm() return render(request,'new_member.html',{'form':form}) <!--template--> <head> <meta charset="utf-8" /> <!--time picker--> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <link rel="stylesheet" href="/resources/demos/style.css" /> <script> $(function() { $('#id_Date_of_Birth).datepicker(); }); </script> <!--end time picker--> </head> <body> {%extends 'dashboard.html'%} {%block content%} <div class="card"> <form method="post" action=""> {% csrf_token %} <table> {{form.as_table}} </table> <button type="button submit" class="btn btn-success">Add Member</button> </form> </div> {%endblock%} </body> -
How do I save user specific quiz answers in django models?
I am having the following Quiz model:- class Quiz(models.Model): quiz_name = models.CharField(max_length=200) def __unicode__(self): return self.quiz_name Each Quiz model has a set of Questions and each Question has set of related possible answers. The question also has a correct answer field. Following are the models for questions and answers:- Answer Model:- class Answer_Options(models.Model): text = models.CharField(max_length=200) def __unicode__(self): return self.text Question Model:- class Quiz_Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions') text = models.CharField(max_length=200) possible_answers = models.ManyToManyField(Answer_Options) correct = models.ForeignKey(Answer_Options, related_name="correct", default=None, on_delete=models.CASCADE) def __unicode__(self): return self.text Now the problem that I am facing is that how can I save which user has selected which option? Is there a way to do so? -
Django Forms not loading
I have tried numerous things. At one point my forms were loading and now they are't. I get the page to load, but the forms simply don't appear, the page is just my layout.html. urls.py url(r'^profile/passreset/$', views.passwordReset, name='passwordReset') views.py def passwordReset(request): if request.method == 'POST': form = PasswordChangeForm(request.POST, user=request.user) if form.is_valid(): form.save() return rediect('/account') else: form = PasswordChangeForm(user=request.user) return render(request, 'posts/accounts/changepass.html', {'form': form}) changepass.html {% extends 'posts/layout.html' %} {% block head %} <title>Change Password</title> {% endblock %} {% block content %} <div class="containter"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> </div> {% endblock %} -
Running Django in Hy
I'm writing a Django webserver using Hy, a Lisp dialect that compiles into Python bytecode. I have been able to write everything in Hy except for specific .py files that Django looks up automatically. myproject/settings.py myproject/urls.py app/management/commands/my_management_command.py I would like to write the above files in Hy too, instead of Python. I can work around this limitation by using these .py files to import .hy files, but I'd prefer a more elegant solution. Is there a way I can get Django to look for .hy files instead of these .py files? -
How can I filter whether a list contains the param?
How can I filter whether a list contains the param? In my Django-Rest-Framework project, I list the physical_server: [ { "id": 23, "name": 'A1' "ipv4s": [ { "id": 313, "ip": "43.243.33.33", "netmask": "255.255.255.248", "prefix": 29, "is_gateway": false, "is_network_ip": false, "is_broadcast_ip": false, "desc": null, "ctime": "2018-04-26T21:17:34.868492+08:00", "uptime": "2018-05-21T12:09:25.674283+08:00", .... this is my list API view : class PhysicalServerListAPIView(ListAPIView): serializer_class = PhysicalServerListSerializer permission_classes = [AllowAny] pagination_class = CommonPagination def get_queryset(self): query_params = self.request.query_params ip_address = '' try: ip_address = query_params.pop('ip_address') # this maybe `43.243.33.33` except Exception as e: pass qs = PhysicalServer.objects.filter(xxxx) # there I want the ip_address filtered if it in the `ipv4s`. return qs How can I realize this filter? because it is not the physicalserver's property. I can not use filter(name='xxx') to do that. -
Trying to save POST data CLASS NAME in STUDENT model (foreign key)?
I am trying to displaying classes in a form on a page. when enrol button is clicked i get the class name and assign it to student model (which has a foreign key to the class model).. ERROR: local variable 'StudentProfile' referenced before assignment New to django I have no idea what I'm doing, please help! My Attempt, what's the issue? models.py class StudentProfile(models.Model): user = models.OneToOneField('Accounts', related_name='student_profile') student_class = models.ForeignKey(to=MusicClass, related_name="student_class", null=True, blank=True) is_student = models.BooleanField('student status', default=True) # more fields class MusicClass(models.Model): class_name = models.CharField(max_length=500, blank=True) # more fields views.py # enrolls student def studentEnrol(request): if request.method == "POST": musicClass = request.POST.get('musicClass', '') StudentProfile = StudentProfile(student_class=musicClass) StudentProfile.save() return HttpResponseRedirect('/') else: querySet = MusicClass.objects.all() args = {'classes': querySet } return render(request, 'accounts/enrol.html', args) forms.py class MusicClassesEnrolForm(forms.ModelForm): class Meta: model = MusicClass fields = ('class_name', 'class_level', 'class_time', 'class_room', 'instrument_taught', 'day', 'teacher') enrol.html {% extends 'base.html' %} {% block body %} <div class="outer"><div class="container"> <h1> Enrol into Class </h1> <table style="width:100%"> <tr> <th>Class Name</th> <th>Instrument</th> <th>Class Level</th> <th>Time</th> <th>Teacher</th> <th>Room</th> <th>Register</th> </tr><br> {% for class in classes %} <tr> <td>{{ class.class_name }}</td> <td>{{ class.instrument_taught }}</td> <td>{{ class.class_level }}</td> <td>{{ class.class_time }}</td> <td>{{ class.teacher }}</td> <td>{{ class.class_room }}</td> <td><form method="post"> {% csrf_token … -
How to get server ip address when one server sends get request to another django server?
I have two servers, one is asp.net and another one is django. So our asp server must send get request to django server, so problem is when asp server sends get request to django server, django server needs to check whether asp server's ip address is correct. So problem is how to get asp server ip address in django server? I tried REMOTE_ADDR and HTTP_X_FORWARDED_FOR in django, but it gives me wrong ip address. Guys please help me. -
Django takes care of `form` from `Field`
I am puzzled over the choices in models field in the following code: class Block(models.Model STATUS = ( (0, 'normal'), (-1, 'deleted'), ) name = models.CharField("block name", max_length=100) desc = models.CharField("block description", max_length=100) admin = models.CharField("block admin", max_length=100) status = models.IntegerField(choices=STATUS) def __str__(self): return self.name Reference to choices=STATUS, I read from offical docs that Django utilize a form widget to handle the 2-tuples, In the particular case, it send 0 -1 to database and issue normal deleted to template: <select name="status"> <option value=0>normal</option> <option value=-1>deleted</option> </select> It's amazing but confused. How could Django take care of form from Field -
Python Django css not loading with huge error in console
I'm making a Django site and the code seems fine, but I get this very long error whenever I load the site from my browser: [23/May/2018 21:01:20] "GET / HTTP/1.1" 200 1840 Traceback (most recent call last): File "/usr/local/lib/python3.6/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/runner/.site- packages/django/contrib/staticfiles/handlers.py", line 67, in __call__ return super().__call__(environ, start_response) File "/home/runner/.site-packages/django/core/handlers/wsgi.py", line 146, in __call__ response = self.get_response(request) File "/home/runner/.site- packages/django/contrib/staticfiles/handlers.py", line 62, in get_response return super().get_response(request) File "/home/runner/.site-packages/django/core/handlers/base.py", line 81, in get_response response = self._middleware_chain(request) TypeError: 'NoneType' object is not callable [23/May/2018 21:01:20] "GET /static/style.css HTTP/1.1" 500 59 I have absolutely no idea what this is supposed to mean, but it loads just find when I use in my HTML. Whenever I use my static folder and a separate CSS file, this pops up. This is my base HTML file (Sorry for the bad indent when copy pasting): {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>&lt; &lt; LambCentral &gt; &gt;</title> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" type="text/css" href="{% static "/style.css" %}"> </head> <body> <div class="maintitle"> <center><h1>LambCentral</h1></center> </div> <br> {% block content %}{% endblock content %} <div class="bottom"> <center> <h2> LambCentral </h2> <h4> Satisfy Curiosity </h4> … -
How about this 20MB json response performance?
I have a API build in django, it goes to query data with PostgreSQL and serializer to json. Now, this API content-length is 3MB (I use the gzip, the truely size is 20MB) response time cost me about 10~20 seconds. I want to ask, Is this performance is right? there is any optimization space that I can do? -
Both `name="button"` and `name="submit" work properly in the form
When working in Django, Both name="button" and name="submit" work properly when I submit the form {% buttons %} <button name="button" class='btn btn-primary'>Save</button> {% endbuttons%} {% buttons %} <button name="submit" class='btn btn-primary'>Save</button> {% endbuttons%} What's the difference between button and submit -
Register Page instantly buffering
When I tried to register in my site, it's instantly buffering, The server is working properly and others were coded finely. The urls.py urlpatterns = [ #Login Page url(r"^login/$", login, {'template_name':'users/login.html'}, name='login'), #Logout Page url(r"^logout/$", views.logout_view, name="logout"), # Registration Page url(r"^register/$", views.register, name='register'), ] The views.py def register(request): """Register a new user.""" if request.method != "POST": #display blank register form. form = UserCreationForm() else: # process completed form. form = UserCreationForm(data=request.POST) if form.is_valid(): new_user = form.save() # Log the user in and then redirect to home page authenticate_user = authenticate(username=new_user.username, password=request.POST['password1']) login(request, authenticate_user) return HttpResponseRedirect(reverse('learning_logs:index')) context = {'form': form} return render(request, 'users/register.html', context) Where might be the problem live? -
Setting up a file upload stream scan using Clamav in a Django back-end
Working on a React/Django app. I have files being uploaded by users through the React front-end that end up in the Django/DRF back-end. We have antivirus (AV) running on the server constantly, but we want to add stream scanning before it is written to disk. It is a bit over my head as how to set it up. Here are a few sources I am looking at. How do you virus scan a file being uploaded to your java webapp as it streams? Although accepted best answer describes it being "... quite easy" to setup, I'm struggling. I apparently need to cat testfile | clamscan - per the post and the corresponding documentation: How do you virus scan a file being uploaded to your java webapp as it streams? So if my back-end looks like the following: class SaveDocumentAPIView(APIView): permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): # this is for handling the files we do want # it writes the files to disk and writes them to the database for f in request.FILES.getlist('file'): max_id = Uploads.objects.all().aggregate(Max('id')) if max_id['id__max'] == None: max_id = 1 else: max_id = max_id['id__max'] + 1 data = { 'user_id': request.user.id, 'sur_id': kwargs.get('sur_id'), 'co': User.objects.get(id=request.user.id).co, 'date_uploaded': … -
Django RequestFactory add HTTP_X_FORWARDED_FOR
I have this code block that I am trying to write tests for: def get_client_ip(req): """ This is used to get the user's IP from the request object. """ x_forwarded_for = req.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = req.META.get('REMOTE_ADDR', "unknown") return ip So far I have been able to test the else section of the if statement. This is what my test currently looks like: def test_get_client_ip(self): """ Test the get Client IP fuction with a request. """ # Create an instance of a GET request. request = self.factory.get('/home') ip = get_client_ip(request) self.assertEqual(ip, '127.0.0.1') How would I go about adding "HTTP_X_FORWARDED_FOR" to META of the request object? -
Error loading admin page after upgrading to django-1.11
So previously, i was using django-1.8 version & i am in the process of upgrading to django-1.11. When i load my /admin page, i get Exception Type: TemplateDoesNotExist Exception Value: admin/index.html I have tried multiple options and dont know why django is not loading admin templates for django-1.11. Few more details: - i use django-jet for the admin interface - My TEMPLATES in settings looks like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'custom_dir_1'), os.path.join(BASE_DIR, 'custom_dir_2'), os.path.join(BASE_DIR, 'custom_dir_3') ], 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.request', 'django.template.context_processors.i18n', 'django.contrib.messages.context_processors.messages', 'context_processors.base_context', ], } } ] Let me know if i can provide any other information to debug better. Any guidance in this issue is super appreciated, Have been at this issue for 3rd consecutive day :-(