Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django return csv file to user in File Field
i have function returns csv file and want add it to File Field in django model i tried to convert it to pandas data frame then to str by using (to_csv) method label_name = 'labeled' + data.name labeled_data = np.concatenate([data, model.labels_.reshape(-1, 1)], axis=1) columns = [x for x in range(labeled_data.shape[1])] labeled_data_file = pd.DataFrame(data=labeled_data, columns=columns) labeled_data_file = labeled_data_file.to_csv(index=False, header=True) instance.labeled_data.save(label_name, labeled_data_file, save=False) however, it returns read = property(lambda self: self.file.read) AttributeError: 'str' object has no attribute 'read' error -
How do I load my test yaml file prior to running my Django test?
I'm using Django and Python 3.7. I would like some test data loaded before running my tests. I thought specifying a "fixtures" element in my test would do this, but it doesn't seem to be loaded. I created the file, mainpage/fixtures/test_data.yaml, with this content model: mainpage.website pk: 1 fields: path: /testsite model: mainpage.article pk: 1 fields: website: 1 title: 'mytitle' path: '/test-path' url: 'http://www.mdxomein.com/path' created_on: type: datetime columnDefinition: TIMESTAMP DEFAULT CURRENT_TIMESTAMP model: mainpage.articlestat: pk: 1 fields: article: 1 elapsed_time_in_seconds: 300 hits: 2 I specify the fixture in my test file below ... from django.test import TestCase from mainpage.models import ArticleStat, Article import unittest class TestModels(unittest.TestCase): fixtures = ['/mainpage/fixtures/test_data.yaml',] # Test saving an article stat that hasn't previously # existed def test_add_articlestat(self): id = 1 article = Article.objects.filter(id=id) self.assertTrue(article, "A pre-condition of this test is that an article exist with id=" + str(id)) articlestat = ArticleStat(article=article,elapsed_time_in_seconds=250,votes=25,comments=15) articlestat.save() article_stat = ArticleStat.objects.get(article=article) self.assertTrue(article_stat, "Failed to svae article stat properly.") But it doesn't appear any of the test data is loaded when my test is run ... (venv) localhost:mainpage_project davea$ cd /Users/davea/Documents/workspace/mainpage_project; source ./venv/bin/activate; python manage.py test test activated! Creating test database for alias 'default'... /Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py:1421: RuntimeWarning: DateTimeField Article.front_page_first_appeared_date received a naive datetime (2019-01-30 … -
How can I get separated queryset with value as list?
I'm refactoring django application with rest-framework. I tried to return post with comments, and the application work with this. It's my json design, and I can't change models. But I can change json design. { "id": 1 "title": "Title", "content": "Content", ..., "comments": [ [ { "id": 1, "parent": 0, "content": "Content", ... }, { "id": 2, "parent": 1, "content": "Content", ... }, ], [ { "id": 3, "parent": 0, "content": "Content", ... }, { "id": 4, "parent": 3, "content": "Content", ... }, ], ], ... } In comments, there are many lists which grouped by "group" column. In that case, data seems like this. Comment(id=1, parent=0, content="Content", group=1) Comment(id=2, parent=1, content="Content", group=1) Comment(id=3, parent=0, content="Content", group=2) Comment(id=4, parent=3, content="Content", group=2) I want to get queryset separated by group column. And I want to use like this. comments = Comment.objects.filter() # How can I get? # [[Comment(id=1), Comment(id=2)], [Comment(id=3), Comment(id=4)]] serializer = CommentSerializer(comments, many=True) I refered here that how can I use serializer with list. -
How to resolve dependency conflicts while installing python packages
I have installed django, django-channels==2.1.6, asgiref==2.3.2, channels_redis Now I would like to install django-seo-js. But this throws an error, as the required dependency requests>=2.11.0 for django-channels has been downgraded to requests==2.2.1 Now I wasn't able to start channels through daphne. So, I upgraded the requests with pip3 install -U requests. Again I get a warning: django-seo-js 0.3.1 has requirement requests==2.2.1, but you'll have requests 2. 21.0 which is incompatible. And I am stuck. I need to use django-channels as well as django-seo-js. How to resolve this dependency conflict? Note: I am running this in an virtualenv I am also facing the same dependency issue while installing asgi_rabbitmq which downgrades asgiref and raises a conflict with django-channels again. Anyway that's another question maybe. I don't have options to downgrade django-channels though. Just trying to use everything latest, keeping up with the pace. Is there a way one could install each package isolated with its dependencies? or any other solution? please help. -
Storing and retrieving a list of integers in sqlite using django
I'm prototyping a JSON API in Django (final implementation will be something embedded such as Civet) in order to have something to test a higher level application against. I need to persist data of the form: { someListOfIds: [1, 2, 7, 9] } The integers mean something to the hardware - they don't correspond to anything else in the db. I'm using Django 2.1.5 and Python 3.5.2. In my model, someListOfIds is currently defined as a CharField so the value is stored as the string "[1, 2, 7, 9]". When I retrieve rows from the db in a view, I pass that field through the .decode method of a json.decoder.JSONDecoder(), which seems to turn it back into a list of ints. However, attempts to deliver it in that form in a JsonResponse result in it being returned in the string-ified form: { someListOfIds: "[1, 2, 7, 9]" } NOTE: Following advice from here, I currently have the following view code to return just the content of the fields property, discarding the extra pk and model properties that would otherwise be included: cfgs = [Configuration.deStringify(x) for x in Configuration.objects.all()] objs = serializers.serialize('python', cfgs) cfgs = [d['fields'] for d in objs] response … -
How to filter dynamically a menu list in Django ModelAdmin?
I'm currently writing some forms in a Django project. Many forms are currently written for the Admin, using ModelAdmin forms. In one of the forms, a listbox displays a ProductCategory. Another listbox displays a list of ProductFeature. What I basically need, is to have the list ProductFeature changed according to the value selected in ProductCategory. It seems to be possible with Django forms using JavaScript, but what about ModelAdmin forms ? Z. -
Is there a way to shuffle a queryset so it shows a different value each day?
I'm building a Django 2.5 web app that shows a different quote from an historical figure every day. The problem is that this quote should be different for each user and should change every day without repeating the same quote. I've already did some research and the only thing that comes close is to use an offset when I request the queryset, but that doesn't solve the random quote for each user problem. quotes/views.py import datetime ... now = datetime.datetime.now() today_tt = now.timetuple() julian_day = today_tt.tm_yday #asuming there are 365 quotes on the database quotes.objects.all()[jualian_day] What can I do to implement this? -
Virtualenv activated but python still running system version
I just trying to run someone else django project with their virtualenv but after activate its still runs the system python: (virtualenv) tbosss@tbosss:~/Desktop/environment$ which python /usr/bin/python -
Why is my docx file content spoiled while saving and downloading it on Django webpage?
I want to build a Django webpage, where the user uploads docx files, edites them and downloads as new docx files. When the file is downloaded, the content is spoiled. The views.py function is the following: def edit_file(request, upload_id): instance = get_object_or_404(DocFile, id=upload_id) document = Document(instance.agreement) # here is some code to edit the docx file file_name = '{}.doc'.format(contract_name) response = HttpResponse(document, content_type='application/msword') response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name) document.save(response) return response return render(request, 'uploads/file_detail.html', { 'variables': variables, 'form_field': form_field }) Is it possible to get downloaded the edited file but not the content be spoiled in this way? If no, what other ways are possible? -
Editpost function not working. Problem with "if request.method=='POST':"
The problems seems to be at the line "if request.method=='POST':". Any help is appreciated. traceback [30/Jan/2019 23:44:22] "GET /testimonypost/ HTTP/1.1" 200 8031 Not Found: /testimonypost/.jpg [30/Jan/2019 23:44:22] "GET /testimonypost/.jpg HTTP/1.1" 404 17479 boo 5 boo a [30/Jan/2019 23:44:25] "GET /37/testimony/edit HTTP/1.1" 200 5320 Not Found: /37/testimony/.jpg [30/Jan/2019 23:44:25] "GET /37/testimony/.jpg HTTP/1.1" 404 17476 [30/Jan/2019 23:44:28] "POST /37/testimony/ HTTP/1.1" 200 4261 Not Found: /37/testimony/.jpg [30/Jan/2019 23:44:28] "GET /37/testimony/.jpg HTTP/1.1" 404 17476 template {%extends 'base_form.html'%} {%block content%} <form class="form-group" action="." method="POST" enctype="multipart/form-data"> {%csrf_token%} {%for field in form %} <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{field.errors}}</span> </div> <label class="control-label col-sm-2"{{field.label_tag}}</label> <div class="col-sm-10">{{field}}</div> {%endfor%} <button type="submit" class="btn btn-success">Submit</button> </form> {%endblock content%} views.py @login_required def TestimonyEdit(request, id=None): instance=get_object_or_404(Testimony, id=id) print(request.user) print('5') print(instance.user) if instance.user == request.user: form = TestimonyForm(request.POST or None, request.FILES or None, instance=instance) print('a') return render(request, 'variablized_form.html', {"form": form}) if request.method=='POST': form = TestimonyForm(request.POST or None, request.FILES or None, instance=instance) if form.is_valid(): print('3') instance=form.save(commit=False) instance.save() print('2') context={ "testimony":testimony } return render(request, 'testimony_post.html', context) else: return HttpResponse('You are unauthorized to edit this post') -
Get_context_data breaking breaking django listview
I have a listview that displays membership pricing, but when the user is not logged in the membership objects don't show up, so there is no pricing. It does work when I am logged in. However, when i completely remove the def get_context_data function from my views.py, it works and the membership list object appears for non authenticated users. So somehow the get_context_data is breaking my model=membership query for non authenticated users. Any idea? membership_list.html {% for object in membership_list %} <td><span>${{ object.price }}</span><span class="text-muted">/mo</span></td> {% endfor %} views.py class MembershipSelectView(ListView): model = Membership context_object_name = 'membership_list' ordering = ['price'] #Check if user is logged in first def get_context_data(self, *args, **kwargs): if self.request.user.is_authenticated: context = super().get_context_data(**kwargs) current_membership = get_user_membership(self.request) context['current_membership'] = str(current_membership.membership) return context -
Django Migrations: Modifying Field of Model After Database in Use
I have created a Django web application that has models and many instances of models created. The problem is that I want to add another field to one of the models already in use (has over 1000 instances). I have had difficult experiences with Django Migrations in the past and am scared that if I modify the model by adding the field, my web application will not function. How do I change the model in such a way that it will not affect the functionality of my web application? -
Django Postgres Multiple Schema Migrations: No migrations to apply
Setup: one Postgres database with two schemas: 'default' and 'other'. Using: Django==2.0.10 psycopg2-binary==2.7.7 (no binary verion in production) My database configuration: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=django,public', }, ... 'TEST': { 'NAME': 'default', 'DEPENDENCIES': ['other'], }, 'ATOMIC_REQUESTS': True, }, 'other': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=other,public', }, ... 'TEST': { 'NAME': 'other', 'DEPENDENCIES': [], }, 'ATOMIC_REQUESTS': True, } } Steps taken on a fresh database: py manage.py migrate: works as expected and the 'default' schema is migrated correctly. py manage.py migrate --database=other results in: No migrations to apply. Oddly, taking these steps (again, on a fresh database) in reverse order works: py manage.py migrate --database=other: works as expected and the 'other' schema is migrated correctly. py manage.py migrate results in: works as expected and the 'default' schema is migrated correctly. I suspect this has something to do with the django_migrations table. I don't know much about this table, is there one per Postgres schema? Or is there only one django_migrations table per project? After a lot of Googling I saw many suggestions for the use of database routers. The 'other' schema must have all the same tables as the 'default' schema so … -
What Is The Exact Difference Between Request.POST,Request.data And Request.GET in DRF?
Iam little bit confusion on request.POST,request.data And request.GET? can anyone explain the main differences beween this In DjangoRestFramework views?? -
How to apply some changes on uploaded photo via form before saving the form
When the user uploads an image via the form, i try to apply some changes on the image using PIL before saving the form(image being added to the database) def photo_update(request): form = imageform(request.POST , request.FILES) if form.is_valid(): tmp = form.save(commit=False) Image.open(tmp.img).convert('LA').save(tmp.img) form.save() return redirect('success') else: form = imageform() context = {'form':form} return render(request , 'photo.html',context) But the image's file winds up broken and the file which has been saved in the database does not show any image -
Django many to many relationship. Connect two tables using id number different then ID(primary key)
i'm trying to build a relationship database which consist of two tables. I didn't have any problems with building database with many to many relationship. but the problem start when i'm changing primary key I need to input old data that i have to a db. In one of the list i would have a list of a clients and in the other list of entities. Clients should have relation with several entities. For example: Client A: Entity 1 Entity 2 Entity 3 Client B: Entity 6 Entity 1 Entity 2 Entity 8 Table of Clients: Client A (identification number: 6582395) Client B (identification number: 7866732) Table of Entities: Entity 1 (identification number: 6582395) Entity 1 (identification number: 7866732) Entity 2 (identification number: 6582395) Entity 2 (identification number: 7866732) Entity 3 (identification number: 6582395) Entity 6 (identification number: 7866732) Entity 8 (identification number: 7866732) Entities would by reused to several clients. The trick is that i have old data, in which I can only compare each list using "identification number:". I dont know how to do it. if i go with a primary key then i cannot have Entities with duplicated identification numbers (which is the only way for me … -
Add dynamically generated columns to django admin list view
Backgorund I have these two models: TYPE_CHOICES = ( (0, 'Income'), (1, 'Outcome'), ) class Transaction(models.Model): type = models.IntegerField(choices=TYPE_CHOICES) amount = models.IntegerField() store = ForeignKey(Store) class Store(models.Model): name = models.CharField(max_length=300) email = models.EmailField(max_length=300) balance = models.ForeignKey(Transaction) What I need to achieve Currently, django shows this output in Admin list view for model Movements (assuming we have two stores): Type Amount Store ------------------------ Income 100 Store A Outcome 20 Store A Income 500 Store B I'd like to show custom columns, each showing partial balance for a store: Type Amount Store Store A Balance Store B Balance ---------------------------------------------------------- Income 100 Store A 100 0 Outcome 20 Store A 80 0 Income 500 Store B 80 500 I know how to make a custom static column and I know how to calculate the values for the rows, but I can't figure out how to make the columns dynamic, i.e. to show in accordance with another model. PS: Please, note that the number/names of stores may change. If I add a new store, the partial balance for that store should be shown in the list view too. -
Django: select / choose a specific form dynamically from a drop-down (or link) or dynamically amend a single form given a choice list
My aim is to be able to choose a form using a drop-down selector (that always is the same). Visually: I would like to get from this: To This: Before a choice is made, the form area is empty, like this: Background: My aim is to find a scalable solution that would work equal well if we have 100's of Fields or choose to make 100's of individual models. I am struggling a bit with to see where this should best be applied, on model level, on view level or on html level. I am a beginner and therefore struggle with things that most likely is seen as basic for many, thus my need to raise a question. My code, so far: PRODUCT_TYPE=[ ('Car', 'Car'), ('Boat', 'Boat') ] class AllProduct(models.Model): Product_Type = models.CharField(max_length=10, blank=True, choices=PRODUCT_TYPE) Boat_Make = models.CharField(max_length=10, blank=True) Car_Make = models.CharField(max_length=10, blank=True) Number_Wheels = models.CharField(max_length=10, blank=True) Number_Sails = models.CharField(max_length=10, blank=True) class ProductForm(ModelForm): class Meta: model = AllProduct fields = ('__all__') def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-2' self.helper.field_class = 'col-sm-4' self.helper.form_id = 'All-product' self.helper.form_method = 'post' self.helper.form_action = ('submit_form') self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success')) Product = 'Product_Type' CarMake = 'Boat_Make' BoatMake = … -
im getting " no such table: main.auth_user__old" when i tried to save something in admin/message/post/add/ in my local server
I have logged in as a superuser and i have tried to save some text but im getting an error here's my whole code. https://bitbucket.org/bhaskarpraveen/message/src/master/first_project/message/models.py this is my code in models.py from django.db import models class Post(models.Model): text = models.TextField() def __str__(self): """A string representation of the model.""" return self.text[:50] OperationalError at /admin/message/post/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/message/post/add/ Django Version: 2.1.4 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\Praveen\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 296 Python Executable: C:\Users\Praveen\AppData\Local\conda\conda\envs\myDjangoEnv\python.exe Python Version: 3.7.2 Python Path: ['C:\Users\Praveen\Desktop\messaging\first_project', 'C:\Users\Praveen\AppData\Local\conda\conda\envs\myDjangoEnv\python37.zip', 'C:\Users\Praveen\AppData\Local\conda\conda\envs\myDjangoEnv\DLLs', 'C:\Users\Praveen\AppData\Local\conda\conda\envs\myDjangoEnv\lib', 'C:\Users\Praveen\AppData\Local\conda\conda\envs\myDjangoEnv', 'C:\Users\Praveen\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages'] Server time: Wed, 30 Jan 2019 13:49:21 +000 -
How to remove clear and currently from ImageField - Django Form
I want to remove currently and clear field from my django form. Basically i want to remove the stuff which is inside red color rectangle box in image forms.py class MyUserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['user_phone','user_dob','user_gender', 'user_image', ] I am using crispy_forms also -
Django permission_classes for access to route is not callable
I am trying to change the permissions to specific routes. Some routes I want to be open, other routes I want the user to be authenticated. My code is the following: from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.viewsets import GenericViewSet class UserViewSet(GenericViewSet): @action(url_path="an/api/path", detail=False, methods=["post"], renderer_classes=[JSONRenderer]) @api_view(['GET']) @permission_classes((IsAuthenticated, )) def get_stuff(self, request): #Will get stuff But I keep getting this error: File "/code/api/views/UserViewSet.py", line 16, in <module> api_1 | class UserViewSet(GenericViewSet): api_1 | File "/code/api/views/UserViewSet.py", line 33, in UserViewSet api_1 | @permission_classes((IsAuthenticated, )) api_1 | TypeError: 'list' object is not callable Any idea why it keeps throwing list' object is not callable function? -
How can I iterate over all the files uploaded into request.FILES?
This is part of my view: if request.method == 'POST': print(request.FILES) print(type(request.FILES)) for key, value in request.FILES.items(): print(key, value, type(value)) Output: <MultiValueDict: {'1': [<InMemoryUploadedFile: Screenshot from 2019-01-27 18-06-10.png (image/png)>], '3': [<InMemoryUploadedFile: Screenshot from 2019-01-27 11-32-34.png (image/png)>, <InMemoryUploadedFile: Screenshot from 2019-01-26 16-25-56.png (image/png)>]}> <class 'django.utils.datastructures.MultiValueDict'> 1 Screenshot from 2019-01-27 18-06-10.png <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> 3 Screenshot from 2019-01-26 16-25-56.png <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> Now, it's apparent that while iterating over request.FILES, the key '3' points to a list of two files. However only one of them appears as value of the dictionary. How can I properly iterate over the entire list of files by key? -
Django user does not inherit permission from group
Consider the following output of a Django shell session: >>> from django.contrib.auth.models import User, Group >>> g=Group.objects.all() >>> g <QuerySet [<Group: Tester>, <Group: Testmanager>]> >>> g[1].permissions.all() <QuerySet [..., <Permission: testman | test plan step | Can add test plan step>, <Permis sion: testman | test plan step | Can change test plan step>, <Permission: testman | test plan step | Can delete test plan step>, <Permission: testman | test plan step | Can view test plan step>, ...]> >>> g[1].user_set.all() <QuerySet [<User: mida>, <User: testma>]> >>> u=User.objects.all() >>> u <QuerySet [<User: somedude>, <User: test>, <User: testma>]> >>> u[0].has_perm('testman.create_testplanstep') True >>> u[2].has_perm('testman.create_testplanstep') False I have defined two groups, Tester and Testmanager. User somedude is a site admin and also a member of group Testmanager. User testma ist not a site admin but also in Testmanager. Group Testmanager has all permissions on the model TestPlanStep. Yet the user testma does not get the permission. What am I doing wrong? -
Identify closest word in terms of meaning to previous known words while parsing an Invoice PDF
I'm trying to parse an Invoice and I'm stuck with matching closest word to predefined word. For example, I want to identify Invoice Date(predefined word) from the parsed invoices but for some of the invoices it is coming as Date of Invoice. I want to match both of these keywords with each other as they have same meaning. For this, I have tried using difflib.get_close_matches(word, possibilities, n=3, cutoff=0.6) library but result is not desired. I am thinking of using NLP and machine learning here. What could be the best way to solve this problem? -
Django makemigrations failing. ProgrammingError: column xxxxx does not exist
Django 2.0, python 3.5, postgres I am trying to create a new boolean field on a model in django. The problem is that when i run makemigrations it throws a psycopg2.ProgrammingError: column core_marca.eh_maiores_bancos does not exist. But the eh_maiores_bancos column is the one i am trying to create. This error happens before i can create the migration files. I have had this same problem before with other models and solved by commenting a piece of the code that was causing the exception, but as it keeps happening i am looking for a better solution than looking at the log and manually commenting the lines that cause the error. Note: The piece of code causing the error is in a totally different file, the views.py file in my API module, in which i have a function that returns a list of all the objects of that model i have. I Tried dropping the database, recreating it, deleting migration files and then creating migrations and migrating but still fails. I also tried changing the imports sequence on the code, the order of the installed apps, adding a if not 'makemigrations' in sys.argv: to prevent the code from running when i am creating …