Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement a/b testing on Django 1.11? [on hold]
Almost week i try to implement this thing to production, but all packages are out-of-date. Maybe someone who made this a short while ago can help? -
Django SQL Server ForeignKey that allows NULL
I've been struggling with this issue for some time. I'm switching one of my apps from Postgres to SQL Server database and I'm facing an issue with ForeignKey field. I'm running latest SQL Server version with Django 1.11 and using django-pyodbc-azure app. class Owner(models.Model): name = models.TextField() dog = models.ForeignKey('Dog', related_name='+') class Dog(models.Model): name = models.TextField() owner = models.ForeignKey('Owner', null=True, related_name='+') When I try to insert a new record I get the following message: dog = Dog.objects.create(name='Rex') owner = Owner.objects.create(name='Mike', dog=dog) dog.owner = owner dog.save() ('23000', u"[23000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Violation of UNIQUE KEY constraint 'UQ__owner__EF6DECB9214EF1D9'. Cannot insert duplicate key in object 'dbo.owner'. The duplicate key value is (). (2627) (SQLExecDirectW)") -
django admin redactor with jet template
how i can solve this? The other fields are behind of redactor widget -
Django: Messages App
Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) I wants to order the Users based upon who sent a message to request.user or to whom request.user sent a message most recently! As we see on social networks. This is what I tried, users = User.objects.filter(Q(sender__receiver=request.user) | Q(receiver__sender=request.user)).annotate(Max('receiver')).order_by('-receiver__max') This code is working fine only when request.user sends someone a message. It's not changing the ordering of messages in case if someone sends a message to request.user. I also tried, users = Message.objects.filter(sender=request.user, receiver=request.user).order_by("created_at") But, I could't filter out the distinct users. It's showing equal number of users as messages. How can I fix this problem? Thank You! -
Wand can't open existing file
I want to open pdf file and get the only first page and save it as image. I've used this solution and it worked perfect. It still works in my local environment, but it fails to work in Travis recently. So, yes, this code from my unittest and I'm trying to run it in Travis. I have a test pdf file and I want to open it: import os from wand.image import Image root_path = 'some/correct/path' filename = 'two_page_pdf.pdf' full_path = os.path.join(root_parg, filename) Image(file=open(full_path, mode='rb'), resolution=300) # Error!!! ----------------------------------------------- DelegateError Traceback (most recent call last) <ipython-input-2-1b1fd9537a14> in <module>() ----> 1 Image(file=open(full_path, mode='rb'), resolution=300) ~/virtualenv/python3.5.3/lib/python3.5/site-packages/wand/image.py in __init__(self, image, blob, file, filename, format, width, height, depth, background, resolution) 2738 b'buffer.' + format) 2739 if file is not None: -> 2740 self.read(file=file, resolution=resolution) 2741 elif blob is not None: 2742 self.read(blob=blob, resolution=resolution) ~/virtualenv/python3.5.3/lib/python3.5/site-packages/wand/image.py in read(self, file, filename, blob, resolution) 2820 r = library.MagickReadImage(self.wand, filename) 2821 if not r: -> 2822 self.raise_exception() 2823 2824 def close(self): ~/virtualenv/python3.5.3/lib/python3.5/site-packages/wand/resource.py in raise_exception(self, stacklevel) 220 warnings.warn(e, stacklevel=stacklevel + 1) 221 elif isinstance(e, Exception): --> 222 raise e 223 224 def __enter__(self): DelegateError: Postscript delegate failed `/tmp/magick-5ypXvY6l': No such file or directory @ error/pdf.c/ReadPDFImage/677 Check file: os.path.isfile(full_path) == True … -
Using array parameters in a Django POST request
How to get array paramaters posted to django backend? I am using a jQuery plugin (DataTables Editor) that POSTs a data array parameter like data[id][fieldname][value] How do I get django to accept and use these parameters. -
how to login user from email or phone OTP in django
I want to remove the password feild and use mobile or email to send OTP and user should login through that OTP! I'm not getting a clear idea on how to do it can anyone help. Thank you -
How to create new tables in Database for each day in Django
I have an understanding question because I'm thinking about how I should manage my data in Django or the database. It is a table with about 2000 lines per day and 8 columns. I would like to store all daily data of the last 10 years into the database and add new data every day. It is a good idea to create a database table for each day. In Django, a table is created for each model, but it is not intended for the inventor to create 5000 models in Django. Is it the only way I use raw SQL to create the tables? Or is there a way I have not discovered in the documentation? -
compress image size before saving in database in javascript?
Is there any way to compress or reduce image size during uploading at client side and before saving in database in javascript? There are some options i have seen but they are using PHP i want that in javascript with HTML. I am using Django framework so it will be easier to implement in JS rather than in PHP. When we are uploading that image it should be compressed automatically and then it will be saved in database. -
ImportError raised trying to import a function
Context: I am trying to build a Django app that uses this package:django-minio-storage. I am trying to extend a certain class in the package with the following class: @deconstructible class MinioStoreStorage(MinioStorage): def __init__(self, bucket_name): client = create_minio_client_from_settings() base_url = bucket_name # base_url = get_setting("MINIO_STORAGE_STATIC_URL", None) bucket_name = bucket_name auto_create_bucket = True presign_urls = True super(MinioStoreStorage, self).__init__( client, bucket_name, auto_create_bucket=auto_create_bucket, base_url=base_url, presign_urls=presign_urls ) Problem: I can not import the function create_minio_client_from_settings. This function resides in the file storage.py of the package. The same file where resides the class MinioStorage. I can also import successfully another function (get_setting) that is in the same file and use it with no problem, but trying to do the same for create_minio_client_from_settings raises an ImportError. storage.py Here is a snippet of the code of the package: @deconstructible class MinioStorage(Storage): """An implementation of Django's file storage using the minio client. The implementation should comply with https://docs.djangoproject.com/en/dev/ref/files/storage/. """ ... ... ... def get_setting(name, default=_NoValue, ): result = getattr(settings, name, default) if result is _NoValue: print("Attr {} : {}".format(name, getattr(settings, name, default))) raise ImproperlyConfigured else: return result def create_minio_client_from_settings(): endpoint = get_setting("MINIO_STORAGE_ENDPOINT") access_key = get_setting("MINIO_STORAGE_ACCESS_KEY") secret_key = get_setting("MINIO_STORAGE_SECRET_KEY") secure = get_setting("MINIO_STORAGE_USE_HTTPS", True) client = minio.Minio(endpoint, access_key=access_key, secret_key=secret_key, secure=secure) return … -
Django send new sessionId Cookie even though previous session cookie is not expired
On page load , I look at the (Firefox) developer console, in the network cookie tab. I see Django is correctly creating a new session with expires date two weeks ahead. Refreshing the /admin/login/?next=/admin/ page a few times, I see Django send another sessionId cookie (after less than a minute) Basically the problem I am seeing is that the admin user get logged out after a few refreshing What can cause that? -
Search results using ajax in django
I am searching the products from the database using this search bar, but as soon as this search bar shows me results the header(dark blue area)part also expands along with the search results something like this. I want when search results are shown the header should not expand, the search results should go over the header. My search box code is like this- <div class="search_box"> {% csrf_token %} <form> <div class="form-group"> <input type="text" id="search" name="search" class="form-control" placeholder="Search"> <ul id="search-results" class="list-group"> </ul> </div> </form> </div> i am using django with ajax, so i am displaying my search result like this- {% if p1.count > 0 %} {% for p in p1 %} <li class="list-group-item"><a href="/products/product_info/{{p.id}}/">{{p.productname}}</a></li> {% endfor %} {% else %} <li>None to show!</li> {% endif %} -
Wagtail, accessing home page in jinja2 templates
I have two pages extending a base.html. home_page and works_page. I am trying to add a favicon image to the base.html. I have decided to add a favicon field to home_page which is my root page. <link rel='icon' href='/media/{{page.favicon.file}}' /> When active page is works_page the {{page}} has no favicon field and I get an error. Is there a way to access always the root page from templates? as {{ root_page }} maybe? -
Django REST Framework Extension recursive nested urls
I want to create URLs for CMS portion of project I have following models class Category(models.Model): name = models.CharField(max_length=150) parent = models.ForeignKey('self', blank=True, null=True) class Page(models.Model): title = models.CharField(max_length=255) content = models.TextField() slug = models.CharField(max_length=255) category = models.ForeignKey(Category, related_name='pages') I want the following URL structure for my categories /categories/{parent category}/ /categories/{parent category}/{child category}/.../{child category}/pages/ How would I accomplish this with DRF-Extensions or any other plugin? -
Loading django based webpage with Apache and mod_wsgi, haystack takes upto 10 sec.
WSGIScriptAlias / /var/www/swpdoc/swpdoc/wsgi.py <Directory /var/www/swpdoc> Require all granted </Directory> WSGIDaemonProcess swpdoc python-home=/var/www/swpdoc/venswpdoc python- path=/var/www/swpdoc WSGIProcessGroup swpdoc Any suggestion to improve the loading time ? -
A form with filtering
I'm trying to set some filtering for a query through a form but I don't really know how to build it. So I want to filter by "recruitment", "game" and/or "platforme". The problem is that I don't really know how to build it in my views.py. template.html <form method="POST"> {% csrf_token %} <select name="recruitment" onchange=this.form.submit();> <option disabled {%if form.recruitment == Null%}selected{%endif%}>Recrutement</option> <option value="all" {%if form.recruitment == "all"%}selected{%endif%}>Tout</option> <option value="open" {%if form.recruitment == "open"%}selected{%endif%}>Ouvert</option> <option value="close" {%if form.recruitment == "close"%}selected{%endif%}>Fermé</option> </select> <select name="plateform" onchange=this.form.submit();> <option disabled {%if form.plateform == Null%}selected{%endif%}>Plateforme</option> <option value="all" {%if form.plateform == "all"%}selected{%endif%}>Toutes</option> {%for plateform in plateform%} <option value="{{plateform.guid}}" {%if form.plateform == plateform.guid%}selected{%endif%}>{{plateform.name}}</option> {%endfor%} </select> <select name="game" onchange=this.form.submit();> <option disabled {%if form.game == Null%}selected{%endif%}>Jeu</option> <option value="all" {%if form.game == "all"%}selected{%endif%}>Tous</option> {%for game in game%} <option value="{{game.guid}}" {%if form.game == game.guid%}selected{%endif%}>{{game.title}}</option> {%endfor%} </select> </form> views.py def view_watch_teams(request): media = settings.MEDIA try: myteam = Team.objects.get(owner=request.user) except: pass team = Team.objects.all() game = Games.objects.all() plateform = Plateform.objects.all() if request.POST: form = request.POST My query should be something like this : result = Relation.objects.filter(recruitment=form['recruitment'], on_game=form['game'], on_plateform=form['plateform']) This kind of query only work if all filters are set. So, what is the correct synthax to make a query more dynamic ? Thank you … -
How to get image from input field using jquery
I am trying to send image from an html page to django view. But I am not able to attain the data. The following is my code. <input type="file" id = "imageupload" onchange = "sendimg()" /> <script> var sendimg = function(){ var img = document.getElementById("imageupload") $.ajax({ type: "POST", url: "/test/", data: { "imgfile": img, }, processData: false, contentType: false, success: function(data){ console.log("success"); console.log(data); }, failure: function(data){ console.log("failure"); console.log(data); }, });} </script> The django view is @csrf_exempt def testimg(request): print "the request",request.POST data = {"data": "ok" } return JsonResponse(data) The print statement gives the request <QueryDict: {}> What am I doing wrong ? -
Django-tenant-schemas and GeoDjango together
I want to use django-tenant-schemas and GeoDjango (postgis) in my Django project. I've a single default database. But both django-tenant-schemas and GeoDjango want me to set a custom Engine for the Database in the settings. django-tenant-schemas want it to be set to tenant_schemas.postgresql_backend while GeoDjango wants it to be set to django.contrib.gis.db.backends.postgis. Is there any work around to this issue? -
How to show django ImageField in browser URL
I have a webscraping app that downloads images from a website and stores it in an ImageField of one of my models. models.py class Article(models.Model): title = models.CharField('Title', max_length=300) url = models.CharField('URL', max_length=200) hero_image = models.ImageField(upload_to='pictures', max_length=255) My hero_image field looks like this in my project: "http://localhost:8000/media/pictures/gettyimages-585288019.jpgw210h158crop1quality85stripall" And the images are stored at myproject/myproject/pictures: myproject ├── myproject │ ├── settings.py ├── pictures ├── manage.py When I click the sample link above I automatically download the image, but instead I would like to show the image in the browser. What I've done so far myproject/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('core.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_URL = '/media/' There are a lot of topics similar to my question on SO but I've read a bunch of them and still can't find one that seems to help me solve my problem. -
Service Worker does not fire upon fetch and return cached data
I am using service workers in one of my projects. On call, my service worker gets successfully registered and it caches all provided URLS. But when I reload my page, all cached data is either picked from disk cache or memory cache and not from service worker. I refered this question Service worker is caching files but fetch event is never fired and cross checked that there is not a problem with scoping. service-worker.js var CACHE_NAME = 'home-screen-cache'; var urlsToCache = [ '/static/client-view/fonts/fontawesome-webfont.eot', '/static/client-view/fonts/fontawesome-webfont.woff', '/static/client-view/fonts/fontawesome-webfont.ttf', '/static/client-view/fonts/fontawesome-webfont.svg', '/static/css/cricket.css', '/static/client-view/js/jquery.mobile.custom.min.js', '/static/client-view/js/jquery-2.1.4.min.js', '/static/js/cricket_matches.js' ]; self.addEventListener('install', function(event) { // Perform install steps event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Opened cache'); return cache.addAll(urlsToCache); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return response if (response) { console.log("Found in cache"); return response; } console.log("Not found in cache"); return fetch(event.request); } ) ); }); service-worker registration script if ('serviceWorker' in navigator) { window.addEventListener('load', function() { navigator.serviceWorker.register('{% static 'service-worker.js' %}').then(function(registration) { // Registration was successful console.log('ServiceWorker registration successful with scope: ', registration.scope); }, function(err) { // registration failed :( console.log('ServiceWorker registration failed: ', err); }); }); } If you need any kind of additional data, mention in comments. Please help. -
django: update database upon onsubmit dropdown
I am trying to create a ticketing system. What I want to do is when I change the Status dropdown list it should update the status of the ticket in the database. Also, I would like to update and view in the same page. Any insights if that would be possible? forms.py class ViewForm(forms.Form): statuses = [ ('In Progress', 'In Progress'), ('On Hold', 'On Hold'), ('Done', 'Done'), ('ForQA', 'ForQA'), ('QAPassed', 'QAPassed'), ('QARevs', 'QARevs'), ] status = forms.ChoiceField(label='Status', required=True, choices=statuses, widget=forms.Select(attrs={'onchange': 'actionform.submit();'})) views.py def view_sheet(request, project_id): project = Project.objects.get(pk=project_id) tickets = Ticket.objects.filter(project=project_id) form = ViewForm() context = { 'project': project, 'tickets': tickets, 'form': form, } return render(request, 'project/sheet/view.html', context) view.html <div class="tracker-sheet"> <div class="project-name"> <h1>{{project.name}}</h1> </div> <div class="actions"> <a href="{% url 'add_ticket' project.id %}"> <button type="submit">New Ticket</button> </a> </div > <div class="tracker-table"> <table> <tr> <th>Total Worked</th> <th>Status</th> <th>Status Date</th> <th>Received</th> <th>Due Date</th> <th>Agent</th> <th>Sub Type</th> <th>CID</th> <th>Link</th> <th>Task Description</th> <th>Server</th> <th>Qty</th> <th>Info</th> </tr> {% for ticket in tickets %} <tr> <td><span class="table-constant"></span></td> {% for field in form %} <td>{{field}}</td> <!-- Status dropdown list --> {% endfor %} <td><span class="table-constant">{{ticket.status_date}}</span></td> </form> <td><span class="table-constant">{{ticket.received}}</span></td> <td><span class="table-constant">{{ticket.due_date}}</span></td> <td><span class="table-constant"></span></td> <td><span class="table-constant">{{ticket.sub_type}}</span></td> <td><span class="table-vary"></span></td> <td><span class="table-constant">{{ticket.link}}</span></td> <td><input type="submit" value="{{ticket.task_description}}"</td> <td><span class="table-constant"></span></td> <td><span class="table-constant">{{ticket.qty}}</span></td> <td></td> </tr> … -
Django rest framework not work with regex validator
In my model I have a field address = models.CharField(_('address'), blank=True, max_length=42, editable=False, validators=[validators.RegexValidator(regex='^0x[a-fA-F0-9]{40}$')]) But when I tried to apply value more then 42 symbols, I get django error: value too long for type character varying(42) When I set value: test for example, it passes validation(but shouldn't) My serializer is simple: class KYCSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' -
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
how to solve this error " Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) " . It appears when i run my engine.py . Could you give me a help? -
Django query: how to apply the mode calculation in the query?
In a previous question I was asking about how to do a complex query in Django. Here is my example model: class Foo(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=100, blank=True) foo_value = models.CharField(max_length=14, blank=True) time_event = models.DateTimeField(blank=True) # ... and many many other fields Now in my previous question @BearBrown answered me with using the When .. then expression to control my query. Now I need something more. I need to calculate the mode (most repeated value) of the quarter of the month in the time_event field. Manually, I do it like this: - I manually iterate over all records for the same user. - Get the day using q['event_time'].day - Define quarters using quarts = range(1, 31, 7) - Then, append the calculated quarters to a list month_quarts.append(quarter if quarter <= 4 else 4) - Then get the mode value for this specific user qm = mode(month_quarts) Is there a way to automate this mode calculation function in the When .. then expression instead of manually iterating through all records for every user and calculating it? -
How to access extra data sent with POST request in Django Rest Framework serializer
I'm trying to send an extra array with a POST request that creates a group. POST /groups/ { "name": “New Group“, "users_to_invite": [ 1, 2, 6 ] } I'm using Django Rest Framework's ListCreateAPIView to handle the request: class GroupListView(ListCreateAPIView): queryset = Group.objects.all() def get_serializer(self, *args, **kwargs): kwargs['context'] = self.get_serializer_context() # Use a dedicated serializer to inspect the field with users to invite if self.request.method == 'POST': return GroupCreateSerializer(*args, **kwargs) return GroupSerializer(*args, **kwargs) I want to get to the contents of the users_to_invite array in a serializer to create invitation objects. However, I'm unable to do so because somehow the array is not there when I'm accessing it in the serializer. class GroupCreateSerializer(ModelSerializer): def create(self, validated_data): # Get user ids to invite # !! It fails here !! invitations_data = validated_data.pop('users_to_invite') # TODO: Iterate over ids and create invitations # Create a group group = Group.objects.create(**validated_data) return group class Meta: model = Group fields = ('id', 'name', ) Array is not there so naturally I'm getting the error: File "...my_api/serializers.py", line 303, in create invitations_data = validated_data.pop('users_to_invite') KeyError: 'users_to_invite' How can I make the array to appear there? Modifying the model does not sound like a good idea because I …