Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django download working with loggedout state
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I added that line, so download from django administration pages work just like download from normal pages ( both logged in state).It was initially only working from normal pages, and not administration pages. The problem arises, that through the url i am able to download the file when its not logged in.I dont want that to happen.I am using django 2.2 and python 3.6.9 -
How to solve checksum failed in Django with PayU payment Integration?
I am sending all the mandatory fields to Payu payment gateway but its showing me checksum failed error how could i solve this. In django i am adding the payu payment gateway integration using paywix library and sending all the mandatory fields to payu payment gateway but its showing me checksum failed error i have checked the sequence of hash value but still showing the checksum failed. views.py @csrf_exempt def checkout(request): carts = Cart.objects.filter(user=request.user) orders = Order.objects.filter(user=request.user, ordered=False) order = orders[0] amount = int(order.get_totals()) # if request.method == 'POST': email = request.user.email first_name = request.user.first_name data = {'amount': amount, 'firstname': first_name, 'email': email, 'productinfo': 'Exam-India', 'txnid': payu.generate_txnid()} # data = dict(zip(request.POST.keys(), request.POST.values())) data['txnid'] = payu.generate_txnid() # hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10" data['hashh']: self.generate_hash(hash_string) payu_data = payu.initiate_transaction(data) print("This is the payu values") print(payu_data) context = {} context['carts'] = carts context['order'] = order context['posted'] = payu_data # context['hash_value'] = hash_value return render(request, 'checkout.html', context) checkout.html <form action="https://sandboxsecure.payu.in/_payment" method="POST" name="payuForm"> <input type="text" name="key" value={{ posted.key }} /> <input type="text" name="hash_string" value={{ posted.hash_string }} /> <input type="text" name="hash" value={{ posted.hashh }}/> <input type="text" name="posted" value="{{ posted }}"/> <input type="text" name="txnid" value={{ posted.txnid }} /> <input type="text" name="amount" value={{ order.get_totals | floatformat }} /></td> <input type="text" name="firstname" … -
How to update Django model data with a unique constraint using a ModelForm?
I have two models with one of them defined with a constraint (see "Entities" model below). I built two forms, one to create new model data and another to update model data. Create form works properly but update form throws an error saying about of already existing items (my constraints is based on the unique combination of two fields). No matter what field I modify within the update form, same error is thrown. For example, modyfing only "notes" field in an "entity" instance leads to the following error. Entities with this Name and Company already exists. How to properly implement my form (and/or models) so that constraint is preserved (an entity with the same name has to be unique within a company) and modification of a non constrained field don't throws an error? models.py class Entities(models.Model): company = models.ForeignKey(Companies, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=False, null=False) notes = models.TextField(blank=True, null=True) class Meta: # Constraint here (entity name + company combination name must be unique) constraints = [models.UniqueConstraint(fields=['name', 'company'], name='unique_company_entity')] managed = True db_table = 'entities' def __str__(self): object_name = self.name + " " + self.company.name return object_name class Companies(models.Model): name = models.CharField(max_length=50, blank=False, null=False) notes = models.CharField(max_length=50, blank=True, null=True) class Meta: … -
Using Django to install Google Analytics tracking code
AIM Using Django to install Google Analytics. PROBLEM It isn't clear to me if I need to apply the following lines to ALL the templates I am interested in tracking or just to index.html. {% load google_analytics_tags %} <div style="display:none"> <img src="{% google_analytics %}" width="0" height="0" /> </div> If the answer is that by simply pasting it into index.html would add it to all my existing templates, how can I exclude the pages I don't want any tracking from? Thanks in advance for your help. -
Couldn't able to import environment variable in django settings.py for sending email
When I specify EMAIL_HOST_USER and EMAIL_HOST_PASSWORD directly email send properly but if try to get using os.environ it is throwing following error (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError l26sm20714449pgn.46 - gsmtp', 'webmaster@localhost'). I have tried to add variables in .bashrc and .bash_profile but it didn't worked. What I have tried shown below. can anyone help me this please. settings.py variables shown below. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True # EMAIL_HOST_USER = 'name@gmail.com' # EMAIL_HOST_PASSWORD = '123456789' EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') print('variable :',os.environ.get('EMAIL_HOST_USER')) EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') .bashrc This file is in the same directory where settings.py exist. import os export EMAIL_HOST_USER = 'name@gmail.com' export EMAIL_HOST_PASSWORD = '9538913650' main below lines I have tried in terminal both in global and vertual envirnment. EMAIL_HOST_USER=name@gmail.com EMAIL_HOST_PASSWORD=123456789 using python comand code shown below. import os os.environ.set('EMAIL_HOST_USER') = 'name@gmail.com' os.environ.set('EMAIL_HOST_PASSWORD') = 12345678 -
Django app with multiple instances - how to ensure daily email is only sent once?
I am building a Django app that uses APScheduler to send out a daily email at a scheduled time each day. Recently the decision was made to bump up the number of instances to two in order to always have something running in case one of the instances crashes. The problem I am now facing is how to prevent the daily email from being sent out by both instances. I've considered having it set some sort of flag on the database (Postgres) so the other instance knows not to send, but I think this method would create race conditions--the first instance wouldn't set the flag in time for the second instance to see or some similar scenario. Has anybody come up against this problem and how did you resolve it? -
secondApp.UserProfileInfo.profile_pic: (fields.E210) Cannot use ImageField because Pillow is not installed
hi i am getting this error: secondApp.UserProfileInfo.profile_pic: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". but when i try to install pillow it is shows that C:\Users\pysaundary>pip install pillow Requirement already satisfied: pillow in c:\users\pysaundary\anaconda3\lib\site-packages (7.0.0) WARNING: Could not generate requirement for distribution -illow 7.0.0 (c:\users\pysaundary\anaconda3\lib\site-packages): Parse error at "'-illow=='": Expected W:(abcd...) WARNING: Could not generate requirement for distribution -cipy 1.3.2 (c:\users\pysaundary\anaconda3\lib\site-packages): Parse error at "'-cipy==1'": Expected W:(abcd...) WARNING: Could not generate requirement for distribution -atplotlib 3.1.0 (c:\users\pysaundary\anaconda3\lib\site-packages): Parse error at "'-atplotl'": Expected W:(abcd...) alabaster==0.7.12 anaconda-client==1.7.2 anaconda-navigator==1.9.7 anaconda-project==0.8.3 ansicon==1.89.0 asgiref==3.2.3 asn1crypto==1.3.0 astroid==2.3.3 astropy==4.0 atomicwrites==1.3.0 attrs==19.3.0 Babel==2.8.0 backcall==0.1.0 backports.functools-lru-cache==1.6.1 backports.os==0.1.1 backports.shutil-get-terminal-size==1.0.0 backports.tempfile==1.0 backports.weakref==1.0.post1 basemap==1.2.0 bcrypt==3.1.7 beautifulsoup4==4.8.2 bitarray==1.2.1 bkcharts==0.2 bleach==3.1.0 blessed==1.16.1 bokeh==1.4.0 boto==2.49.0 Bottleneck==1.3.1 certifi==2019.11.28 cffi==1.13.2 chardet==3.0.4 Click==7.0 cloudpickle==1.2.2 clyent==1.2.2 colorama==0.4.3 comtypes==1.1.7 conda==4.8.2 conda-build==3.18.8 conda-package-handling==1.6.0 conda-verify==3.4.2 contextlib2==0.6.0.post1 cryptography==2.8 cycler==0.10.0 Cython==0.29.14 cytoolz==0.10.1 dask==2.10.1 decorator==4.4.1 defusedxml==0.6.0 distributed==2.10.0 distro==1.4.0 Django==3.0 django-fontawesome==1.0 django-mssql==1.8 django-registration-redux==2.7 docutils==0.16 entrypoints==0.3 et-xmlfile==1.0.1 factor-analyzer==0.3.2 Faker==3.0.0 fastcache==1.1.0 filelock==3.0.12 Flask==1.1.1 fsspec==0.6.2 future==0.18.2 gevent==1.4.0 glob2==0.7 greenlet==0.4.15 h5py==2.10.0 HeapDict==1.0.1 html5lib==1.0.1 hypothesis==4.54.2 idna==2.8 imageio==2.6.1 imagesize==1.2.0 img2pdf==0.3.3 importlib-metadata==1.4.0 ipykernel==5.1.4 ipython==7.11.1 ipython-genutils==0.2.0 ipywidgets==7.5.1 isort==4.3.21 itsdangerous==1.1.0 jdcal==1.4.1 jedi==0.16.0 Jinja2==2.10.3 jinxed==1.0.0 joblib==0.14.1 json5==0.8.5 jsonschema==3.2.0 jupyter==1.0.0 jupyter-client==5.3.4 jupyter-console==6.1.0 jupyter-core==4.6.1 jupyterlab==1.2.5 jupyterlab-server==1.0.6 Keras==2.3.1 Keras-Applications==1.0.8 Keras-Preprocessing==1.1.0 keyring==21.1.0 kiwisolver==1.1.0 lazy-object-proxy==1.4.3 libarchive-c==2.8 llvmlite==0.31.0 lml==0.0.9 … -
data visualization of sqlite3.db data analysis
I am modelling data from a csv file with some ML analysis and I would like to visualize it into Django localhost with some chart, radar chart would be perfect. What is not yet clear to me is if I have to use Python language or CSS because view.py make use of templates … in HTML, right? I am a little bit confused about that. Could anybody please give me some directions to follow? Is there any documentation would you recommend me? -
Can I Override Global Authentication for a Single Request Type in an ApiView using DRF?
I'm using django_rest_frameork (DRF) on a large project. In general, I want all my views protected, so I have Token Authentication set as my global authentication scheme. But there are a few views that I want this turned off, for example, creating a new user, and logging in. For example my /User ApiView has a get and post method. The get returns the user profile and the post creates a new user. How can I override the global authetication scheme on the /User post only? I still need it turned on when getting user information. I'm asking more to increase my understanding of DRF than anything. I know that I could separate the /User/ calls into to different ApiViews, where one is authenticated and one isn't. I also know that I could dispense with the global scheme entirely and authenticate on a pre-view basis. Is there a particularly "pythonic" or django-typical way of doing this? Any recommendations? -
is there an way to use python in cloud and use it with heroku or there is not?
so guys can i use Heroku to run my python scripts without django? i need to use it to make things like bot or whatever so is there any way to do that, and please provide me with the full steps to do that. thanks <3 -
Django: how to prevent login view diplaying when user already authentificated?
well I currently develop a Django project with registration app using Django authentification (tuto simple is better than complex ) doing like that, I do not have de write any views for login and logout and all prefectly works nevertheless, I have a unexpected behavior: when user click on browser back arrow when just authentificated, the login view is displayed whereas user is already logged in so I would like to prevent this I should be able to test if user is authentificate before displaying the login view but how can I do that without any login view defined in my code? I must override the default login view? How ? -
Editing posts in a Django blog
Note: there's a similar question to mine, there're a few differences in our code, and I tried the solutions to his question, didn't work for me. I'm working on a blog using Django, I'm trying to add an edit_post feature but when I go to localhost:8000 it shows NoReverseMatch, the problem is related to the post's id, I'm trying to create a home page that shows the post's title and it's content. here'e my code: models.py from django.db import models # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=20) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title urls.py from django.urls import path from . import views app_name = 'blogs' urlpatterns = [ # Home page path('', views.index, name='index'), # page for adding a new post path('new_post/', views.new_post, name='new_post'), # page for editing a post path('edit_post/<int:post_id>/', views.edit_post, name='edit_post'), ] index.html {% block content %} <p>My personal Blog</p> <a href="{% url 'blogs:new_post' %}">Add a new post</a> <ul> {% for p in posts %} # the problem is probably here <li>{{ p.title }}</li> <li>{{ p.text }}</li> <p> <a href="{% url 'blogs:edit_post' post.id %}">Edit post</a> </p> {% endfor %} </ul> {% endblock content %} edit_post.html {% block content %} <p>Edit post:</p> … -
How to subsample time series, to every n’th row in Django?
Goal I'm trying to reduce the data sent to the front-end of an application by subsampling a timeseries. Initially by just taking every nth row, because I also want to optimize for speed. Layout I'm using Django 2.1.5, with a PostgreSQL backend. The time series table is filled with measurement data every 1-15 minutes from various sensors. models.py class Measurement(models.Model): sensor = models.ForeignKey(Category,on_delete=models.PROTECT,related_name='measurements') datapoint = models.DecimalField(max_digits=8, decimal_places=4) time = models.DateTimeField(auto_now_add=True) Related questions A few resources came up around a close solution here How to filter/reduce a QuerySet to every nth row? and https://stackoverflow.com/a/56487889/11225898 which is based around annotating with 'F' like so: views.py Measurement.objects.annotate(idmod2=F('id') % 2).filter(idmod2=0) This does work till a certain extent, however as the measurements are made by ~5-25 different sensors and come in every ~1-15 minutes, the id field is not consistently tracking. Just to visualize an simplified example: +----+--------+------+-------+ | id | sensor | data | time | +----+--------+------+-------+ | 1 | A | 432 | 10:00 | | 2 | A | 534 | 10:15 | | 3 | B | 2342 | 10:20 | | 4 | B | 87 | 10:25 | | 5 | B | 2 | 10:30 | | 6 … -
Django_tables2 NonType object is not iterable
iam stuck in using django_tables2. i intended to display a simple table using a queryset. data in the model is being displayed in the djangoAdmin. my model.py ``` class PM03(models.Model): date_done=models.DateField() ticket=models.CharField(unique=True,max_length=100) site_code=models.ForeignKey(Sites,on_delete=models.PROTECT) site_name=models.ForeignKey(Sites,on_delete=models.PROTECT,related_name='pm_site_name',to_field='site_name') spare_replaced_1=models.ForeignKey(Asset,related_name='pm_spare_replaced_1',on_delete=models.CASCADE,blank=True,null=True) spare_replaced_2=models.ForeignKey(Asset,related_name='pm_spare_replaced_2',on_delete=models.CASCADE,blank=True,null=True) spare_replaced_3=models.ForeignKey(Asset,related_name='pm_spare_replaced_3',on_delete=models.CASCADE,blank=True,null=True) rehabilitation=models.TextField(null=True,blank=True,help_text="indicate work done") saved_by=models.ForeignKey(User,on_delete=models.PROTECT) def __str__(self): return self.ticket,self.site_name class Meta: verbose_name='PM03' verbose_name_plural='PM03' ``` my view.py ```class TableView(tables.SingleTableView): table_class = Asset_table queryset = Work_Orders_CR.objects.all() template_name = "test.html" ``` my tables.py ```class Asset_table(tables.Table): class Meta: model=Work_Orders_CR template_name = "django_tables2/bootstrap4.html" ``` my traceback Environment: Request Method: GET Request URL: http://localhost:8000/test Django Version: 2.2.6 Python Version: 3.7.3 Installed Applications: ['IENG_MIS', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'management_information_system', 'bootstrap_datepicker_plus', 'widget_tweaks', 'bootstrap4', 'django_tables2', 'django_datatables_view', 'django_countries', 'django_filters', 'multiselectfield', 'bootstrap3'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Rigelsolutions\source\repos\management_information_system\management_information_system\IENG_MIS\templates\test.html, error at line 111 'NoneType' object is not iterable 101 : <div class="row" style="margin-top: 1em; margin-left: 1mm"> 102 : 103 : 104 : <a class="btn btn-primary" href="{% url 'admin:index' %}">Inventory Manager</a> 105 : 106 : </div> 107 : {% block maincontent %} 108 : 109 : <div class="bg-light table-resposive-lg"> 110 : <table id="asset_table" style="width:100%;" class="table table-hover sortable"> 111 : {%render_table table %} 112 : 113 : </table> 114 : </div> 115 : </div> 116 : … -
How to make a feature like playlist in youtube to add videos to it with wagtail?
I have a wagtail Page (Post) and I want to give users the ability to make collections and add posts to it (like when you add videos to playlist in youtube). I found a way to make this by making a (Collection) page and add Orderable to it so user can choose as mush as (Post) page as he like, but I want to make users also choose collection in the posts page (like when you choose tags or categories). so how to make this two things? 1- add posts to collection through the collection page (with Orderable for example). 2- choose collection in the posts page (like when you choose tags or categories). thanks. -
Django : CheckboxSelectMultiple default select Something if other field value is Something
I'd like to make when payer is "example1", then dutch_payer default select "example1" and save it. moneylogs>models.py: class Moneylog(core_models.TimeStampedModel): moneybook = models.ForeignKey( moneybook_models.Moneybook, on_delete=models.CASCADE) pay_day = models.DateTimeField(default=NOW) payer = models.ForeignKey( tempfriend_models.Tempfriend, on_delete=models.CASCADE, related_name="payer") dutch_payer = models.ManyToManyField( tempfriend_models.Tempfriend, related_name="dutch_payer", blank=True) price = models.IntegerField() category = models.CharField(max_length=10) memo = models.TextField() objects = models.Manager() and when User SignUp, tempFriends will create with same User.username. like: class SignUpView(FormView): template_name = "users/signup.html" form_class = forms.SignUpForm success_url = reverse_lazy("cores:home") ... tempfriend_models.Tempfriend.objects.create( name=user.username, belongs_to=user) monelogs>forms.py: class CreateMoneylogForm(forms.ModelForm): class Meta: model = models.Moneylog fields = ( "pay_day", "payer", "dutch_payer", "price", "category", "memo", ) widgets = { "dutch_payer": forms.CheckboxSelectMultiple, "memo": forms.Textarea(attrs={"rows": 3, "style": "width:100%"}) } def save(self, *args, **kwargs): moneylog = super().save(commit=False) return moneylog How to make it with simple code? Please kindly help me. -
DJango download from administration not working
Policy with ID "1/change/policy/bsd-policy.pdf" doesn't exist. Perhaps it was deleted? class Policy(models.Model): name = models.CharField(max_length=15, default="BSD_POLICY") policy = models.FileField(upload_to="policy/") Thats the message I get when I try to download from django/admin pages the policy. However, as normal user I am able to download it with the below code. def download_policy(request): the_file = None try: policy = Policy.objects.get(name="BSD_POLICY") the_file = os.path.join(settings.MEDIA_ROOT, str(policy.policy)) except Exception as e: print(e) the_file = "base/document-not-found.pdf" filename = os.path.basename(the_file) chunk_size = 8192 response = FileResponse(open(the_file, 'rb'), content_type=mimetypes.guess_type(the_file)[0]) response['Content-Length'] = os.path.getsize(the_file) response['Content-Disposition'] = "attachment; filename=%s" % filename log( user=request.user, action="FILE_DOWNLOAD_REQUEST", extra={ "file_path":the_file, "file_length":response['Content-Length'] } ) return response why is it working as normal user download? whereas as admin its not working? I dont conntrol admin pages either because its autogenerated by django. I AM Using django 2.2 and python 3.6.9 here is settings.py too static_root = '<STATIC_PATH>' media_root = 'mediafiles' # the path where files are stored MEDIA_ROOT = 'mediafiles' MEDIA_URL = '' PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__)) SITE_ROOT = os.path.dirname(PROJECT_ROOT) FILE_UPLOAD_TEMP_DIR = os.path.join(MEDIA_ROOT, 'temp') # directory for holding temporary files (database files for upload) -
Django forms cleaned_data missing a field completely
forms.py from datetime import datetime, date, timedelta from django import forms class MyForm(forms.Form): field1 = forms.IntegerField() date = forms.DateTimeField(initial=datetime.now) field3 = forms.IntegerField( help_text="Number of something") field4 = forms.IntegerField(required=False) field5 = forms.IntegerField(required=False) def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['field1'].widget.attrs['readonly'] = True def clean(self): cleaned_data = super().clean() submit_date = cleaned_data.get("date") # relevant validation checks here After submitting the form, the submit_date variable is None. Not only is it None, it is completely missing from the cleaned_data dictionary. This is what the cleaned_data dict looks like when a request is made: {'field1': 1, 'field3': 22, 'field4': 0, 'field5': 200} What could be the possible cause for this error? Any and all help will be highly appreciated. -
Get data in Django view from AJAX POST request
I am new to Django and working on a project which does not involve the use of forms in Django. I have a JS which makes an AJAX POST call to my Django web service which is my backend and I just want a response from it. However I always get none on doing so. I searched a lot but was not able to find a solution. Here is my code: My project urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('home/', include('demo_app.urls')), path('admin/', admin.site.urls), ] My app urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('dispatcher/', views.dispatcher, name='dispatcher'), ] My views.py: from django.shortcuts import render from django.http import HttpResponse from demo_app.models import VesselStatus from django.db.models import Count from django.views.decorators.csrf import csrf_exempt def index(request): return HttpResponse("Hello world") @csrf_exempt def dispatcher(request): if request.method == "POST": print(request.POST.get("inputText")) return HttpResponse(request) I dont want to use forms hence the CSRF exempt decorator My AJAX call: if(individual_result.toLowerCase().includes('some text')) { console.log("Found"); data = { "inputText": individual_result } $.ajax ({ crossDomain: true, type: "POST", contentType: "application/json", url:"--address-of-local--/home/dispatcher/", data: JSON.stringify(data), dataType: 'json', cache: false, success: function(response){ console.log(response) } }) } For some reason I always seem … -
How can I duplicate an image in cloudinary?
I am using cloudinary with Django, and I need to duplicate an instance of a model which also contains a CloudinaryField. I know how to duplicate model instances in Django, but I don't know how to duplicate the image. This is my model: class CustomImage(models.Model): image = CloudinaryField("image", null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now=True, auto_now_add=False) This is my duplication code for an instance of that model: image = CustomImage.objects.get(id=1) image.pk = None image.save() The problem is that both instances now have assigned the same image assigned, so if I delete one, the other gets deleted. How can I properly duplicate an existing image in cloudinary? -
Filenames getting appended every time I search and store them in list using Google Drive API?
I am using the google drive API to search inside of a folder named 'Users' and then I store the filenames the reside in that folder in a list. In Django every time I refresh a page which triggers this google API function the list of filename gets appended. Ex. 1st execution files_in_users = ['1','2','3','4','5'] same page refreshed again files_in_users = ['1','2','3','4','5','1','2','3','4','5'] And this goes on every time I refresh the page. I have even tried to restart the server but there is always some redundant data in the list.I have also used the list.clear() function at the end of execution. Why does this happen? Is there some cache that I need to delete after each execution? code: #GET ID OF USER FOLDER FROM DRIVE drive_users_id = get_user_file_id(service) # GET THE FILES IN USER FOLDER FROM DRIVE flow_of_users_file = service.files().list(q=" '{0}' in parents ".format(drive_users_id),spaces ='drive').execute() for i in flow_of_users_file['files']: files_in_user_folder.append(i['name']) print('files in drive are :', files_in_user_folder) After printing the flow_of_users_file which is of type Dictionary, I could see there are redundant data in it, some files are getting appended every time I execute that line -
Django model current link not pointing to file in MEDIA_ROOT
My code generates Pandas dataframes. They are big. I save them as files. For this, I have created this Model: models.py: class TargetFiles(models.Model): owner = models.CharField(max_length=25) csv_file = models.FileField(blank=True, upload_to='target') file_name = models.CharField(max_length=255) settings.py: ... BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') mycode.py: file_content = df.to_csv(index=False, encoding='utf-8') csvname = 'target1.csv' csf = ContentFile(file_content, csvname) TargetFiles.objects.create(owner=self.user, csv_file=csf, file_name=csvname) I don't know if this is the best approach for the problem. This documentation made me skeptical. The thing is that my code is generating the file properly, and saving it in MEDIA_ROOT directory. But when I go to admin view and click on TargetFiles object, the link to the file returns this error: The current path, media/target/target1.csv, didn't match any of these. Since I am not an Django expert, I think I am setting something wrong. Maybe in settings.py or in urls.py (this file I didn't write any reference to media, maybe this is where the error lives). I have already read these posts: Django - how to create a file and save it to a model's FileField? , Django: generate a CSV file and store it into FileField and this assign resulting csv file to django model. But … -
Django migrations: crashing in a data migration refering to an already removed model field
Creating test database, Django is raising this exception django.core.exceptions.FieldError: Cannot resolve keyword 'xxx' into field. Choices are: ... The failing migration is a custom one, moving data from (let's say) ModelA to ModelB: def forwards(apps, schema_editor): ... prev_list = ModelA.objects.all().values_list('xxx').distinct() for item in prev_list: ModelB(xxx=item).save() My next movement has been checked ModelA which, ok expected, doesn't have a field called XXX class ModelA(Model): # no field named xxx Digging a little bit what happened here: ModelA used to have a field named xxx there is a migration trying to create ModelB rows reading from ModelA.xxx ModelA doesn't have such field since there is a later migration removing that field, so I don't have the field declared in my model. Why is failing the creation of the test database (from python manage.py test)? how can I fix this? -
How to limit no. of consecutive objects with a certain property in django queryset?
I have a model: class Employee(models.Model): name = models.CharField(max_length=255) department = models.ForeignKey("Department", ...) ...... ... Here's a queryset that returns best performing employees in a company sorted over the annotated field score. best = Employees.objects.filter(...some filters).annotate(score=...some calculations).order_by('-score') How to limit the queryset to return a maximum of 2 or n no. of consecutive employees with same department? current result:(only printing department for time sake) dep5, dep9, dep9, dep9, dep9, dep5, dep5, dep4, dep4, dep4 Expected result:(only printing department for time sake) dep5, dep9, dep9, dep5, dep5, dep4, dep4 Note: I have done my research, and not able to find any solution. Please help. -
Unclear errors when trying to save data while overriding default 'create' method
Tried to write custom create method for my model, but run into some unclear errors. Here is my code: # models.py: class ItemModel(models.Model): item_id = models.CharField(max_length=10, primary_key=True) name = models.CharField(max_length=40) active = models.BooleanField(default=True) def __str__(self): return self.item_id class ItemVersion(models.Model): item_ver_id = models.CharField(max_length=13, primary_key=True) item_ver = models.TextField() config = models.TextField() model = models.ForeignKey(ItemModel, on_delete=models.CASCADE, default=0) session_id = models.CharField(max_length=40, default=0) creation_date = models.DateTimeField(auto_now=False, auto_now_add=True) finished = models.BooleanField(default=False) def name(self): return self.model.name def __str__(self): return str(self.model) # serializers.py: class ItemModelSerializer(serializers.ModelSerializer): item_id = serializers.RegexField(regex='^\d{3}-\d{9}$', allow_blank=False) name = serializers.CharField(min_length=6, max_length=50, allow_blank=False) class Meta: model = ItemModel fields = '__all__' class ItemVersionSerializer(serializers.ModelSerializer): item_ver_id = serializers.RegexField(regex='^r\d{2}$', allow_blank=False) session_id = serializers.RegexField(regex='^s\d{2}$', allow_blank=False) link = serializers.SerializerMethodField() name = serializers.SerializerMethodField() config = serializers.CharField(min_length=6) item_ver = serializers.CharField(min_length=6) def get_name(self, obj): return obj.name() def get_link(self, obj): link = 'https://example.net/' + str(obj.model) + str('-dyn') + '/?iv_id=' + str(obj.item_ver_id) + '&sessid=' + str(obj.session_id) return link # views.py: class ItemModelViewSet(viewsets.ModelViewSet): queryset = ItemModel.objects.all() serializer_class = ItemModelSerializer lookup_field = 'item_id' class ItemVersionViewSet(viewsets.ModelViewSet): serializer_class = ItemVersionSerializer lookup_field = 'item_ver_id' def get_queryset(self): pass def create(self, request, *args, **kwargs): data = request.data model = ItemModel.objects.get(item_id=data["model"]) item_version = ItemVersion.objects.create( # model=model, item_ver_id=data["item_ver_id"], config=data["config"], item_ver=data["item_ver"], session_id=data["session_id"] # finished=data["finished"] ) item_version.model.add(model) finished = True if data["finished"] else False item_version.finished.add(finished) item_version.save() serializer = …