Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest framework, not serializable
I am new at using the django REST framework and I am having trouble to import a list of the members of a team my query is team_name_list = Project.objects.get(id=kwargs['pk1']).team_id.members.all() which give an output : <QuerySet [<MyUser: johndoe@gmail.com>, <MyUser: johndoe2@gmail.com>, <MyUser: johndoe3@gmail.com>, <MyUser: johndoe4@gmail.com>]> The thing is when I try to import it in my context I get an error Object of type 'MyUser' is not JSON serializable I guess because the output of my query should be something ["johndoe@gmail.com","johndoe2@gmail.com","johndoe3@gmail.com","johndoe4@gmail.com"] How can I make it work -
Django getting csrf error
I've made a register form, usually it works, but sometimes it gives me the csrf error, after i go back to the register page, it works again: Forbidden (403) CSRF verification failed. Request aborted. This is the register form i've made: def register(request): data = dict() if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): cd = form.cleaned_data email = cd['email'] password = cd['password1'] new_user = CustomUser.objects.create_user( email=email, password=password, ) new_user.valid_email = False new_user.save() current_site = get_current_site(request) subject = 'Activate your account.' message = render_to_string('registration/account_activation_email.html', { 'user': new_user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(new_user.pk)), 'token': account_activation_token.make_token(new_user), }) new_user.email_user(subject, message) return redirect('account:account_activation_sent') else: form = RegistrationForm() data['form'] = form return render(request, 'registration/register.html', data) In register.html i am using {% csrf_token %}: <form method="POST" class="m-login__form m-form" action=""> {% csrf_token %} {{ user_form.non_field_errors }} {{ user_form.email.errors }} <div class="form-group m-form__group"> <input type="text" placeholder="E-mail*" name="email" autocomplete="off"> </div> {{ user_form.password1.errors }} <div class="form-group m-form__group"> <input type="password" placeholder="Parola*" name="password1"> </div> {{ user_form.password2.errors }} <div class="form-group m-form__group"> <input type="password" placeholder="Confirmati parola*" name="password2"> </div> <div class="m-login__form-action"> <button id="m_login_signup_submit" class="btn m-btn m-btn--pill m-btn--custom m-btn--air m-login__btn m-login__btn--primary"> Sign Up </button> </div> </form> What could be the problem? -
Is there is any phpmyadmin like alternative for python
Iam new to python, and i need to know is there any phpmyadmin like alternative for python. -
systemctl restart httpd failed, when I don't know why there is python/django related
I start my httpd failed: systemctl restart httpd Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details. [root@controller html]# journalctl -xe 12月 05 18:22:17 controller sshd[16444]: Failed password for root from 182.100.67.120 port 32032 ssh2 12月 05 18:22:18 controller sshd[16444]: pam_succeed_if(sshd:auth): requirement "uid >= 1000" not met by user "root" 12月 05 18:22:20 controller sshd[16444]: Failed password for root from 182.100.67.120 port 32032 ssh2 12月 05 18:22:20 controller sshd[16444]: pam_succeed_if(sshd:auth): requirement "uid >= 1000" not met by user "root" 12月 05 18:22:22 controller sshd[16444]: Failed password for root from 182.100.67.120 port 32032 ssh2 12月 05 18:22:22 controller sshd[16444]: Disconnecting: Too many authentication failures for root [preauth] 12月 05 18:22:22 controller sshd[16444]: PAM 5 more authentication failures; logname= uid=0 euid=0 tty=ssh ruser= rhost=182.100.67.120 user=root 12月 05 18:22:22 controller sshd[16444]: PAM service(sshd) ignoring max retries; 6 > 3 12月 05 18:22:24 controller sshd[16463]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=182.100.67.120 user=root 12月 05 18:22:24 controller sshd[16463]: pam_succeed_if(sshd:auth): requirement "uid >= 1000" not met by user "root" 12月 05 18:22:26 controller sshd[1646 In my /var/log/messages: Dec 5 18:27:45 controller systemd: Starting The Apache HTTP Server... Dec 5 18:27:46 controller … -
Django: string representation from choices list [duplicate]
This question already has an answer here: Django: Display Choice Value 3 answers Is there a way to use django's model choices to obtain a string representation? I am trying to avoid having to write a long series of if-thens or switch conditions. I have many lists of tuples for various choices in my models.py, like this: FOOD_CHOICES = ( ("1", "Pizza"), ("2", "Hamburger"), ("3", "Hoagie"), ) The point was to obtain a quick numeric representation of each choice, while allowing admins to see the actual choices on the admin page. But now I would also like to get "Pizza" instead of "1" when I pass a query to a web page. It seems like the only way to do this is to use a series of If-thens, and I would really like to avoid that because there are dozens of choices that are only going to increase as time goes on. -
Django Rest Framework API in AWS cant use user token
So i have created a database and API for user to use it to register, login, see current user profile and log out. This work perfectly locally so i uploaded it into AWS. The register and login works but when using the token from the login. the data i get is blank. Even using the token for logout also got error. I am not sure what is the problem as it was perfectly fine when using it locally. Please help Here is the screenshot taken from Postman on both locally and AWS Expected - Local: https://imgur.com/a/HQKtt Result - AWS: https://imgur.com/a/hwjKt models.py class CustomUserManager(UserManager): def get_by_natural_key(self, username): return self.get( Q(**{self.model.USERNAME_FIELD: username}) | Q(**{self.model.EMAIL_FIELD: username}) ) class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=9, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) ethnicGroup = models.CharField(max_length=30, blank=True, null=True) mobileNo = models.IntegerField(blank=True, null=True) favoriteClinic = models.CharField(max_length=50, blank=True, null=True) # displaypicture = models.ImageField objects = CustomUserManager() def __str__(self): return self.username class Session(models.Model): userId = models.ForeignKey(MyUser) token = models.CharField(max_length = 255) firstActive = models.DateField(auto_now=True) lastActive = models.DateField(auto_now=True) class Relation(models.Model): # relationId = models.AutoField() userId = models.ForeignKey(MyUser) relativeId = models.ForeignKey(MyUser, related_name='relative') relationship = models.CharField(max_length = 20) dateEst = models.DateField(auto_now_add=True) class … -
What's the rationale of using properties instead of fields within the File model of django-filer
I tried to do filtering for the extension field, which is actually not a field at all as the following example suggests. For the sake of this example, let's imagine we have a running Django with django-filer installed and some file already uploaded. >>> from filer.models import File >>> File.objects.all()[0].extension 'some_ext' # just as example But when trying to filter: >>> File.objects.filter(extension='pdf') django.core.exceptions.FieldError: Cannot resolve keyword 'extension' into field. Choices are: _file_size, clipboarditem, description, downloadfilemodel, file, filer_image_file, folder, folder_id, has_all_mandatory_data, id, in_clipboards, is_public, modified_at, name, news_attachment, original_filename, owner, owner_id, polymorphic_ctype, polymorphic_ctype_id, sha1, uploaded_at This is because extension are not stored with the model but in fact are computed properties. My question: What's the rationale of not storing this meta data in the File Model. -
Adding languages dynamically through Django Admin
If I have a project which is using english language and I have all the string fields with translator helpers like this: from django.utils.translation import ugettext as _ from django.http import HttpResponse def my_view(request): output = _("Welcome to my site.") return HttpResponse(output) But I have potential users from other languages (which I dont know which languages are yet). Is it possible to add a new language like french, russian, etc from django admin without modifying django settings and adding the language there? -
Issue with Django 2.0 : 'WSGIRequest' object has no attribute 'session'
I upgraded my Django version from 1.11.5 to 2.0 and I'm trying to solve different deprecated element. However, even if my CSS/bootstrap style sheet doesn't work, I don't overcome to log into my Django software. I have this issue : 'WSGIRequest' object has no attribute 'session' This is the entire Traceback : Environment: Request Method: POST Request URL: http://127.0.0.1:8000/Authentification/Login/ Django Version: 2.0 Python Version: 3.6.2 Installed Applications: ['Institution', 'django.conf.urls', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrapform', 'django_countries', 'chartit', 'Configurations', 'Home', 'Authentication', 'Identity', 'rest_framework', 'Fiscal', 'bootstrap4'] Installed Middleware: [] Traceback: File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/Users/valentinjungbluth/Desktop/Django/DatasystemsCORE/DatasystemsCore/DatasystemsCORE/Authentication/views.py" in Login 26. login(request, user) File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/contrib/auth/__init__.py" in login 130. if SESSION_KEY in request.session: Exception Type: AttributeError at /Authentification/Login/ Exception Value: 'WSGIRequest' object has no attribute 'session' In my Authentification app : # views.py file #-*- coding: utf-8 -*- from django.contrib.auth import authenticate, login, logout from .forms import ConnexionForm from django.shortcuts import render, reverse, get_object_or_404, redirect from django.http import HttpResponseRedirect, HttpResponse from .models import LoggedUsers from API_GED import Logger import datetime from django.views.decorators.csrf import … -
TypeError: __init__() missing 1 required positional argument: 'on_delete' in remote server CentOS7.2
In my Mac I use PyCharm run my Django project very well. But in the remote server I use the same commands to run my project: python3 manage.py runserver 8001 The there comes the issue: File "/var/www/html/Qiyun02//user_admin_productmanage_cloudserver/models.py", line 3, in <module> from xxx.qiyun_admin_productconfig_cloudserver.models import ( File "/var/www/html/Qiyun02/qiyun_admin_productconfig_cloudserver/models.py", line 109, in <module> class Disk(models.Model): File "/var/www/html/Qiyun02/qiyun_admin_productconfig_cloudserver/models.py", line 110, in Disk diskEssenceType = models.ForeignKey(to=DiskEssenceType, related_name='disks') # "SAS", "SSD" and so on TypeError: __init__() missing 1 required positional argument: 'on_delete' I know the on_delete error means. but I mean, in my Mac why there do not shows the error? whether this is related to django version? My local Mac Django version is 1.11.2. The remote server CentOS7.2 version is python-django-1.8.14-1.el7.noarch EDIT Please, I know the on_delete error in there, I mean, in my Mac, there is no the reminds, why I copy to the CentOS7.2 remote server there comes this issue? whether this is caused by django version? -
WSGIDaemonProcess, Etc. Causing Connection Timeout in Debian 9
I was previously running Debian 8 and hosting my Django app using the following setup: Django 1.11 mod-wsgi 4.5 apache 2.4 mysql Now that I have updated to Debian 9, and using mariaDB, I am having an issue using the following settings in my apache2.conf file: LoadModule wsgi_module "/root/.virtualenvs/user/local/lib/python2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so" WSGIScriptAlias / /home/user/web/user.com/project/project/wsgi.py WSGIDaemonProcess user.com socket-user=user group=user processes=2 threads=25 WSGIProcessGroup user.com WSGIPythonHome "/root/.virtualenvs/user" <-- outside of virtual host I took each line out to see which was causing the issue, with LoadModule wsgi_module "/root/.virtualenvs/user/local/lib/python2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so" being the only one that was allowed to be in there and not cause the site to hang. By taking out all of those lines, my site works (albeit, without static files) and is not running in Daemon mode... My error logs show nothing except the following: 2017/12/05 08:59:15 [error] 446#446: *80 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: X.X.X.X, server: website.com, request: "GET / HTTP/1.1", upstream: "http://X.X.X.X:8080/", host: "website.com" 2017/12/05 09:00:00 [error] 446#446: *80 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: X.X.X.X, server: website.com, request: "GET / HTTP/1.1", upstream: "http://X.X.X.X:8080/", host: "website.com" How do I fix this?? -
How to install HTTPS on django with python hendrix server?
Which is the best method to install https on a django project running on hendrix server ? Could you describe your favorite cooking recipe step by step ? (pip install ..., app to add, settings vars, middleware, hendrix configuration) -
NoReverseMatch error in rendering Django
Below is my views.py. After the POST, user gets a success page showing the 5 Items. At the same time I also want to show environment to the user. So I did something like below (passed environment as an argument). I get that while the redirect happens, it tries to find something like success and the environment argument match which it is not able to get. Probably I need right regular expression to handle this and I am not sure how to handle this. def order_create(request): cart = ItemObject.objects.all() if request.method == 'POST': ... environment = envi_dict1.difference(item_dict1) return HttpResponseRedirect(reverse('success', kwargs={'environment': environment})) else: form = ItemObjectCreateForm() return render(request, 'index.html', {'form': form}) def successView(request): return render(request, 'success.html', {'items': ItemObject.objects.filter(gp_code='Unknown')[:5]}) urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^export_action/', include("export_action.urls", namespace="export_action")), url('^business-logic/', include('business_logic.urls')), url('^index/', views.order_create), url(r'^success/', views.successView, name='success') ] The error I am getting is this NoReverseMatch at /index/ Reverse for 'success' with keyword arguments '{u'environment': set([u'Test1'])}' not found. 1 pattern(s) tried: ['success/'] -
Django pdf viewer
views.py def pdf(request, lec_id): if not request.user.is_authenticated(): return render(request, 'Home/login.html') else: user=request.user lectu=get_object_or_404(Lecture,pk=lec_id) return render(request, 'Home/pdf.html', {'lectu':lectu,'user':user}) pdf.html <h1>start</h1> <iframe src="{{ lectu.PDF_file }}" width='800' height='800' frameborder='0'></iframe> end But it's show this [i want to open pdf file in pdf viewer like google pdf viewer with django but here is one problem in this image] -
Django Deep Linking render with #tag
I am trying to Deep Link tabs with Dango by adding the #panel1 at the end. This would be the template needed: template = "charts/chart1.html#panel1" return render ( request, template, context ) But obviously Django can not find that template once I add the hashtag. Is there a way to overcome this issue? Thank You. https://foundation.zurb.com/sites/docs/tabs.html -
Django forms.VaildationError not showing on a class based view
My forms.validationerror is not showing. Below is my form that I am using. The if statement works and it detects the issue, and prints out the content successfully. As a lot the existing errors on stackoverflow suggest, the content is not None as shown in the print statement. class PollItemMessageAddForm(forms.ModelForm): class Meta: model = Message fields = [ "content" ] labels = { 'content': 'Add your comment', } widgets = { 'content': Textarea(attrs={'cols': 10, 'rows': 5}), } def __init__(self, *args, **kwargs): # this line should be before a super call self.request = kwargs.pop('request', None) super(PollItemMessageAddForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.add_input(Submit('submit', value='Post', css_class='buttonspace btn-success')) def clean_content(self): content = self.cleaned_data.get("content") if len(content) > 50: print content raise forms.ValidationError("Please limit your message to less the 50 characters") return content Below is my views.py post statement in my class based view, which skips the form.isvalid to be redirected to the same url where the error message should appear. I am using a detailview and formmixin in my class based view if it helps. I cant see where the issue is coming from in the absence of a traceback. Any help would be appreciated. def post(self, request, *args, **kwargs): url = … -
Comparing dates in Django does not work
I have a problem comparing dates in Django. I followed the hint How to compare dates in Django but it does not work. Maybe you can help me. My code: modelys.py class Customer(models.Model): last_updated = models.DateTimeField(auto_now_add=True) views.py @property def is_past_due(self): return (date.today() - self.date)> timdedelta(1) home.html {% if customer.last_updated.is_past_due %} <td class="table-danger">{{ customer.last_updated }}</td> {% else %} <td class="align-middle">{{ customer.last_updated }}</td> {% endif %} I am using Bootstrap, so when the difference between two dates has a more than one day I want a tablefield to become 'danger'-ous ;-), but nothing changes. Thanks in advance. -
Using django tag in a div ID
I am trying to generate dynamically an ID in my app using bootstrap dropdown menu but for some reason it does not appear .. <div class="dropdown"> <button class="btn btn-secondary btn-sm btn-canvas dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Compare with </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for i in team_list_pop %} <a class="dropdown-item" id="{{i.first_name}}" href="#">{{i.first_name}} {{i.last_name}}</a> {% endfor %} </div> </div> and the output when I do inspect in my browser <a class="dropdown-item" href="#">John Doe</a> with no traces of the ID. how can I get to hve an output <a id="john" class="dropdown-item" href="#">John Doe</a> thx you very much -
Many-to-many relationship with 'through' model returning error on migration
I'm trying to implement a system which allows for two Profile model objects to be a part of a Pair model object. Here is the Profile, followed by a Pair model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) pair = models.ManyToManyField('self', through='Pair', symmetrical=False, related_name='pair_to+') class Pair(models.Model): requester = models.ForeignKey(Profile, related_name='pairing_requester') accepter = models.ForeignKey(Profile, related_name='pairing_accepter') requester_learns = models.CharField(max_length=60, null=True) requester_teaches = models.CharField(max_length=60, null=True) The relationship between profiles should be symmetrical, such that (profile1, profile2) are a unique object and I should not expect a (profile2, profile1) to be created. So, per this article, I am trying to create the relationship. Upon makemigrations, I am receiving the error: ERRORS: <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x1044b47b8>: (models.E022) <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x1044b47b8> contains a lazy reference to user_profile.pair, but app 'user_profile' doesn't provide model 'pair'. user_profile.Profile.pair: (fields.E331) Field specifies a many-to-many relation through model 'Pair', which has not been installed. What am I doing wrong? -
Django form is not displaying
I am new to django forms and while trying to design an HTML form, I notice that the django form blocks are not displaying. Below are the codes: <body> tag of index.html: <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="panel panel-login"> <div class="panel-heading"> <div class="row"> <div class="col-xs-6"> <a href="#" class="active" id="login-form-link">Login</a> </div> <div class="col-xs-6"> <a href="#" id="register-form-link">Register</a> </div> </div> <hr> </div> <div class="panel-body"> <div class="row"> <div class="col-lg-12"> {% block login_content %} {% endblock %} {% block register_content %} {% endblock %} </div> </div> </div> </div> </div> </div> </div> login.html which goes into the {% block login_content %} {% extends 'index.html' %} {% block login_content %} <form id="login-form" action="{% url 'authentication:user_login' %}" role="form" style="display: block;" method="POST"> {% csrf_token %} <label for="username">Username:</label> <input id="username" type="text" name="username" placeholder="Enter Username" tabindex="1" class="form-control"> <label for="password">Password:</label> <input id="password" type="password" name="password" tabindex="=2" class="form-control" placeholder="Password"> <button type="submit" class="btn btn-success">Login</button> </form> {% endblock %} register.html that goes into the {% block register_content %} {% extends 'index.html' %} {% block register_content %} <form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <input type="submit" name="" value="Register"> </form> {% endblock %} On my UI, the {{ user_form.as_p }} and the {{ profile_form.as_p }} does … -
get dictionary from queryset
I have below query where I want to fetch 'specs' which is a dictionary but the type of envi_dict is a Queryset class. How do I fetch the dictionary from this queryset? Any help is much appreciated. envi_dict = Environment.objects.values('specs') Result <QuerySet [({u'CPU Model': u'Dell', u'RAM': 1000, u'CPU': 400},), ({u'CPU Model': u'Dell', u'RAM': 1000, u'CPU': 400},)]>, <class 'django.db.models.query.QuerySet'>, ) I tried Environment.objects.filter(title=item.title).values('specs') and also Environment.objects.get('specs') but I am still getting a queryset. -
How to handle special character in file path of a file in python
file_path : "/home/encoding/What Is A_ V Can?and Can't?It Offer Us_ (ABC) (720p_30fps_H264-192kbit_AAC).mp4" File exists in server but my python code unable to find file due to special characters. import os print os.path.isfile(file_path) This giving me False. -
Override url and view from reusable app
Please answer only for django 1.10+ where patterns() is removed. I want to override "inbox" from django-postman with custom url and custom view. For example I have url(r'^myurl/$', my_view, name='inbox'). How can I get my url from reverse('postman:inbox') instead of built-in url(r'^inbox/(?:(?P<option>m)/)?$', InboxView.as_view(), name='inbox')? I use this method, but it may be dirty: from postman.urls import urlpatterns as postman_urlpatterns merged = ([ url(r'^myurl/$', my_view, name='inbox') ] + [ u for u in postman_urlpatterns if u.name != 'inbox' ], 'postman') urlpatterns = [ url(r'^', include(merged)) ] Is there a cleaner method? -
Django-filters how to pass current user from view inside FilterSet?
I have a filter where I need to access the request.user. However, Django-filter does not pass it. I was able to figure out possible FilterSet configuration. But how to pass current user from view inside FilterSet? filters.py class TransationsListFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(TransationsListFilter, self).__init__(*args, **kwargs) transaction_date = DateFromToRangeFilter(widget=RangeWidget(attrs {'placeholder': 'DD/MM/YYYY'})) class Meta: model = Transations fields = ['transaction_date'] @property def qs(self): return super(TransationsListFilter, self).filter(user=user) views.py class TransactionsList(PagedFilteredTableView): model = Transations table_class = TransactionsTable filter_class = TransationsListFilter formhelper_class = TransationsFormHelper models.py class Transations(models.Model): transaction_date = models.DateField(default=datetime.now, blank=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default = 0 ) -
django using angular 4 in apache server static files cannot be loaded
I am using angular 4 for frontend for django application. I used "ng build --target=production --environment=prod --aot=false" for building dist and collectstatic to put files in static folder. It is working fine while running on a port but while running on apache server is not working because of the relative paths of bundle js and css files. Any help is greatly appreciated.