Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF Exclude from queryset
I'm trying to exclude ids from one model from foreignkey of another model. So i have a User model with ManyToMany going through Vote model. For now i tried many times in my ModelViewSet by .filter and .exclude and nothing working. (For sure i'm doing it bad.) From User.vote i'm getting ids of voted users, and i want them to be excluded from to_user, so user logged in can't vote twice the same person, and himself. class User(AbstractUser): ... some code. vote = models.ManyToManyField('self', through=Vote, symmetrical=False, related_name='related_to+') class Vote(models.Model): from_user = models.ForeignKey(User, related_name='from_user', on_delete=models.CASCADE) to_user = models.ForeignKey(User, related_name='to_user', on_delete=models.CASCADE) status = models.IntegerField(choices=VOTE_STATUSES) and serializer: class UserVoteSerializer(serializers.ModelSerializer): from_user = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserDefault()) class Meta: model = UserVote fields = ('from_user', 'to_user', 'status') -
Registering a User in Django
I am creating an application that allows a user to create and account and view their profile. When a user fills out the registration form they are redirected to their profile. However when the user is sent to this page, They are displayed as an AnonymousUser. Below is how I have tried to implement the functionality. Forms #Here is the information that a user has to enter to register. All information must be unique. class RegisterUserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'input'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'input'})) class Meta: model = User fields = ['username', 'email'] widgets = { 'username': forms.TextInput(attrs={'class': 'input'}), 'email': forms.EmailInput(attrs={'class': 'input'}), } # validate password... def clean_password2(self): cd = self.cleaned_data if cd['password2'] != ['password']: raise ValidationError("Passwords don't match") return cd['password2'] Views class RegisterUserView(CreateView): form_class = RegisterUserForm template_name = "account/register.html" def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): return HttpResponseForbidden() return super(RegisterUserView, self).dispatch(request, *args, **kwargs) #Here i am trying to create the user and save him to the DB def form_valid(self, form): user = form.save(commit=False) user.set_password(form.cleaned_data['password']) user.save() UserProfileModel.objects.create(user=user) #Redirecting the new user to the profile page. return HttpResponseRedirect(reverse('account:profile')) HTML {% extends 'base.html' %} {% block body %} <div class="container"> <div class="columns is-mobile"> <div class="column is-half is-offset-one-quarter"> <div class="content"><h2>Register</h2></div> <form action="{% url … -
Collectstatic creates empty files
I trying to upgrade an app to django 1.11, but experience issues with collectstatic. Old versions: django 1.8.17 django-storages 1.5.1 New versions: django 1.11.12 django-storages 1.6.6 Storage: class StaticS3BotoStorage(ManifestFilesMixin, S3BotoStorage): location = 'static' file_overwrite = True preload_metadata = True or class StaticS3BotoStorage(CachedFilesMixin, S3BotoStorage): location = 'static' file_overwrite = True preload_metadata = True With the old versions, collectstatic worked fine, including collectstatic --clear. After the upgrade, collectstatic --clear fails (no files are deleted). collectstatic does copy files, however, sometimes it creates two versions of the same file. In this particular example, I get base.hash1.css and base.hash2.css. base.hash2.css is empty, so pages open, but do not render correctly. If I don't use CachedFilesMixin or ManifestFilesMixin, collectstatic works fine, but clear still fails. I tested different combinations of django 1.11 and django-storages, but they all seem to behave the same. Did someone else experience a similar issue? -
Django DateFromToRange filter seems does not work
I have a two model with simple relation as below: # models.py class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) class PersonSession(models.Model): start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(null=True, blank=True) person = models.ForeignKey(Person, related_name='person_sessions') # views.py class PersonFilter(django_filters.FilterSet): start_time = django_filters.DateFromToRangeFilter(name='person_sessions__start_time', distinct=True) class Meta: model = Person fields = ('first_name', 'last_name', 'start_time') class PersonList(generics.ListCreateAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend) filter_class = PersonFilter As it is shown I want to use DateFromToRangeFilter and I expect that I get api such this: api/persons?start_time_before=2018-04-20&start_time_after=2018-04-18 But this does not work at all. It seems as stated in this post, there is an error with implementation of this type of filter but solution in the post does not work for me because I would get two inner join and get completely different results as I expected. -
Django ORM ExtractDay / ExtractHour / ExtractMinute
I'm trying to do a GROUP BY to a queryset. I'd like to group the datetimes. So I'm using the function Extract. My model is the following: class CustomData(models.Model): site = models.ForeignKey(CustomModel, blank=True, null=True, on_delete=models.PROTECT) number = models.IntegerField(default=0) created = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = 'custom_data' And this is my QUERY: from django.db.models.functions import (Extract, ExtractDay, ExtractHour, ExtractMinute, ExtractMonth, ExtractQuarter, ExtractSecond, ExtractWeek, ExtractWeekDay, ExtractYear ) cd = CustomData.objects.filter(site=c).order_by('-id') cd = cd.annotate( year=ExtractYear('created'), month=ExtractMonth('created'), day=ExtractDay('created'), hour=ExtractHour('created'), minute=ExtractMinute('created'), ).values( 'year', 'month', 'day', 'hour', 'minute' ) cd = cd.annotate(number=Max('number')) for x in cd: print(x) But the result is the following: {'hour': None, 'minute': None, 'day': None, 'year': None, 'month': None, 'number': 15} {'hour': None, 'minute': None, 'day': None, 'year': None, 'month': None, 'number': 17} {'hour': None, 'minute': None, 'day': None, 'year': None, 'month': None, 'number': 28} {'hour': None, 'minute': None, 'day': None, 'year': None, 'month': None, 'number': 97} {'hour': None, 'minute': None, 'day': None, 'year': None, 'month': None, 'number': 11} {'hour': None, 'minute': None, 'day': None, 'year': None, 'month': None, 'number': 19} {'hour': None, 'minute': None, 'day': None, 'year': None, 'month': None, 'number': 7} {'hour': None, 'minute': None, 'day': None, 'year': None, 'month': None, 'number': 8} {'hour': None, 'minute': None, 'day': … -
Issue between Django 2.0 / Apache2 and WSGI
I'm trying to deploy my Django project in my server but I'm encountering some issues. My environment : Ubuntu 16.04 Server Django 2.0 Python 3.5 Apache2 2.4 WSGI Django configuration : My Django project is located to : /var/www/html/DatasystemsCORE I have wsgi.py file (/var/www/html/DatasystemsCORE/DatasystemsCORE) which looks like : import os, sys from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DatasystemsCORE.settings") application = get_wsgi_application() I have ALLOWED_HOST like this : ALLOWED_HOSTS = ['localhost', '172.30.10.86', '[::1]'] Apache2 configuration : In my apache2.conf file, I have : WSGIScriptAlias / /var/www/html/DatasystemsCORE/DatasystemsCORE/wsgi.py WSGIPythonPath /var/www/html/DatasystemsCORE Alias /static/ /var/www/html/DatasystemsCORE/static/Theme/ <Directory /var/www/html/DatasystemsCORE/static/Theme/> Require all granted </Directory> <Directory /var/www/html/DatasystemsCORE/DatasystemsCORE> <Files wsgi.py> Require all granted </Files> </Directory> And I have in sites-available/000-default.conf : <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html/DatasystemsCORE ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> To my mind, all parameters seem to be right, but when I write : 172.30.10.86:80 in my browser, I get : 500 Internal Server Error Traceback This is the Traceback given by error.log in apache2 : [Tue Apr 24 12:07:32.526764 2018] [wsgi:error] [pid 2611:tid 139723751765760] [client 172.30.10.73:50128] mod_wsgi (pid=2611): Target WSGI script '/var/www/html/DatasystemsCORE/DatasystemsCORE/wsgi.py' cannot be loaded as Python module. [Tue Apr 24 12:07:32.526839 2018] [wsgi:error] [pid 2611:tid 139723751765760] [client 172.30.10.73:50128] mod_wsgi (pid=2611): Exception occurred processing WSGI script '/var/www/html/DatasystemsCORE/DatasystemsCORE/wsgi.py'. … -
Django duplicated queries with select related
I can't optimize Django query requests for foreign keys composed of other foreign keys. Each project has a foreign key to a status. Each status has two foreign keys to a type and a phase of the project. Here is the model.py: class Project(WithDateAndOwner): name = models.SlugField() status = models.ForeignKey("ProjectStatus", blank=True, related_name="status") class ProjectStatus(WithDateAndOwner): name = models.SlugField() type = models.ForeignKey(ProjectStatusType) phase = models.ForeignKey(ProjectStatusPhase) def __unicode__(self): return "%s-%s-%s" % (self.type, self.phase, self.name) class ProjectStatusPhase(WithDateAndOwner): name = models.SlugField() def __unicode__(self): return "%s" % self.name class ProjectStatusType(WithDateAndOwner): name = models.SlugField(unique=True) def __unicode__(self): return self.name Here is the admin.py: from moxutils.admin WithDateAndOwnerAdmin_show class ProjectAdmin(WithDateAndOwnerAdmin_show): list_display=("name", "status",) list_selected_related = [ "status", "status__phase", "status__type" ] def get_queryset(self,request): return super(ProjectAdmin, self) \ .get_queryset(request) \ .select_related(*self.list_selected_related) I put the foreign keys in the select related list, but I still get duplicated queries (read from the django debug toolbar): SELECT `projects_projectstatustype`.`id`, `projects_projectstatustype`.`created`, `projects_projectstatustype`.`updated`, `projects_projectstatustype`.`owner_id`, `projects_projectstatustype`.`name`, `projects_projectstatustype`.`order` FROM `projects_projectstatustype` WHERE `projects_projectstatustype`.`id` = 4 Duplicated 44 times. 0.959447560819% 1.16 Connection: default models.py in __unicode__(175) return "%s-%s-%s" % (self.type, self.phase, self.name) What am I doing wrong? -
Problems with sessionid expired django
I have a django app, and the autheticate user use the cookies, i set de cookie age with de value 36000 SESSION_COOKIE_AGE = 36000 # In Google Chrome the cookie sessionid set the expired date 1969-12-31T23:59:59.000Z The app logout in 3 minutes, in other browser have the same problem In my server i used gunicorn(timeout workers 600s) + nginx(keep_alive_timeout 20m) Whats the problem? -
AttributeError: 'Library' object has no attribute '
I'm trying to use reactjs with django api for an app, and i get this error, I dont know what I'm doing wrong, Internal Server Error: / Traceback (most recent call last): File "~/.virtualenvs/virtualenv/lib/python3.5/site- packages/django/template/utils.py", line 64, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "~/.virtualenvs/virtualenv/lib/python3.5/site- packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "~/.virtualenvs/virtualenv/lib/python3.5/site- packages/django/core/handlers/base.py", line 158, in _get_response response = self.process_exception_by_middleware(e, request) File "~/.virtualenvs/virtualenv/lib/python3.5/site- packages/django/core/handlers/base.py", line 156, in _get_response response = response.render() File "~/.virtualenvs/virtualenv/lib/python3.5/site- packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "~/.virtualenvs/virtualenv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "~/.virtualenvs/virtualenv/lib/python3.5/site- packages/webpack_loader/templatetags/webpack_loader.py", line 50, in <module> @register.assignment_tag AttributeError: 'Library' object has no attribute 'assignment_tag' [24/Apr/2018 10:37:29] "GET / HTTP/1.1" 500 159238 Not Found: /favicon.ico if there is an exemple of an app where django is used for Backend and reactjs for frontend, it's my first experience where I try … -
Django: HOW TO "redirect to a page after download and update download number"
Django redirect after download and update download number in the html view template of a specific image: Download models.py class Image(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) in_gallery = models.ManyToManyField(Gallery, blank=True, null=True) title = models.CharField(max_length=100) no_of_download = models.IntegerField(default=0) def __str__(self): return self.title + '-' + self.description what should be added to urls.py, views.py, models.py so that the number of downloads of the Image and the owner can be incremented by 1? -
Django URL pattern using pk error
I'm using the latest version of python3 and Django2, trying to do an URL pattern that is dynamic and changes for every different variable, Here are the codes: urls.py path('categories/<int:item_category>/', views.item_category, name="item_category"), views.py def item_category(request, pk): item_category = get_object_or_404(Categories, pk=pk) return render(request, 'items_modal.html', {'item_category': item_category}) models.py class Categories(models.Model): category_name = models.CharField(max_length=30) def __str__(self): return self.category_name def item_category(self): return reverse('item_category', args=[self.pk]) home.html <div class="table-responsive"> <table class="table table-hover"> <thead class="thead-dark"> <tr> <th scope="col"><h2 align="center"> محتويات المخزن</h2></th> </tr> </thead> <tbody> {% for cat in all_cats %} <tr> <th scope="row"><a href="{% url 'item_category' item_category.pk %}"" data-toggle="modal" data-target="#exampleModal">{{ cat }}</a></th> </tr> {% endfor %} </tbody> </table> </div> when I try to go to open the home page it gives me the error : NoReverseMatch at / Reverse for 'item_category' with arguments '('',)' not found. 1 pattern(s) tried: ['categories\\/(?P<item_category>[0-9]+)\\/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'item_category' with arguments '('',)' not found. 1 pattern(s) tried: ['categories\\/(?P<item_category>[0-9]+)\\/$'] Exception Location: C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632 Python Executable: C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\python.exe Python Version: 3.6.5 Python Path: ['C:\\python\\Django\\nothing', 'C:\\Users\\Dev3\\AppData\\Local\\Programs\\Python\\Python36-32\\python36.zip', 'C:\\Users\\Dev3\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs', 'C:\\Users\\Dev3\\AppData\\Local\\Programs\\Python\\Python36-32\\lib', 'C:\\Users\\Dev3\\AppData\\Local\\Programs\\Python\\Python36-32', 'C:\\Users\\Dev3\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages'] Server time: Tue, 24 Apr 2018 09:39:46 +0000 -
Django: Error with django content type
I got error: django.db.utils.IntegrityError: insert or update on table "auth_permission" violates foreign key constraint "auth_content_type_id_508cf46651277a81_fk_django_content_type_id" DETAIL: Key (content_type_id)=(1) is not present in table "django_content_type". I found this post but no recommendation helps: ContentType.objects.clear_cache() move 'django.contrib.contenttypes' before 'django.contrib.auth' in INSTALLED_APPS Has anyone found a solution to this problem? -
Django Rest Framework registrations
I have a custom user model class User(AbstractUser): username = None email = models.EmailField( unique=True) phone = models.CharField( max_length=15) is_pro = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone'] objects = UserManager() @property def token(self): """ Allows us to get a user's token by calling `user.token` instead of `user.generate_jwt_token(). The `@property` decorator above makes this possible. `token` is called a "dynamic property". """ return self._generate_jwt_token() def _generate_jwt_token(self): """ Generates a JSON Web Token that stores this user's ID and has an expiry date set to 60 days into the future. """ import jwt from datetime import datetime, timedelta from django.conf import settings dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') Now I try make SignIn API with Django Rest Framework using this tutorial https://thinkster.io/tutorials/django-json-api/authentication serializer.py class RegistrationSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=128, min_length=8, write_only=True ) token = serializers.CharField(max_length=255, read_only=True) class Meta: model = User fields = ['email', 'phone', 'password', 'token'] def create(self, validated_data): # Use the `create_user` method we wrote earlier to create a new user. return User.objects.create_user(**validated_data) views.py class RegistrationAPIView(APIView): # Allow any user (authenticated or not) to hit this endpoint. permission_classes = (AllowAny,) serializer_class = RegistrationSerializer def post(self, request): user = … -
Django formset with multiple foreignkey to same model object
I created a model class 'Boat' with two ForeignKeys to the same class 'InsurancePolicy' and I'm trying to render a Boat creation form with the two InsurancePolicy forms as inline formsets, not as ChoiceFields. Here is my main class 'Boat' class Boat(models.Model): name = models.CharField(blank=True, null=True, max_length=255) description = models.TextField(blank=True, null=True) rca_policy = models.ForeignKey(InsurancePolicy, on_delete=models.CASCADE, related_name='rca_policy') all_risks_policy = models.ForeignKey(InsurancePolicy, on_delete=models.CASCADE, related_name='rca_policy') and the 'InsurancePolicy' class: class InsurancePolicy(models.Model): contract_name = models.CharField(max_length=255) company_name = models.CharField(max_length=255) I tried to follow the django documentation to this link: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#more-than-one-foreign-key-to-the-same-model but I still can't render a single form with the all following fields: name description rca policy contract_name rca policy company_name all risks policy contract_name all risks policy company_name Am I missing anything? -
Django with Weasyprint on Azure
I have an Django application running on Azure via WebApps. To generate PDF files I am using Weasyprint. Deploying this on Azure fails because of: File ".\myapp\views.py", line 19, in <module> from weasyprint import HTML File "D:\home\python364x64\lib\site-packages\weasyprint\__init__.py", line 375, in <module> from .css import preprocess_stylesheet # noqa File "D:\home\python364x64\lib\site-packages\weasyprint\css\__init__.py", line 29, in <module> from . import computed_values File "D:\home\python364x64\lib\site-packages\weasyprint\css\computed_values.py", line 16, in <module> from .. import text File "D:\home\python364x64\lib\site-packages\weasyprint\text.py", line 18, in <module> import cairocffi as cairo File "D:\home\python364x64\lib\site-packages\cairocffi\__init__.py", line 41, in <module> cairo = dlopen(ffi, 'cairo', 'cairo-2') File "D:\home\python364x64\lib\site-packages\cairocffi\__init__.py", line 38, in dlopen raise OSError("dlopen() failed to load a library: %s" % ' / '.join(names)) OSError: dlopen() failed to load a library: cairo / cairo-2 It is a windows instance running. I had some problems installing all python packages I need - i.e. cairocffi. But I finally managed this now, by using the python3.6.4 (x64) extension. I have following packages installed via pip/wheel: --find-links wheelhouse cairocffi==0.8.0 CairoSVG==2.1.3 cffi==1.11.5 cssselect2==0.2.1 defusedxml==0.5.0 Django==2.0.3 html5lib==1.0.1 pdfrw==0.4 Pillow==5.0.0 pycparser==2.18 Pyphen==0.9.4 pytz==2018.3 six==1.11.0 tinycss2==0.6.1 WeasyPrint==0.42.2 webencodings==0.5.1 On the web I found nothing concerning problems with cairo on azure. Can anybody help? Thanks! -
How do I allow Puppeteer to access a login-required view in Django?
My goal here is to use Puppeteer to generate a PDF from a HTML view in Django. Preferably, this happens every time a certain model is saved. The view requires the user to be logged-in and own the model instance used in the view. This, of course, creates problems when trying to launch a Puppeteer instance to access the view and turn it into a PDF -- all I get is a PDF of the login page. I can think of a few ways, none of which stand out as The Right Way to do things: Get the users session ID and set the corresponding cookie in Puppeteer, either on the command line or using an environment variable -- I'm not sure this will actually work, I think there are security issues and as I'd like to do this in the model.save() method I don't necessarily have access to the user session ID. Make the view require login only when not accessed from localhost -- this seems like a security issue. Other ways to do this would be to use a HTML-to-PDF library, but these come with a lot of limitations on the HTML/CSS they can understand, or to draw … -
Django load specifik javascript file
i would like to load a specifik javascript file for the specifik html file. Instead of loading them into the base.html. Then alot of pages will have unnecessary scripts that are not used. I get this error: Invalid block tag on line 3: 'static', expected 'endblock'. Did you forget to register or load this tag? when i try to load it into the child.html. I'm {% extends 'base.html' %} {% block js %} <script src="{% static "javascript/week.js" %}" type="text/javascript"> </script> {% endblock %} -
Integrate Django Rest Swagger 0.3.x
Working on rather old project running Django 1.6 there's a need to integrate Swagger to describe REST endpoints. I've installed compatible version of Django Rest Framework (3.2.5) and Django Rest Swagger (0.3.0), then imported both into INSTALLED APPS and included DRF-Swagger's urls in my url scheme: ... url(r'^api/v1/$', include('rest_framework_swagger.urls')), ... When I go to this URL I see that Swagger is working, but I can't understand what should I do next to make it work with my endpoints and display display information about them? -
overwrited save method in django models doesn't work
I have a model that has an ImageField and I want to name it to its id that generated by AutoField, and therefore I overwrite the save() method in my model. But when I create an instance of the model in Admin panel, the picture name is set to None.png. How can I fix that? My models.py is: from django.db import models import os def get_image_name(instance, filename): fn = os.path.join('img/thumbnailCategory/', str(instance.id) + '.png') return fn class Category(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=50, null=False, blank=False) c_thumbnail = models.ImageField(upload_to=get_image_name, null=False, blank=False) def save(self, *args, **kwargs): super(Category, self).save(*args, **kwargs) def __str__(self): return '%s' % self.title Thanks in advance. -
Django: Generic - create model with manytomany relations
models.py class Image(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.DO_NOTHING) tag = models.ManyToManyField(Tag, blank=True, null=True) title = models.CharField(max_length=100) photo = models.FileField() description = models.CharField(max_length=1000) def __str__(self): return self.title + '-' + self.description urls.py url(r'image/add/$', views.ImageCreate.as_view(), name='image-add'), view.py class ImageCreate (CreateView): model = Image fields = ['category', 'title', 'photo', 'description', 'tag'] def form_valid(self, form): form.instance.owner = self.request.user.userprofile return super().form_valid(form) image_form.html (I have deleted unrelated div) <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'imagebank/form-template.html' %} <button type="submit" class="btn btn-success">Submit</button> </form> As from the screencap above, I cannot input any tags What to add to the code so that I can input at most 10 tags -
How to open a template as modal (detail user data) in user_list page (Django 1.11)
I have a user list page which works fine, and a user detail page which works fine too that I call from urls.py in seperate window. I want to open user detail in user list page in a modal window. user_list.html <table class="table table-bordered"> <thead> <tr> <th>Name</th> <th>Surname</th> <th>Email</th> <th></th> </tr> </thead> <tbody> {% for user in users %} <tr userid="{{user.id}}" class="edit_user"> <td>{{user.first_name}}</td> <td>{{user.last_name }}</td> <td>{{user.username }}</td> <td> <form class="right user_delete" method="POST" userid="{{user.id}}" action="{% url 'user_delete' user.id%}"> {% csrf_token %} <input class="btn btn-danger btn-sm" type="submit" value="DELETE"> </form> </td> <td><a type="button" class="btn btn-primary edit_user" href="{% url 'user_details' user.id %}" target="#edit_user"> UPDATE </a></td> </tr> {% empty %} <tr> <td>No Projects.</td> </tr> {% endfor %} </tbody> </table> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#registerformmodal"> New user </button> -
Django2 with postgis given unorderable types: F() < int()
I have the following view and model with me @api_view(['GET', ]) def fetch_proposals_for(request, nick_of_finder, current_latitude, current_longitiude): finder = get_object_or_404(TinderUser, nickname=nick_of_finder) finder_location = Point(float(current_longitiude), float(current_latitude)) candidates = TinderUser.objects.filter( last_location__distance_lte=( finder_location, D(km=min(finder.preferred_radius, F('preferred_radius')))) ).distance(finder_location).order_by('distance') if finder.preferred_sex == finder.sex: # deal with homosexual candidates_inside_finder_radius_and_vice_versa = candidates.filter( preferred_sex=finder.sex, sex=finder.preferred_sex, age__range=(finder.preferred_age_min, finder.preferred_age_max), preferred_age_min__lte=finder.age, preferred_age_max__gte=finder.age, ).exclude(nickname=finder.nickname) else: # deal with heterosexual: candidates_inside_finder_radius_and_vice_versa = candidates.filter( sex=finder.hetero_desires(), age__range=(finder.preferred_age_min, finder.preferred_age_max), preferred_age_min__lte=finder.age, preferred_age_max__gte=finder.age, ).exclude(sex=F('preferred_sex')).exclude(nickname=finder.nickname) paginator = Paginator(candidates_inside_finder_radius_and_vice_versa, 20) page = request.QUERY_PARAMS.get('page') try: result = paginator.page(page) except PageNotAnInteger: result = paginator.page(1) except EmptyPage: result = paginator.page(paginator.num_pages) serializer_context = {'request': request} serializer = TinderUserListSerializer(result, context=serializer_context) return Response(serializer.data) models.py from django.contrib.gis.db import models from django.core.validators import MinValueValidator, MaxValueValidator SEX_CHOICES = ( ('F', 'Female',) ('M', 'Male',), ) def hetero_desires(sex): return 'M' if sex == 'F' else 'F' class TinderUser(models.Model): nickname = models.CharField(max_length=250, unique=True) age = models.IntegerField(validators=[MinValueValidator(18), MaxValueValidator(130)], db_index=True) sex = models.CharField(max_length=1, choices=SEX_CHOICES, db_index=True) preferred_sex = models.CharField(max_length=1, choices=SEX_CHOICES) preferred_age_min = models.IntegerField(validators=[MinValueValidator(18), MaxValueValidator(130)]) preferred_age_max = models.IntegerField(validators=[MinValueValidator(18), MaxValueValidator(130)]) last_location = models.PointField(max_length=40, null=True) preferred_radius = models.IntegerField(default=5, help_text="in kilometers") def __str__(self): return self.nickname def hetero_desires(self): return hetero_desires(self.sex) When I try to execute the request I get unorderable types: F() < int() After investigation I found it is with the D(km=min(finder.preferred_radius, F('preferred_radius')))) which I am using is causing problem. Can … -
Django save uploaded file
I want to upload the file which I am able to do from below code , but I also nned to save all the uploads in Different folder with different names , if 2 users upload same file from browser then in the folder it should been saved by different name or Unique Identification number. Following is my code: views.py from django.shortcuts import render import openpyxl def index(request): if "GET" == request.method: return render(request, 'myapp/index.html', {}) else: excel_file = request.FILES["excel_file"] # you may put validations here to check extension or file size wb = openpyxl.load_workbook(excel_file) # getting all sheets sheets = wb.sheetnames print(sheets) # getting a particular sheet worksheet = wb["Sheet1"] print(worksheet) # getting active sheet active_sheet = wb.active print(active_sheet) # reading a cell print(worksheet["A1"].value) excel_data = list() # iterating over the rows and # getting value from each cell in row for row in worksheet.iter_rows(): row_data = list() for cell in row: row_data.append(str(cell.value)) print(cell.value) excel_data.append(row_data) return render(request, 'myapp/index.html', {"excel_data":excel_data}) -
Integration tests of Ebay connection service with mocks
I've got a project with ebay marketplace. Have to write integrated tests and looks like gonna crack my teeth on it. Could you please give me advice how can I do it correctly? ebay.services: class EbayAdapter(object): SANDBOX_URL = 'https://signin.sandbox.ebay.com/ws/eBayISAPI.dll?SignIn&RUName={ebay_ru_name}&SessID={session_id}' URL = 'https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&RUName={ebay_ru_name}&SessID={session_id}' def __init__(self, app_id, dev_id, cert_id, session_id=None): self.__app_id = app_id self.__dev_id = dev_id self.__cert_id = cert_id self.domain = 'api.sandbox.ebay.com' if TEST_MODE else 'api.ebay.com' self.user_token = None self.session_id = session_id def __get_trading_obj(self): return Trading(domain=self.domain, appid=self.__app_id, devid=self.__dev_id, certid=self.__cert_id, token=self.user_token, config_file=None) def __request(self, request_name, data=None): api = self.__get_trading_obj() data = data if data else {} api.execute(request_name, data) return api def get_session_id(self): try: req_res = None req_res = self.__request('GetSessionID', {'RuName': EBAY_RU_NAME}) if req_res.response_code() == 200: self.session_id = req_res.response.reply.SessionID return req_res.response.reply.SessionID except Exception as exp: raise EbayAdapterError(req_res.error() if (req_res and req_res.error()) else str(exp)) @property def sign_in_url(self): """ Build eBay sing-in URL :return: str """ if not self.session_id: EbayAdapterError('Session ID isn`t set') url = self.URL if TEST_MODE: url = self.SANDBOX_URL return url.format(ebay_ru_name=EBAY_RU_NAME, session_id=self.session_id) def fetch_token(self): """ Get token data :return: dict """ if not self.session_id: EbayAdapterError('Session ID isn`t set') req_res = self.__request('FetchToken', {'SessionID': self.session_id}) if req_res.response_code() != 200: raise EbayAdapterError('Fetch token ebay error') return req_res.response.reply And my tests for it: class EbayAdapterTest(TestCase): def setUp(self): self.service … -
Django CMS display name of model entry
I would like to have the entries for a model listed in the admin panel showing the name of the model entry. Currently it shows the following However, instead of Objekt object I would like to have Objekt OBJECT_NAME where OBJECT_NAME is the name of the object. My model is the following: models.py class Objekt(models.Model): name = models.CharField(max_length=100) beschreibung = models.TextField() aktiv = models.BooleanField(default=False) def __unicode__(self): return self.name class Meta: verbose_name = 'Miet-Objekt' verbose_name_plural = 'Miet-Objekte' and admin.py class ObjektAdmin(admin.ModelAdmin): model = Objekt can_delete = True How can I achieve this?