Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fetch data from an excel file and make an editable data grid
I am new to django. I am provided a task to fetch data from an excel sheet and display it as an editable datagrid on a web page on page load. In grid few fields will already contain data and User need to provide data in few fields in the grid and then after performing some calculations on the frontend itself, one more field will be filled and on clicking save the data should be saved in the excel file. Next time user visit the page he should see the earlier data in the grid. I am not getting how to approach this problem. deadline is coming Sunday. Please suggest how can I achieve this or any sample code will be very helpful. Any help will be appreciated. Thanks -
ProfileFilter results not rendering in HomeView
I have a ProfileFilter which allows a user to filter through other users by age, location, etc. It worked fine when it was a separate page with a unique URL with view class FilterView(View) but I am having problems with it when trying to combine it with the main homepage. The filtering form is showing up and filtering as can be seen from the URL, (?interests__icontains=&age=&gender=M) but it is not rendering out the results. This is obviously because the ProfileFilter has been assigned to the variable f and the page is populated using a {% for user in users %} forloop. I need to assign f to users and have tried making a separate def filter function where I add context = {'users': f} but then the form doesn't show up on the page anymore. I'm a beginner so if there is something critical I am missing please inform me...many thanks as usual, I really appreciate it. views.py class ConnectView(View): template_name = 'connect/home.html' def get(self, request, *args, **kwargs): f = ProfileFilter(request.GET, queryset=Profile.objects.exclude(user=request.user)) context = { 'users': User.objects.exclude(username=request.user), 'filter': f, } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): location = Location(latitude=request.POST['latitude'], longitude=request.POST['longitude'], user = request.user) location.save() return JsonResponse({'message': 'success'}) … -
How to output one value at a time from an instance in Django?
I'm trying to build a questionaire and am struggling to output one question at a time. Currently I have a take model which is being created every time a user goes on the quiz page. At the same time ticket objects(they contain the questions) are added to the take. this is an app where a user can purchase tickets and for every ticket they get to answer one question. if self.logged_in_user: self.take, new_obj = Take.objects.new_or_create(request) x = range(6) for n in x: take_ticket = Take.objects.create_ticket("Whatcha think?") self.take.tickets.add(take_ticket) form = QuestionForm(request.POST) if form.is_valid(): form.save() form.cleaned_data['answer'] form = QuestionForm() context = {'the_obj': self.take, 'form': form} return render(request, 'question.html', context) right now when I ouput the_obj every question stored pops out. I would like to make it so it'll only be one question at a time. the user answers, clicks submit and it'll go to the next one. I have tried using the_obj.first() but that gives me 'Take' object has no attribute 'first' Any advice on how to approach this would be much appreaciated! -
readonly_fields function doesn't work in Django Admin with models tabularly inlined
readonly_fields function works properly when I use it with individual models, but it doesn't work with models which are tabularly inlined. Could somebody help in understanding how to mark fields read only when we deal with models inlined to each other on admin page ? Thanks. -
In Django/Python, how to, after proper validation, insert a field data in the database formatted as desired?
I'm developing a web system with Django/Python and I need a specific field from the User model: CPF (https://en.wikipedia.org/wiki/Cadastro_de_Pessoas_Físicas). I need it with a validator and to be properly formatted before insertion in the the database. I've tried to use localflavor.br.forms.BRCPFField from django-localflavor and django-localflavor-br (https://django-localflavor.readthedocs.io/en/latest/localflavor/br/), but makemigrations couldn't recognize the new field neither migrate could update the respective table in the database (I think it's a bug, but this issue is not for now). So, after considering other options, I've decided to give it a try and to write my own validator. In models.py: from django.core.exceptions import ValidationError def validate_cpf(cpf): digitos = [int(digit) for digit in cpf if digit.isdigit()] if len(digitos) < 11 or len(digitos) > 11: raise ValidationError("Wrong number of digits") sop = sum(a*b for a, b in zip(digitos[0:9], range(10, 1, -1))) ed1 = (sop * 10 % 11) % 10 sop = sum(a*b for a, b in zip(digitos[0:10], range(11, 1, -1))) ed2 = (sop * 10 % 11) % 10 if ed1 != digitos[9] or ed2 != digitos[10]: raise ValidationError("Verification digits don't match") else: return f'{digitos[0:2]}.{digitos[3:5]}.{digitos[6:8]}-{digitos[9:10]}' class Usuario(models.Model): name = models.CharField(max_length=256) cpf = models.CharField(max_length=14, validators=[validate_cpf]) In admin.py: from .models import Usuario class UsuarioAdmin(admin.ModelAdmin): fieldsets = [ ('ID', … -
Django Models: How to retrieve custom error messages in view function?
I have a model UserProfile: class UserProfile(models.Model): class Meta: db_table = 't_user_profile' display_name = models.CharField( max_length=20, unique=True, error_messages={ 'unique': ("A user with that display name already exists."), }, blank=True ) I have a view function: @csrf_exempt def change_display_name(request): data = json.loads(request.body.decode('utf-8')) display_name = data.get('displayName') try: user_profile = UserProfile.objects.get(id=2) except UserProfile.DoesNotExist: return JsonResponse({'error': 'User does not exist.'}, safe=False) user_profile.display_name = display_name user_profile.save() return JsonResponse({'status': 'SUCCESS'}, safe=False) How do I try except the unique display_name and return in JSON the custom error message I setup in my model? -
Connect esp8266 to django site
i am working in a project which includes: 1) pick up measurements from a variaty of sensors 2) upload them in a server 3) display them using a django - site i want to load to the server's database throw a Post request to django page.The site is still in development however because i am a noobie i would like to know if: -the esp8266/32 can actually connect to the server though the site and send a post request with the data to the database -i will be able to somehow make a test using localhost without really deploying the project online in a server. if you have any other suggestions or ideas i am glad to listen! Thanks ,in advance! -
FacebookRequestError while trying to retrieve Campaign Insight Data via Facebook Marketing API with Python/Django
I am trying to get Campaign Insights via Facebook's Marketing API using the Python Business SDK and I am getting a FacebookRequestError: Message: Call was not successful Method: GET Path: https://graph.facebook.com/v3.1/2603111949730990/insights Params: {} Status: 400 Response: { "error": { "message": "Error accessing adreport job.", "type": "OAuthException", "code": 2601, "error_subcode": 1815107, "is_transient": true, "error_user_title": "Loading Async Ads Report Failed", "error_user_msg": "Sorry, the report cannot be loaded successfully. Please check if your job status is completed instead of failed or running before fetching the data.", "fbtrace_id": "BQJsdi3g5tX" } } I already tried to modify the code for the wait_for_async_job() function by checking if the job status is not 'Job Completed' and the percentage of job completion is smaller than 100 but the issue persists. def wait_for_async_job(async_job): async_job.remote_read() while async_job[AdReportRun.Field.async_status] != 'Job Completed' and async_job[AdReportRun.Field.async_percent_completion] < 100: time.sleep(1) async_job.remote_read() Any help would be much appreciated. Thank you in advance! -
there is any library that secure your web app out of the box?
there is any library to secure your web app out of the box ? (for django or flask) -
Django Sitemap with Google News Synthax
With Django, I'm using django.contrib.sitemaps to generate a basic sitemap.xml. Currently, I want to build a new Sitemap for Google News, but the synthax has to be changed. And I don't really know how to transform this template: <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <script id="tinyhippos-injected"/> <url> <loc> http://www.url.com/ </loc> <lastmod>2019-02-14</lastmod> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> </urlset> To this Google News template: <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:n="http://www.google.com/schemas/sitemap-news/0.9"> <url> <loc>http://example.com/</loc> <n:news> <n:publication> <n:name>News paper, blog or similar name</n:name> <n:language>en</n:language> </n:publication> <n:publication_date>2008-12-30T00:00:00+00:00</n:publication_date> <n:keywords>2008,news,xml,sitemap,example,keywords,generated</n:keywords> <n:title>News Article Title</n:title> </n:news> </url> </urlset> sitemaps.py from django.contrib.sitemaps import Sitemap from wall.models import Articles from datetime import timedelta from django.utils import timezone class ArticleSitemap(Sitemap): #Basic Sitemap changefreq = "daily" priority = 0.7 def items(self): return Articles.objects.filter(published=True).order_by('-update') def lastmod(self, item): return item.date class NewsSitemap(Sitemap): #For Google News Sitemap changefreq = "daily" priority = 0.7 def items(self): return Articles.objects.filter(published=True, date__range=[timezone.now() - timedelta(days=3), timezone.now()]).order_by('-update') def lastmod(self, item): return item.date My question is : how to insert the <n:news> and the the tohers childs tags ? Thank you -
Save an object during a Celery task
I would like to save an object in my database during the Celery task. This object is an export file. The Celery task lets to create it and I would like to store it in my table. This is my models.py : class CeleryExportFile(models.Model): name = models.CharField(max_length=100, verbose_name=_('Name of export file'), default='') file = models.FileField(upload_to='media/', default='') creation_date = models.DateTimeField(verbose_name=_('Creation date'), auto_now_add=True) expiration_date = models.DateTimeField(verbose_name=_('Expiration date')) def __str__(self): return self.file class Meta: verbose_name = _('Celery Export File') verbose_name_plural = _('Celery Export Files') I have a Celery tasks.py file : @shared_task(bind=True, time_limit=3600, soft_time_limit=3600) def get_xls_export(self, model="", search_info="", query_params=None): # Some lines which fill the file book.close() output.seek(0) name = str(name + "_" + str(datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%s")) + '.xlsx') CeleryExportFile.save(name=name, file=output, expiration_date=datetime.datetime.now()) # default_storage.save(name, output) try: self.send_email(name=name) except ConnectionRefusedError as e: return ['error_message', _('Error for sending email')] return ['success_message', _('Generation of export file is done')] I'm getting this issue : [2019-02-14 12:23:56,151: ERROR/ForkPoolWorker-4] Task ocabr.tasks.get_xls_export[80e7ea2e-4192-4df7-ba05-83a14805225f] raised unexpected: TypeError("save() got an unexpected keyword argument 'name'",) Traceback (most recent call last): File "/home/.pyenv/versions/3.6.2/envs/ocabr/lib/python3.6/site-packages/celery/app/trace.py", line 382, in trace_task R = retval = fun(*args, **kwargs) File "/home/.pyenv/versions/3.6.2/envs/ocabr/lib/python3.6/site-packages/celery/app/trace.py", line 641, in __protected_call__ return self.run(*args, **kwargs) File "/home/Bureau/Projets/ocabr/src/ocabr/tasks.py", line 151, in get_xls_export CeleryExportFile.save(name='test', file=book, expiration_date=datetime.datetime.now()) TypeError: save() got an unexpected keyword … -
Why is django cron is not working in my application
I was trying to do some cronejobs using django_crons as per the official documentation I set up everything , even for debug I use print statement in do function in project/app_name/crone.py enter code herfrom django_cron import CronJobBase, Schedule from cricket.models import * from cricket.service import cricket_player_performance_update class CricketScoreUpdate(CronJobBase): RUN_EVERY_MINS = 2 # every 2 minutes MIN_NUM_FAILURES = 1 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'project_name.app_name.crone.CricketScoreUpdate' def do(self): print("aaya") pass Also I setup in setting.py file FAILED_RUNS_CRONJOB_EMAIL_PREFIX = "[Server check]: " CRON_CLASSES = [ "cricket.cron.MyCronJob", "django_cron.cron.FailedRunsNotificationCronJob", ] Also I edit crontab */2 * * * * source /home/ubuntu/.bashrc && /usr/bin/python && source /home/abhi/venv/bin/activate && python /home/abhi/leaguesx/manage.py runcrons > /home/abhi/leaguesx/cronjob.log What should I do ? Thanx in advance -
how to create Oauth2 Application from Template Dynamically
I want to create Oauth2 Application manaully from my template using Oauth-toolkit-django. IT was http://localhost:8000/o/applications/ but i want to fill this data from my template and automatically i should get client_id and secret with grant_type as client_credentials. -
Auto-fill forms with the reference of one field
I am developing a website in django. I am new to django and python and need help. I have many fields on the website and if I fill one field (ex:customer id), I want rest other fields to autocomplete from the data in the database I have. Any help is appreciated.Thankyou -
Ignore SuspiciousFileOperation in Django
Please don't flag this question as duplicate without reading first. I am serving my vuejs SPA in django at /app/ Serving static files at /static/ My app is working fine served in django development, but, collectstatic fails. My vue.config.js has: module.exports = { assetsDir: '../static', } Works fine in the browser, but can't be deployed. It throws SuspiciousFileOperation exceptions: django.core.exceptions.SuspiciousFileOperation: The joined path (/mnt/c/Users/static/fonts/materialdesignicons-webfont.ee2bb9f3.eot) is located outside of the base path component (/mnt/c/Users/fede_/braced/staticfiles) I am really stuck with this. -
Unable to Import Model Into an other Model Django
I have Suppliers Model from a Purchase Module and i am simply import it in my Inventory Module. Here is my Purchase Module Model Supplier from django.db import models from django_countries.fields import CountryField from Inventory.models import productDetails,products from Accounts.models import elementaryhead from datetime import datetime import base64 # Create your models here. class suppliers(models.Model): companyName=models.CharField(max_length=30,verbose_name='Company Name') companyAddress=models.CharField(max_length=50,verbose_name='Company Address') city=models.CharField(max_length=20,verbose_name='City') region=models.CharField(max_length=20,verbose_name='Region') country=CountryField() postalCode=models.IntegerField(verbose_name='Postal Code') companyPhone=models.IntegerField(verbose_name="Company Phone") companyFax=models.IntegerField(verbose_name='Company Fax') elementaryID=models.ForeignKey(elementaryhead,on_delete=models.CASCADE,default=None,null=True,verbose_name='Elementary head',editable=False) buyer=models.BooleanField(default=None,verbose_name='Is Buyer',editable=False) supplier=models.BooleanField(default=None,verbose_name='Is Supplier',editable=False) website=models.URLField(default=None,verbose_name='Website') def save(self, force_insert=False, force_update=False, using=None, update_fields=None): accountID = elementaryhead.objects.order_by('id').last().id + 1 code = '00003-000010-0000' + str(accountID) subhead=10 elementaryhead.objects.create(subhead_id=subhead, name=self.companyName,fixed=False, codes=code, right=True) accountID = elementaryhead.objects.order_by('id').last().id + 1 subhead=11 code = '00003-000011-0000' + str(accountID) elementaryhead.objects.create(subhead_id=subhead, name=self.companyName+'(I/TAX PAYABLE)',fixed=False, codes=code, right=True) accountID = elementaryhead.objects.order_by('id').last().id + 1 subhead=15 code = '00003-000015-0000' + str(accountID) elementaryhead.objects.create(subhead_id=subhead, name=self.companyName+'(GST W/HELD PAYABLE)',fixed=False, codes=code, right=True) self.supplier = True self.buyer = False super(suppliers,self).save() def __str__(self): return self.companyName Here is my Inventory Module Model InventoryIn from django.db import models from datetime import datetime from Purchase.models import suppliers,contracts class inventoryIn(models.Model): supplierID=models.ForeignKey(suppliers,on_delete=models.CASCADE,verbose_name='Supplier') productID=models.ForeignKey(products,on_delete=models.CASCADE) purchaseContractID=models.ForeignKey(contracts,on_delete=models.CASCADE) unitsIn=models.IntegerField(verbose_name='Units In') doID=models.IntegerField(verbose_name='Do ID') doImage=models.ImageField(upload_to='/assets/image') invoiceID=models.IntegerField(verbose_name='Invoice ID') invoiceImage=models.ImageField(upload_to='/assets/image') agingDate=models.DateField() dateOfEntry=models.DateField(default=datetime.now()) def __str__(self): return self.supplierID I am basically add two ForeignKey(supplierID,purchaseContractID) which relates to Purchase module.But its throws an error that ImportError: cannot import name 'suppliers' And i … -
Django: Convert timestamps to date
I am currently writing tests and trying to assert if the expiry date is similar to what I expect it to me. Now I have the problem that the seconds are not similar and differ. E.g. >>> session_expiry_date = 1550744238.096939 while >>> expiry_date = 1550744238.087822. My best idea is to abandon the numbers after the dot and just compare if it's the same day. I now struggle to convert the timestamps into dates (YEAR-MONTH-DAY) that I can compare it in a way with self.assertTrue. Can you explain to me how to convert these timestamps to comparable Year-Month-Day format? def test_st_code_via_get(self): self.assertFalse(self.session_name in self.client.session) current_time = timezone.now().timestamp() expiry_date = timezone.now() + timezone.timedelta( days=settings.ST_ATTRIBUTION_WINDOW ) self.client.get(self.path, {'a': 'LOREM'}) session_expiry_date = self.client.session[self.session_name].get('expiry_date') self.assertTrue(expiry_date, session_expiry_date) -
How to implement a dynamic referral program?
Example: Currently, we will provide 100 credits each to both the referrer and referred. Then in the future, we might want to implement a different referral program. Such as change credits to 200 instead of 100. Then again in the future, give each 100 credits as well give referrer 50 if the referred spends 100 with us for the first time. Then again in the future, give each 100 credits as well give referrer 50 each time the referred spends 100 with us. Also, sometimes restrict the program to a few users only. "Dynamic referral": We should be able to create different referral programs in the long course. Should be dynamic and able to take stats from the data. I'm confused. How to create a schema/design/table(model) for such? Please help. -
Only superuser is getting logged in but user is not getting logged
I have created a django app with signin,login and logout.i have executed pyhon manage.py createsuper user to create a superuser.if i login with those credentials it is getting logged but when i am creating the credentials using custom signin form the user is getting saved in the database but the user is not getting logged in with login form. models.py -------- class MyUserManager(BaseUserManager): def create_user(self, fname,lname,username, password): """ Creates and saves a User with the given username, date of birth and password. """ if not username: raise ValueError('Users must have an username') user = self.model(username=username,fname=fname,lname=lname) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, fname,lname,username, password,email=None): """ Creates and saves a superuser with the given username and password. """ user = self.create_user( fname=fname, lname=lname, username=username, password=password, ) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class Event(AbstractBaseUser): fname = models.CharField('fname', max_length=120) lname = models.CharField('lname',max_length=120) username = models.CharField('username',max_length = 60,unique=True) password = models.CharField('password',max_length=120,default='pavi@2789') USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['fname','lname'] objects = MyUserManager() def __unicode__(self): return self.username class Meta: # managed = False db_table = "user" forms.py ------- #User Registration Form class UserRegistrationForm(forms.Form): fname = forms.CharField(required=True,label='FirstName',max_length=32,widget=forms.TextInput(attrs={ 'autocomplete':'off'})) lname = forms.CharField(required=True,label='LastName',max_length=32,widget=forms.TextInput(attrs={ 'autocomplete':'off'})) username = forms.CharField(required = True,label = 'Username',max_length = 32,widget=forms.TextInput(attrs={ 'autocomplete':'off'})) password = forms.CharField(required … -
How Can I Display Data on same page after clicking radio button in Django
I have two Div section, One Div section contains list of radio button, I want to when i click the radio button, display the data corresponding to radio button on another Div section. <div class="card-body "> <form id="ShowAvailableDataFiles" method="post"> {% csrf_token %} {% for post in posts %} <input type="radio" id="showavailabledataid" name = "datafilesname" value= '{{post}}' onclick="ShowAvailableDataFiles()"> {{post}} <br> {% endfor %} </form> </div> <div id='show-me'> </div> <script> function ShowAvailableDataFiles() { $('#showavailabledataid').on('click', function () { var radioValue = $("input[name='showavailabledataname']:checked").val(); console.log("You clicked radio button") }); $.ajax({ url: "/analytics/datafile_name/", type: "POST", data: { datafiles: $("input[name='showavailabledataname']:checked").val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success : function(data) { console.log("=========") } }); } </script> -
Django - Upload multiple CSV Files without override
Is there a way to use update_or_create for multiple file uploads from different files? So right now I am able to upload a csv file to my sqlite3 database. If I change the csv file, the entries in the database get updated without any problems. But right now I am trying to add entries from another csv file. With my current approach I am overriding the entries in the database because I am only checking for the id. I am trying to add the entries of another File to my current database without having to copy the entries to the initial one. Here is my models.py class CSV5(models.Model): gebaeudebereich = models.CharField(max_length=100) gebaeudenummer = models.CharField(max_length=100) ebene = models.CharField(max_length=100) raum = models.CharField(max_length=100) dose = models.CharField(max_length=100) switch_ip = models.CharField(max_length=100) switch_port = models.CharField(max_length=100) datum = models.CharField(max_length=100) akteur = models.CharField(max_length=100) class Meta: unique_together = (("gebaeudebereich", "gebaeudenummer", "ebene", "raum", "dose"), ("switch_ip", "switch_port")) Here is my file upload function: if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) updated_obj = 0 created_obj = 0 duplicate_obj = 0 count = 0 if form.is_valid(): csv_file = request.FILES['file'] with open(str(csv_file)) as file: reader = csv.reader(file) for row in reader: count += 1 try: datet = datetime.now().date() datum = datet.strftime("%d.%m.%Y") row[7] = … -
Pdb can find a value but can't find it with Django
I'm working on a website using Django, and I debug with Pdb. I'm trying to reach for a value in the init of a form, when I try to reach it through self.instance.company.id I get an error telling me that my model doesn't have any company, but when I put pdb.set_trace() at the same point I tried to reach it, inside Pdb I can find it and get the value I'm looking for. Here the code where I try to get it: def __init__(self, *args, **kwargs): super(HarvestChoiceForm, self).__init__(*args, **kwargs) print(self.instance.company.id) self.fields['culture'].queryset = models.Harvests.objects.filter( display = True).all() Can anybody tell me why I can find it in pdb but not in django ? (^_^) -
Microsoft Edge Browser Django Admin login not working
I am trying to login on django admin using Microsoft Edge Browser, but there is no luck that I can login to the admin site. Everything is working in other browsers even on internet explorer it's working smoothly except some CSS issues. I have tried everything from this link from comments, still no luck. Any help? -
How to join tables in Django 1.8
I have tried to access joined data in my django template but nothing works, a little help is deeply appreciated. Model1(): project_code = Foreignkey(another table1) shot_code = charfield(primary_key = True) shot_name = charfield() sequence_name = Integerfield() Model2(): vendor_id = Foreignkey(another table2) shot_code = Foreignkey(Model1, on_delete= models.CASCADE) shot_rate = integerfield() shot_bid = integerfield() I wanted to display Select * from Model1 a, Model2 b, where model1.shot_code = model2.shot_code and model1.project_code = "XXX" and columns to be accessed in template are 1. Shot code 2. Shot name 3. Sequence name 4. Shot rate 5. Shot bid 6. Vendor id I tried the following method 1. Using Select_related result = only values of model2 is displayed unable to access model1's data, error = 'QuerySet' object has no attribute model1 -
How to export excel or csv file after search data in Django 2?
I have a search function that returns json, this I use via ajax, but I also want to export to a csv file the data that returns this function. It occurred to me to do another function to export the data, which brings the search function I'm doing it like this def search(request): date = request.GET.get('date') queryset = List.objects.filter(date=date) data = serializers.serialize('json', queryset) return HttpResponse(data, content_type='application/json') def export_to_csv(request): data = search(request) # But that does not bring the search data print(data) # <HttpResponse status_code=200, "application/json"> I hope you understand my question, some idea or suggestion?