Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GeoDjango, distance filter based on database column taking into account the radius of both the seeker and the one he is looking for
I need to find objects taking into account the radius of both the seeker and the one he is looking for. How i can do this? At now i can filter from seeker side: n_range = Obj.objects.filter(location__distance_lt=( obj.location, Distance(mi=obj.radius) ) ) This is my model: class Obj(models.Model): RADIUS_CHOICES = [ (1, "1 km round"), (2, "2 km round"), (3, "3 km round"), ] radius = models.PositiveIntegerField( default=RADIUS_CHOICES[0][0], choices=RADIUS_CHOICES ) location = models.PointField(null=True, blank=True) It is necessary that in the end result there should be only those objects that fall into the radius of the seeker, and at the same time, the seeker must fall into the radius of those whom he seeks -
How to use highstock with django
I can't use Highstock correctly. I'm trying to display candle stick chart with using django and highstock. My code transfer some ohlcv data from django backend to html frontend in json format. And Highstock displays chart but not correctly. I read highstock official documents but I can't understand many options because of I'm newbie(not only python and java script even programing). Please look at my code and a result. I'd like to teach me. models.py from django.db import models class OandaChartData(models.Model): exchange_name = models.CharField(max_length=50) pair = models.CharField(max_length=10) open_time = models.DateTimeField() open_value = models.FloatField() high_value = models.FloatField() low_value = models.FloatField() close_value = models.FloatField() volume = models.FloatField() write_time = models.DateTimeField(null=True) views.py from django.shortcuts import render from .models import OandaChartData from django.core import serializers import json from datetime import timezone def highstock_view(request): record_list = [] records = OandaChartData.objects.all().order_by("id")[0:43200] for record in records: open_time = record.open_time.replace(tzinfo=timezone.utc).timestamp() * 1000 open_value = record.open_value high_value = record.high_value low_value = record.low_value close_value = record.close_value volume = record.volume record_list_tmp = [open_time, open_value, high_value, low_value, close_value, volume] record_list.append(record_list_tmp) record_json = json.dumps(record_list) return render(request, 'scraping/highstock_view.html', {'record_json':record_json}) HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>HighStockView</title> </head> <body> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="https://code.highcharts.com/stock/highstock.js"></script> <script src="https://code.highcharts.com/stock/modules/exporting.js"></script> <div id="container" style="height: 400px; min-width: 310px"></div> <script> let … -
How to store SVG files in Django model?
I've got a simple Django template that allows a user to input an image from the system. It should accept only JPEG, JPG, PNG and SVG files. The first three seems to work well. However, SVG doesnt get uploaded. Instead, it sends an error message stating: 'Upload a valid image. The file you uploaded was either not an image or a corrupted image' How do I store a SVG file into my database model? You can view my current code below: models.py from django.db import models import os from PIL import Image from datetime import date import datetime def get_directory_path(instance, filename): file_extension = os.path.splitext(filename) today = date.today() t = datetime.datetime.now() day, month, year = today.day, today.month, today.year hour, minutes, seconds = t.hour, t.minute, t.second if file_extension[1] in ['.jpg','.png','.jpeg','.svg']: filename = str(day) + str(month) + str(year) + str(hour) + str(minutes) + str(seconds) + '.png' dir = 'media' else: dir = 'others' path = '{0}/{1}'.format(dir, filename) return path # Create your models here. class Image(models.Model): image = models.ImageField(upload_to = get_directory_path, default = 'media/sample.png') created_date = models.DateTimeField(auto_now = True) def __str__(self): return str(self.id) forms.py: from django import forms from myapp.models import Image class ImageForm(forms.ModelForm): """Image upload form""" class Meta: model = Image exclude … -
how to fix this exception in django code?
i have a search form that allow the user to search for stored records in the database where the user enter the number and the function will get the user input from the URL. the problem is that is always display the below error: ValueError: invalid literal for int() with base 10: b'12 21:00:00' i don't know what it mean and how to fix it. views.py def searchFolder(request): query = request.GET.get('q') try: print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>", len(query)) print("search for :",query) FilterQuery = Folder.objects.filter(Q(FolderNum__icontains = query)) print("FilterQuery============================", FilterQuery) ListID = list(FilterQuery) if query == "": messages.error(request,"Search field is empty!") print("Search field is empty!!!!!!!!!!!!!!!!") return redirect('create_folder_test') elif ListID == []: messages.error(request,"Record not found/does not exist!") print("Record does not exist!!!!!!!!!!!!!!!!") return redirect('create_folder_test') else: return render(request, 'blog/update2.html', {'FilterRecords': ListID}) except Exception as e: messages.error(request,"ValueError") print("Value Error!!!!!!!!!!!!!!!!",e) return redirect('create_folder_test') -
Is there 3rd party software for storing and displaying, but not processing payment information?
My business (travel agency) must accept payment from a customer, then broker the payment directly to the travel provider (say, a cruise line). The providers do not have API's, and it is not customary (nor financially viable) to actually process the payment to our own merchant account. This means customers supply us with card information which we have to store, queue to accounting, then remit the payment to the supplier. We are currently producing an in-house proprietary software package for the business. We need to have this functionality, but we would like to issue private keys to only a handful of local machines capable of decrypting the data to plain text. The back end is powered by Django and most of the modules it supports are to a VUE.JS front-end application. Is there an established approach for doing this? Are there any 3rd party providers we could off load this to? All of the 3rd parties I see are only for processing the payment, not to view it later in plain text to remit to an entirely different vendor. None of the major travel providers accept payment cooperation with Stripe or any such 3rd party. -
How to call a function before a django app start?
In my django project i have to check if a database/table exist before starting application, i don't know how is better insert the code for check. I try to add in views.py into login function a try except block but i was try to find an elegant and more effective solution. Thanks in advance -
Usage permissions for AppHooks in DjangoCMS
I'm registering a new custom AppHook in DjangoCMS (v.3.5.3): @apphook_pool.register class CustomAppHook(CMSApp): name = _("CustomAppHook") def get_urls(self, page=None, language=None, **kwargs): return ["customapp.urls"] I want to hide this app hook in the dropdown menu in the extended page settings. Only superusers should see and use it. To exclude the "extended page settings" for other users/groups is no option here... Is there another decorator to use? There exists the permissions = True attribute in the CMSApp class. But this says: "if set to true, apphook inherits permissions from the current page". Not excactly what I want/need. -
Django : Fetch application User Model for multiple application from Central Database
Django : I have 6 applications which are already live but they have their own user database table and Model(All have different field names and they have their own extra column.Now I have to go and add user in every application. I have one Idea that I can create cron job which syncs data to current database from central database, but still I have to maintain all local database. Can I use something like singleton class and remove applications user database and sync user object once from central database and use that? I am new to django and I would welcome any suggestions or any implementation sample. -
How to make the input field appear in update profile form?
I am trying to make the Id_card_number input field to be appeared in Profile Update Form. Although it is appeared in admin page due to migration in model.py, but it is not appearing in browser page. the model is Profile not User forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username','email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image','Id_card_number'] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') User._meta.get_field('email',)._unique = True Id_card_number = models.CharField(max_length=15) def __str__(self): return f'{self.user.username} Profile' -
Custom Serializer and ViewSet for ManyToManyField in DRF
I have a M2M relationship between the Entity and EntityGroup and I want to save the corresponding entity index to the EntityGroup just like an entity array to database. Since I used a custom through Model with additional field index inside, I need to serialize the index to the corresponding entity to the response, how should I implement that? I'm new to django and django-rest-framework and it seems there are not similar M2M examples after a few google search. Here is my thought, a serializer could only serialize the only one model's fields with ForeignKey relationship, a viewset could have a custom model based on queryset which could merge the relationships for a few models. So I need to implement a more expandable viewset with a custom queryset inside? Please help! Great thanks! Here is my code: models.py class Entity(models.Model): uuid = models.CharField() name = models.CharField() class EntityGroup(models.Model): name = models.CharField() entities = models.ManyToManyField(Entity, through='EntityGroupRelationship', through_fields=('group', 'entity'), related_name='groups' ) class EntityGroupRelationship(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE) group = models.ForeignKey(EntityGroup, on_delete=models.CASCADE) index = models.PositiveIntegerField() serializers.py class EntitySerializer(serializers.ModelSerializer): class Meta: model = Entity fields = '__all__' class EntityGroupRelationshipSerializer(serializers.ModelSerializer): class Meta: model = EntityGroupRelationship fields = '__all__' class EntityGroupSerializer(serializers.ModelSerializer): entities = EntitySerializer(many=True) class Meta: … -
How to fix this error, I just used django
How to fix this error my code program, I just used Django and just made my first project, I made project use "django-admin startproject mysite" and then the project will be called mysite, in mysite there is manage.py, when I running manage.py use " py manage.py runserver" shows error, how can I fix it? This is My code: import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Here is Messages Errors: C:\Users\ulfahartinam\mysite>py manage.py runserver File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax -
Django - How to pass a form instance from one view to another
I have a form with multi steps in it. First part uses a forms.ModelForm, once completed, the user is re-directed to another view with a forms.Form in it. Ideally, I would like to save the first form only if the secondary form is valid and save them both at the same time if that's the case. I usually use self.request.session to pass data from one view to another, but a form's instance is not serializable, hence, can not append it to the session. Would anyone have any suggestions? Thank you. -
Action that runs automatically when you open the django suit manager
It is possible to perform an action automatically when opening the django suit administration panel, this in order to define specific tasks when the django suit main screen is opened, or when the screen of a specific model is loaded -
Exact query in Django-Haystack
I'm trying to fix my Django-haystack combined with Elasticsearch search results to be exact. The principa; usecase is that a user enter is destination and get only the results that matches this given place. But the problem I have now is that when a user try for example, a query for "Mexico", the search results also returns information in "Melbourne" which is far from being user-friendly and accepted. What I've tried so far but still not working: My forms.py from haystack.forms import FacetedSearchForm from haystack.inputs import Exact class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag = data.get('ptags', []) self.q_from_data = data.get('q', '') super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() # Ideally we would tell django-haystack to only apply q to destination # ...but we're not sure how to do that, so we'll just re-apply it ourselves here. q = self.q_from_data sqs = sqs.filter(destination=Exact(q)) print('should be applying q: {}'.format(q)) print(sqs) if self.ptag: print('filtering with tags') print(self.ptag) sqs = sqs.filter(ptags__in=[Exact(tag) for tag in self.ptag]) return sqs My search_indexes.py import datetime from django.utils import timezone from haystack import indexes from haystack.fields import CharField from .models import Product class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField( document=True, use_template=True, template_name='search/indexes/product_text.txt') title = … -
How to access data in get_context_data RSS Feed django 2.2
I've been following these docs https://docs.djangoproject.com/en/2.2/ref/contrib/syndication/ and I can't figure out how to access the context dictionary that returns from the get_context_data(self, item, **kwargs): It works and when I do a debug print just before the return it returns a dictionary with the last entry as the user that uploaded the video. the debug print is print(context['author']) which returns as expected everytime the feed is interacted with. feeds.py link = '/video-feeds/' description = 'New Video Posts' def items(self): return VideoPost.objects.all() def get_context_data(self, item, **kwargs): context = super().get_context_data(**kwargs) context['author'] = item.author print(context['author']) return context def item_title(self, item): return item.title def item_description(self, item): return item.description def item_link(self, item): return reverse('video_post', args=[item.pk]) views.py def video_list(request): feeds = feedparser.parse('http://localhost:8000/profs/video-feeds') return render(request, 'vids/video_list.html', {'feeds': feeds}) template {% for thing in feeds.entries %} <h1>Author</h1><br> {{thing.author}} <-- Nothing is printed here <h1>Title</h1> {{thing.title}}<br> <h1>Description</h1> {{thing.summary}}<br> <h1>Video Link</h1> <a href="{{thing.link}}">{{thing.title}}</a><br> {% endfor %} -
How to add view count for articles?
Currently I am developing a blog that contains articles. I wish to add the view count for the articles so that when a user views the article page, that view count will increase. This is for my models.py file: class Article(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='kbase_posts') # body = models.TextField() #body = RichTextField(blank=True, null=True) body = RichTextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. tags = TaggableManager() #topic = models.CharField(max_length=250, blank = True) -
Why am I getting 'Foreign Key Mismatch' when trying to save a model form in Django?
I am trying to save an instance of a modelform in Django. I have setup a template to input information to the form and a view to handle the save. The form validates fine, but when trying to save it generates a foreigkey mismatch error. What am I doing wrong here? I am running Django 2.0.0. I have already tried adding and removing the primary_key option without any luck and deleting my sqlite database, clearing all pycache, and migrating again. The problem persists. #models.py from django.db import models import uuid from users.models import Company, CustomUser from delivery import settings class Location(models.Model): location_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) address = models.CharField(max_length = 120) date_added = models.DateField(auto_now_add = True) class Shipment(models.Model): date_created = models.DateField(auto_now_add=True) sender_company = models.ForeignKey(Company, on_delete = models.PROTECT, related_name='sender') receiver_company = models.ForeignKey(Company, on_delete = models.PROTECT, related_name='receiver') origin = models.ForeignKey(Location, on_delete = models.SET_DEFAULT, default = 'Location no longer active.', related_name='origin') destination = models.ForeignKey(Location, on_delete = models.SET_DEFAULT, default = 'DESTINATION UNKNOWN', related_name='destination') expected_arrival = models.DateField() weight = models.FloatField() current_handler = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.SET_DEFAULT, default = 'UNKNOWN') shipment_id = models.UUIDField(unique=True, primary_key = True, default=uuid.uuid4, editable=False) #forms.py from django import forms from .models import Location, Shipment class LocationRegisterForm(forms.ModelForm): class Meta: model = Location fields … -
Change button depending on like status
I am attempting to add a post liking system to my website. I already have the functionality to like and unlike posts, however I can't get the button value to change in the template. models.py class Post(models.Model): file = models.FileField(upload_to='files/') summary = models.TextField(max_length=600) pub_date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='likes') is_liked = models.BooleanField(default=False) views.py def likepost(request, pk): if request.method == 'POST': user = request.user post = get_object_or_404(Post, pk=pk) if post.likes.filter(id=user.id).exists(): post.is_liked = True post.likes.remove(user) else: post.is_liked = False post.likes.add(user) return redirect('home') home.html {% if post.is_liked == True %} <a href="javascript:{document.getElementById('like__post').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Like {{ post.total_likes }}</button></a> {% else %} <a href="javascript:{document.getElementById('like__post').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Unlike {{ post.total_likes }} </button></a> {% endif %} <form id="like__post" method="POST" action="{% url 'likepost' post.id %}"> {% csrf_token%} <input type="hidden"> </form> -
Replace an image through Django admin panel
I want to be able to replace my homepage image from the Django admin panel. I can upload to my ../media/homepage directory just fine but I want to first delete any image named "bg.jpg" and rename my new image to "bg.jpg". models.py from django.db import models from django.core.files.storage import FileSystemStorage from datetime import datetime class Homepage(models.Model): homepage_image = models.ImageField(upload_to="../media/homepage",blank=True) image_text = models.CharField(max_length=200, blank=True) header_title = models.CharField(max_length=200, blank=True) header_text = models.TextField(blank=True) class Meta: verbose_name_plural = "Homepage" def __str__(self): return "Homepage" -
Django rest framework and XML. Change item_tag_name, root_tag_name and other
I set up a rest framework in my project according to Quickstart Everything works, but, as it usually happens, not without questions! My serializer.py: class kvSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = kv fields = ['title', 'price', 'address'] My views.py: class kvViewSet(viewsets.ModelViewSet): queryset = listings.objects.all() serializer_class = kvSerializer My XML: Object title 100 object address Question: How can I change tags <root> and <list-item>? <root> should be called <feed> <list-item> should be called <offer> Before tag <offer> need to insert tag <creation-date> My final XML should be as follows: <feed> <creation-date>Date</creation-date> <offer id=1> <title> Object title </title> <price>100</price> <address> object address </address> </offer> <offer id=2> <title> Object title </title> <price>100</price> <address> object address </address> </offer> </feed> -
NotADirectoryError at /admin/
I'm new in django, and I have a problem with The Django admin documentation generator I have install Docutils and all requirements specified in the documentation Now, the documentation is showing in my django admin: but the issue is when i want tu retrieve a link like LogEntry i got a following error: > NotADirectoryError at /admin/doc/views/frontend.views.index/ [Errno > 20] Not a directory: > '/usr/local/lib/python3.7/site-packages/docutils-0.16b0.dev0-py3.7.egg/docutils/writers/html4css1/template.txt' > Request Method: GET Request > URL: http://localhost:8008/admin/doc/views/frontend.views.index/ > Django Version: 2.2.1 Exception Type: NotADirectoryError Exception > Value: [Errno 20] Not a directory: > '/usr/local/lib/python3.7/site-packages/docutils-0.16b0.dev0-py3.7.egg/docutils/writers/html4css1/template.txt' > Exception > Location: /usr/local/lib/python3.7/site-packages/docutils-0.16b0.dev0-py3.7.egg/docutils/writers/_html_base.py > in apply_template, line 77 Python Executable: /usr/local/bin/python > Python Version: 3.7.4 Python Path: ['/webapp', > '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', > '/usr/local/lib/python3.7/lib-dynload', > '/usr/local/lib/python3.7/site-packages', > '/usr/local/lib/python3.7/site-packages/docutils-0.16b0.dev0-py3.7.egg'] > Server time: lun, 5 Aoû 2019 21:45:56 +0000 Here are my settings: # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'rest_framework_swagger', 'api.apps.ApiConfig', 'frontend.apps.FrontendConfig', 'dashboard.apps.DashboardConfig', ] 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', 'django.contrib.admindocs.middleware.XViewMiddleware' ] and my urls files look like: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('frontend.urls')), path('dashboard/', include('dashboard.urls')), path('admin/doc/', include('django.contrib.admindocs.urls')), path('admin/', admin.site.urls), path('api/', include('api.urls')), ] -
Ajax does not show any functionality in Django
I want to display an error screen for a new user who wants to retrieve a user name already taken using Ajax, but the project continues to run as if Ajax did not exist and django gives its own error. register.html {% extends "layout.html"%} {% load crispy_forms_tags %} {% block body %} <script> $("#id_username").change(function () { var username = $(this).val(); $.ajax({ url: '/ajax/validate_username/', data: { 'username': username }, dataType: 'json', success: function (data) { if (data.is_taken) { alert("A user with this username already exists."); } } }); }); </script> <body style = background-color:midnightblue;color:White;> <div class="row"> <div class="col-md-6 offset-md-3"> <h3>Register</h3> <hr style="background:white;"> <form method="post"> {% csrf_token %} {{form|crispy}} <br> <button type="submit" class ="btn btn-danger">Register</button> </form> </div> </div> </body> {% endblock body %} views.py def validate_username(request): username = request.GET.get('username') data = { 'is_taken' :p User.objects.filter(username__iexact=username).exist() } return JsonResponse(data) urls.py urlpatterns = [ path('login/',views.loginUser,name = "login"), path('register/',views.register,name = "register"), path('logout/',views.logoutUser,name = "logout"), path('panel/<str:username>',views.userPanel,name="userPanel"), path('ajax/validate_username/',views.validate_username,name="validate_username") ] -
django how to find the minimum value NOT in a field?
Assume that we have records with 1,2,4,5,6, ... in a field named Code in table Material. How can I write an orm to return 3 that is the minimum number not in the existing records? -
Add Multiple Placemarkers on Google Earth Fetching Address From SQL
I am trying to connect Google earth using python django framework and I want to add multiple place markers on Google earth based on the address stored in the database connected to django database by a single click on the User Interface. Is it possible to achieve this? Suppose I have 10 database records and we have a button on the UI which automatically places the markers on all the locations (addresses stored in the database). NA NA NA -
Django html forms get value from button
Shortly I am busy with the web framework Django, I have already implemented some small projects and wanted to try something bigger, but unfortunately I can not continue at one point and the search has not been promising. I would like to get displayed on a page single records from my database and by clicking this the server should get a feedback which of the displayed records was clicked. I currently use some CSS elements from Materialize, but that does not work as well as I would like. my example.html <head> </head> <body> {% block content %} <div class="row"> {% for data in persenal_data %} <form action= "{% url 'main:beispiel' %}" method="POST"> {% csrf_token %} <button class="col s10 m6 14" type="submit" > # value = data.id <div class="card"> <div class="card hoverable"> <div class="card-content"> <div class="card-title">{{data.id}} </div> </div> </div> </div> </button> </form> {% endfor %} </div> </body> and my views.py def build_reseption_page(request): if request.method == "POST": chusing_data = request.POST.get('value') return render(request=request, template_name='main/beispiel.html', context={"personal_data":personal_data}) else: return render(request=request, template_name='main/beispiel.html', context={"personal_data":personal_data}) I'd like to assign a variable by clicking the button # value = data.id, that this can be controlled in the views.py.