Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Manage ModelManyToMany request in views.py
I have a ModelManyToMany selector in my html. (I can't post images so, here is the url to image: https://i.stack.imgur.com/HDhde.png) I want to catch the user's selections with my POST method in my views.py views.py class userPageView(TemplateView): template_name = 'user.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['edit_profile_form'] = EditProfileForm(prefix='edit') return context def post(self, request, *args, **kwargs): edit_name = request.POST.get('edit-name') edit_two_factors_auth = request.POST.get('edit-two_factors_auth') edit_coins = request.POST.get('edit-coins') if request.method == "POST": if 'profileButton' in request.POST: if edit_name and (edit_name != request.user.name): request.user.name = edit_name request.user.save() print(edit_coins) return render(request, 'user.html') models.py class Usuario(AbstractUser): name = models.CharField(max_length=12, help_text="The name must be between 2 and 12 characters") email = models.EmailField(max_length=60, unique=True, help_text="The email must be between 5 and 30 characters") password = models.CharField(max_length=78) change_password_code = models.CharField(blank=True,max_length=15) activated = models.BooleanField(default=False) activated_code = models.CharField(default="",max_length=15) ip = models.CharField(blank=True,max_length=15) last_login = models.DateField(default=now) wallets = models.ManyToManyField(Wallet) coins = models.ManyToManyField(Coin) avatar = models.CharField(blank=True,default="bitcoin.png",max_length=15) delete_code = models.CharField(default="",max_length=9,blank=True) two_factors_auth = models.BooleanField(default=False) two_factors_auth_code = models.CharField(default="",max_length=12,blank=True) fingerprint = models.CharField(max_length=64,blank=True) The print in my views.py only returns me the last selection, but not all the set of choices that the user has done. I want to save all coins selections by the users in his coins field -
Allow user to download zip file generated on AWS
Here is how I do to generate ZIP and download it fron my server, it works well in local development. import zipfile filepath = doc.file.path filename = os.path.basename(doc.file.name) directory = os.path.dirname(filepath) xzip = zipfile.ZipFile(os.path.join(directory,"%s.zip" % filename), "w") xzip.write(filepath,filename) xzip.close() zip_file = open(xzip.filename, 'rb') response = HttpResponse(zip_file, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="%s.zip"' % os.path.splitext(filename)[0] return response All my static files are uploaded to AWS in production. So I change a little bit # filepath becomes filepath = settings.MEDIA_ROOT + "/" + doc.file.name But When I try to download it, it gives me [Errno 2] No such file or directorywith the link: https://bucket_name.s3.amazonaws.com/media/public/files/file.pdf.zip the settings.MEDIA_ROOT is: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'bucket_name' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_PUBLIC_MEDIA_LOCATION = 'media/public' MEDIA_ROOT = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_PUBLIC_MEDIA_LOCATION) doc.file.path gives me the error: 'This backend doesn't support absolute paths', that's why I changed to MEDIA_ROOT + doc.file.name How can I configure that to download the zip file generated from AWS? -
Button populate geometry (frontend) from python script (backend)
I am new in web development/javascript, and I am trying to build a web application using django, javascript (three.js) in the frontend and python in the backend. My frontend is working and once a press a button I am updating a object with all vectors from the geometry: vertices_update = [Vector3, Vector3, Vector3, Vector3, Vector3, Vector3, Vector3, Vector3]. Now the challenge is: Once I press the button the variable vertices_update should be updated also in the python script (backend) to generate a subdivision in each surface and then render it back in the javascript (frontend). The button should behavior as a switch. See diagram below. I don´t need to store the data, it is just for that users. Does anyone have a suggestion how to integrate both? Can I just keep it in the RAM memory, as an object? or Should I work with json file? or Even with SQLite database? or None of these will be a solution... Thnx in advance -
Django: for loop and POST request create function
In the project there is a model with existing instances in the database. class Instagram(models.Model): userid = models.CharField(max_length=255, unique=True) username = models.CharField(max_length=50, blank=True, null=True) There is another model, so far without instaces class InstagramAgesAnalitics(models.Model): instagram = models.ForeignKey(Instagram) age = models.CharField(max_length=10) viewer_percentage = models.DecimalField(default=0, max_digits=5, decimal_places=2) Now I need from the values stored in the json file, create new instances of the InstagramDemographicsAnalitics model. For this, I wrote a function that uses the for loop and substitutes the required key values in the instance fields. example.json { "@nightcrvwlxr": { "userId": "5697152", "content_persons_statistic": { "ages": { "45-64": 0.016358024691358025, "18-24": 0.37570950015055704, "25-34": 0.2789897621198434, "13-17": 0.2103470340258958, "35-44": 0.11859567901234568 }, "genders": { "MALE": 0.6046939714680166, "FEMALE": 0.39530602853198343 } } } } views.py from django.shortcuts import render import json from django.http import HttpResponse, HttpResponseRedirect from .models import InstagramDemographicsAnalitics, Instagram, InstagramAgesAnalitics def get_ida_instance(request): with open('/home/jekson/projects/jsontest/example.json', encoding='utf-8') as f: data = json.loads(f.read()) if request.method == 'POST': for key, value in data.items(): print(value['userId']) instagram = Instagram.objects.get(userid=value['userId']) ages = (value["content_persons_statistic"]['ages']) for key, value in ages.items(): ida = InstagramAgesAnalitics() ida.instagram = instagram ida.age_group = key ida.viewer_percentage = float(str(value)) ida.save() print(key + ":" + " " + str(value)) return HttpResponse("Succesful") return render(request, 'ida.html') template.html <form method="post" action=""> {% csrf_token %} <button type="submit">Click Me!</button> … -
What do with this issue, when i start my server on Django?
When I start my server on Djano i have such issue. (myvenv) orlov@orlov-System-Product-Name:~/Desktop/back_v0.1$ python manage.py runserver Error processing line 1 of /home/orlov/Desktop/back_v0.1/myvenv/lib/python3.6/site-packages/dj-0.1-nspkg.pth: Traceback (most recent call last): File "/usr/lib/python3.6/site.py", line 174, in addpackage exec(line) File "<string>", line 1, in <module> File "<frozen importlib._bootstrap>", line 568, in module_from_spec AttributeError: 'NoneType' object has no attribute 'loader' What is it? -
What does 'many = True' do in Django Rest FrameWork?
I am learning DRF now, im little puzzuled by this many = True code. What does it do? Or what does it mean? example 1 class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.RelatedField(many=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') example 2 class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAdminUser,) def list(self, request): # Note the use of `get_queryset()` instead of `self.queryset` queryset = self.get_queryset() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) -
Django caching an entire rendered HTML page for all website visitors
I have a particular view which takes over a minute to load for all users. The contents of the view aren't specific to the user viewing the rendered HTML it produces (it's a large schedule), but it's not possible (and highly inefficient, I imagine) to run that expensive operation every time someone visits the schedule page. So what I want to do is cache the rendered contents of that entire page in my database or even a file in S3, perhaps. All the Django and caching documentation in general which I've seen talk about caching each unique visitor to the portion of the app you want to cache, but not for the site as a whole. I want to present the same cached view to everyone, always. I'm not even sure if caching is the right word, in this case. The reason it's not a static page is because the contents do change a few times a day (approximately), but I have no problem connecting a post_save signal to the schedule such that it'll refresh the cached and full rendered HTML content. This is my first time delving into caching, so maybe there's some fundamental flaw in my understanding. Would … -
comparing value stored in widthratio tag django
I have to multiply 2 values in django template and then compare it to another value so I used this approach: {% widthratio value1 1 2 as total%} #multiplies value1 with 2 {% if value2 == total %} true {% else %} false {% endif %} This is returning false even if both values are equal, it seems 'total' is not acting as a number. What can I do to solve this issue? -
Django Vue.js - rendering multi-choice dropdown list
I am trying to use Vue.js multiselect component: https://vue-multiselect.js.org/ Unfortunately it does not render as it should. Instead of multiselect dropdown list, I am obtaining something like this: enter image description here Used code: HTML: <div id="app"> <button @click="toggle">open and close later </button> <pre>{{ isOpen }}</pre> <multiselect ref="multiselect" v-model="value" :options="options" :multiple="true" track-by="library" :custom-label="customLabel" @close="isOpen = false" @open="isOpen = true" > </multiselect> </div> Used libraries (included in ): <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.18/vue.min.js"></script> <script src="https://unpkg.com/vue-multiselect@2.1.0"></script> <link rel="stylesheet" href="https://unpkg.com/vue-multiselect@2.1.0/dist/vue-multiselect.min.css"> Used script ( placed at the bottom of the page ): <script> new Vue({ components: { Multiselect: window.VueMultiselect.default }, data: { isOpen: false, value: { language: 'JavaScript', library: 'Vue-Multiselect' }, options: [ { language: 'JavaScript', library: 'Vue.js' }, { language: 'JavaScript', library: 'Vue-Multiselect' }, { language: 'JavaScript', library: 'Vuelidate' } ] }, methods: { customLabel (option) { return `${option.library} - ${option.language}` }, toggle () { this.$refs.multiselect.$el.focus() setTimeout(() => { this.$refs.multiselect.$refs.search.blur() }, 400) } } }).$mount('#app') </script> -
Django pagination with ListView - page 2 onwards displays all objects
In my listview, when the page is loaded the pagination appears correct and shows page links for pages 1-7 at the bottom. However when I go to any of these pages it displays all model instances. For example, I click on page 2, the url is appended with ?page=2 and as I set paginate-by as 20 I expect objects with ids 21-40. I define paginate_by in a base ListView which I inherit from i a number of views, e.g. 'CompoundListView' below. I generally only override get_context_data in these subclasses, so I cannot figure out why this is happening. The html for the pagination is contained in a base template which I extend in the templates for the ListView subclasses. Any suggestions on why the pagination is not working correctly and/or what I should try in order to fix it would be greatly appreciated. Base ListView and a subclass: class BaseCompoundListView(ListView): queryset = Compound.objects.all() template_name = 'compounds/compound_list.html' paginate_by = 20 def get_context_data(self, **kwargs): context = super(BaseCompoundListView, self).get_context_data(**kwargs) context['odor_types'] = OdorType.objects.values('term') return context class CompoundListView(BaseCompoundListView): def get_context_data(self, **kwargs): context = super(CompoundListView, self).get_context_data(**kwargs) context['page_header'] = 'All compounds' return context The base template: {% block content %}{% endblock %} {% block pagination %} {% … -
Django app with postgressql db querry to ms sql on a server
I am building a web application using Python and the framework Djando. The database used will be Postgressql. The company I work for use an ERP system with a ms sql DB located on a server. There are some information that could be useful for my web application. Is there a way to querry that information over my Django app which will be cloud based? I would like to have some guideline. Regards, -
The above exception (no such table: oauth2_provider_accesstoken) was the direct cause of the following exception:
am trying to develop an application with Python3.6 by Django1.10 . trying to test in chrome browser and getting this error massage:- The above exception (no such table: oauth2_provider_accesstoken) was the direct cause of the following exception:this the massage in my browser -
Display users' images in Django
I am learning Django and currently trying to make a simple website where users can post topics and stuff. What I want is only the uploaded images that belong to a certain topic to display when you open the topic. But I am so stuck at it now I can't get any image come up on the pages. I've tried many different things but none's worked so far. I can't get my head around how exactly the template should look like and how do I link it to the topic page...and my view is probably far from right but I've tried a lot of things and it's all got a bit messy...pretty much it's been 2 days of hassle and I will appreciate any directions Thank you in advance This is what i have: models.py class Image(models.Model): """images representation""" image=models.ForeignKey(Topic, on_delete=models.CASCADE) image=models.ImageField(upload_to= 'media/') caption=models.CharField(max_length= 100) uploaded_at=models.DateTimeField(auto_now_add=True) views.py def upload_image(request, topic_id): """Upload images""" topic=Topic.objects.get(id=topic_id) if request.method != 'POST': # No data submitted; creaete a blank form form=ImageForm() else: # Data submitted; Process data form=ImageForm(request.POST, request.FILES) if form.is_valid(): instance=form.save(commit=FALSE) instance.topic=topic instance.save() return HttpResponseRedirect(reverse('the_horror:topic', args=[topic_id])) images=Image.objects.all() context={'form':form, 'topic':topic, 'images':images} return render(request, 'the_horror/topic.html', context) upload_image.html {% extends 'the_horror/base.html' %} {% block content %} {% … -
Running view for a stipulated time in Django
I am developing a quiz application in Django in which the teacher(user of one type) adds a quiz along with its duration. Now, students start giving the test but I want the test to automatically get submitted as the stipulated time(provided by the teacher) completes. Reopening/refreshing the page should not restart the time. How do I incorporate this feature? *Currently, view is written such that test gets submitted when the user attempts the last question. -
Knowing the logged in user in Flash TCP Socket server with Django
I am trying to have a TCP server (by googling since March I could say a "Flash policy server"), to allow Flash games on my Django front-end to communicate with my models on the back-end. I already use consumers.py for WebSocket games (HTML5), but I am unable to find any guidance or resources for Flash games communication in Django. I am using the following example TCP server (SocketServer package with python 2.7), and all I need to know is which Django user is requesting the "policy-file-request". In consumers.py (WebSocket) this can be done with @channel_session_user_from_http, which is what I am doing right now for the HTML5 games. #! /usr/bin/python import SocketServer class FlashPolicyHandler(SocketServer.StreamRequestHandler): timeout = 5 def handle(self): self.data = self.request.recv(1024).strip() if self.data == '<policy-file-request/>': self.request.sendall('<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>') self.request.close() if __name__ == "__main__": HOST, PORT = "0.0.0.0", 9999 SocketServer.TCPServer.allow_reuse_address = True server = SocketServer.TCPServer((HOST, PORT), FlashPolicyHandler) server.serve_forever() -
send the chosen dropdown item to the view when onselect
I want to send the value of the chosen dropdown item to my view when onselect option, not when a button clicked to submit. My goal is to filter a list of model objects immediately by the chosen data. I don't find any clear answer and I'm confused about that. Can anyone help me with that? -
Error 1050, "Table already exists" though it does not
I configure mysql in settings.py and __init__.py #settings.py DATABASES = { 'default':{ 'ENGINE': config['database']['engine'], 'NAME': config['database']['name'], 'HOST': config['database']['host'], 'PORT': config['database']['port'], 'USER': config['database']['user'], 'PASSWORD': config['database']['password'], } } #__init__.py import pymysql pymysql.install_as_MySQLdb() When python manage.py migrate was implemented, it throw error django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1050, "Table 'django_migrations' already exists")) It tells "Table 'django_migrations' already exists") However, it does not exists $ find / -iregex ".*django_migrations.*" 2>/dev/null (forum_env) I consult sql - Mysql 1050 Error "Table already exists" when in fact, it does not - Stack Overflow, which does help with the problem. $ ls data Friday demo ib_logfile0 ibtmp1 mysqld.local.pid a_very_strange_name forum ib_logfile1 mysql performance_schema auto.cnf ib_buffer_pool ibdata1 mysqld.local.err sys -
Best way / framework to add Django to existing Bootstrap website
I have a website built on Bootstrap framework. It contains web pages (HTML, CSS, Javascript, jQuery) that load dynamic data through AJAX / jQuery calls to exposed Web Services. However there is no backend code that generates the HTML files. Now I want to add "My Account", "Login", "Saved Favorites" types of features. I am new to Django. What is the best way (or framework / library) to migrate this existing website to Django? Keep in mind the pages would no longer be static after above mentioned features are added. -
Django Reverse Relationship property not exists
Let's say I have AssetUser model looks like follow. class AssetUser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) my query set looks like follow. qs = User.objects.get(pk=1) when i run qs.assetuser_set i am getting error like follow. Traceback (most recent call last): File "", line 1, in AttributeError: 'User' object has no attribute 'assetuser_set' what mistake i made here. -
unable to save multiple values via Django Form
// model class AttributeInstance(models.Model): somefilter = models.CharField(max_length=255, blank=True) values = models.TextField() //form class ABCModelForm(forms.ModelForm): class Meta: model = ABCModel fields = ('somefilter', 'value') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.data: self.fields['values'] = forms.MultipleChoiceField(()) // view class ABCModelView(FormView): def get(self, request): form = ABCModelForm() return render(self.request, 'core/abc_model_edit.html', {'form': form}) def post(self, request): try: form = ABCModelForm(request.POST) form.save() form = ABCModelForm() return render(self.request, 'core/abc_model_edit.html', {'form': form}) except Exception as e: return HttpResponse(status='400') // HTML // fills the multiple choice field on runtime based on somefilter // the multiple choice UI element looks like below after rendering Description: Values: dodo bobo foo bar Save The post request is sending multiple values with same key e.g. values=foo&values=bar I am seeing only one value in request object in both Django view and form. Not sure what I need to do to get multiple values in Django request object. -
compressing font files in amazon s3
I am using Amazon S3 to serve static files for my website. My server side code is built on Django 2.0. I am using boto3 and django-storages packages to server static files. AWS_IS_GZIPPED is set to True in settings.py file. All the static files (CSS, JS, images) are compressed. Response header has content-encoding as gzip for these requests. But, font files are not getting compressed. Is there a different way to compress font files when served from S3? You can clearly see this behaviour when you inspect my website. Click here to go to the website. -
How to create the model.py in my django app for achieving what I need?
Lets say, I want to track my workers attendence. There are 30 locations thoughout the country. There are 4000 workers in each sector and roughly 200 working days. Every worker has separate profile page. I'm using mysql database. What should I do? 1. Should I create a single table for a day?(40*200 tables for 200 days) 2. Should I create a single coulmn in a table for a day?(1 table per year and per location, 200 days in a table columns) So, how can I write the model for achieving this? What is the standard way and will be better in the long run. I should mention the working days are not fixed so these would be dynamic like when I will enter the date it will create one table/column for me in the database. -
Django images found but not displating
I am using Django views to display some images in a folder. The program is able to search for the files but not able to display, there is a 404 error for all the images. views.py import os from datetime import datetime image_list=[] app_static_dir = os.path.join(os.path.join(os.path.join(os.path.join(settings.BASE_DIR,'index'),'static'),'{}'.format(image_now)),'demo') for file in os.listdir(app_static_dir): if file.endswith("1_plate.jpg"): image_list.append(file) html {% for file in image_list %} <img src="{{ file }}" alt=""> {% endfor %} enter image description here -
Django viewflow extend task view
Am trying out an idea to use both django-viewflow and django-permission in an app where there would be some complicated permission rules. The way that I have understood the way django-permission works is by adding a decorator to the view that you want to apply permission rules. I have managed to get this working on the process views by extending the base viewflow views and pointing the urls.py to the extended view. When I try to follow the same idea for tasks I bump into the error listed below type object 'CBVTask' has no attribute 'flow_class' models.py class CBVArticle(models.Model): created_by = models.ForeignKey(User) title = models.CharField(max_length=100) content = models.TextField() class CBVArticleProcess(Process): article = models.ForeignKey(CBVArticle, blank=True, null=True) class CBVTask(Task): class Meta: proxy = True flow.py class CBVArticleFlow(Flow): process_class = models.CBVArticleProcess task_class = models.CBVTask start = ( flow.Start(views.ArticleCreate).Next(this.end) ) end =flow.End() urls.py myflow_urls = FlowViewSet(CBVArticleFlow).urls urlpatterns = [ url(r'^process/(?P<process_pk>\d+)/$', views.TestDetailProcessView.as_view(), kwargs = dict(flow_class=CBVArticleFlow), name='detail'), url(r'^process/(?P<process_pk>\d+)/start/(?P<task_pk>\d+)/detail/$', views.DetailTaskView.as_view(), kwargs = dict(flow_class=CBVArticleFlow, flow_task=CBVTask), name='start__detail'), ] views.py from viewflow.flow.views import DetailProcessView as BaseDetailProcessView, DetailTaskView as BaseDetailTaskView @permission_required('test_app_cbv.view_cbvarticleprocess') class TestDetailProcessView(BaseDetailProcessView): template_name = 'test_app_cbv/detail.html' def get_queryset(self): pk = self.kwargs['process_pk'] return models.CBVArticleProcess.objects.filter(process_ptr_id = pk) class DetailTaskView(BaseDetailTaskView): template_name = 'test_app_cbv/task_detail.html' Thanks in advance for any pointers! -
How to Create Table with MultiCells using ReportLab through Django
I want to create multi-cell table using ReportLab. This feature is already there in FPDF (http://www.fpdf.org/en/script/ex3.pdf) but i want to do it through Python/Django using ReportLab library. Reference: http://www.fpdf.org/en/script/script3.php