Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating tables for users in Django
I am creating a medical inventory system with Django. In this system, there are several. I want to create medicine tables ,in database, for the users. Every user has their own table. How can I make this? I am using mysql. users/model.py from django.contrib.auth.models import AbstractUser from django.db import models user_type = ( ('pharmacist', 'Pharmacist'), ('manager', 'Medical Repository Manager'), ) class CustomUser(AbstractUser): user_type = models.CharField(max_length=50, choices=user_type) def __str__(self): return self.username Note: Every user can add or delete medicine from their table. Because this is an inventory management system. -
How to using the form in 2 pages
Guys i am new to django and want to learn how to keep the same entry field in 2 different pages. In forms.py: class StudentForm(forms.ModelForm): name = forms.CharField(max_length=150) class Meta: model = Student fields = ['name',] In views.py def studinfo(request): form = StudentForm(request.POST) if request.method == "POST": if form.is_valid(): form1 = form.save(commit=False) name = form1.name background=Student.objects.get(stud_name=name) context={'profile':background ,} return render(request, 'main/stud_info.html', context) return render(request, 'main/main.html', context={'form':form}) in stud_info.html where it shows the results i also included: <form class="form-inline"> <input class="form-control mr-sm-2" type="search" aria-label="Search"> <button class="btn btn-outline-warning" type="submit">OK</button> </form> but it does not work as i do not know how to make it implement the function of studinfo(request). I do not want to create the same function and pass to the form. How automatically make it implement the same function in aother page? I hope i could explain what i want to learn. I apologise for any unclear explanation as Django is new for me and keep learning. -
How do i create a model for the alert message generated unique number?
views.py from django.contrib import messages import datetime import random def personal_detail(request): now=datetime.datetime.now() messages.success(request,now.strftime("SKPMMVY%Y%m%d%H%M%S")+str(random.randint(0,99))+str(":\tYour form has been submitted successfully")) I've generated unique number for each form submission ,how do i create a model to save it in the database so that i can use it as a reference -
Django Postgres migration: Fastest way to backfill a column in a table with 100 Million rows
I have a table in Postgres Thing that has 100 Million rows. I have a column that was populated over time that stores some keys. The keys were prefixed before storing. Let's call it prefixed_keys. My task is to use the values of this column to populate another column with the same values but with the prefixes trimmed off. Let's call it simple_keys. I tried the following migration: from django.db import migrations import time def backfill_simple_keys(apps, schema_editor): Thing = apps.get_model('thing', 'Thing') batch_size = 100000 number_of_batches_completed = 0 while Thing.objects.filter(simple_key__isnull=True).exists(): things = Thing.objects.filter(simple_key__isnull=True)[:batch_size] for tng in things: prefixed_key = tng.prefixed_key if prefixed_key.startswith("prefix_A"): simple_key = prefixed_key[len("prefix_A"):] elif prefixed_key.startswith("prefix_BBB"): simple_key = prefixed_key[len("prefix_BBB"):] tng.simple_key = simple_key Thing.objects.bulk_update( things, ['simple_key'], batch_size=batch_size ) number_of_batches_completed += 1 print("Number of batches updated: ", number_of_batches_completed) sleep_seconds = 3 time.sleep(sleep_seconds) class Migration(migrations.Migration): dependencies = [ ('thing', '0030_add_index_to_simple_key'), ] operations = [ migrations.RunPython( backfill_simple_keys, ), ] Each batch took about ~7 minutes to complete. Which would means it would take days to complete! It also increased the latency of the DB which is bing used in production. -
How to remove duplicates from Django QuerySet with MySQL database and related models
I use MySQL database in Django, so i can't use .distinct() to remove duplicates from QuerySet. I want to display each computer name with latest values of ip and last_on time. Models.py class Computer(models.Model) name = models.CharField() def __str__(self): return self.name class ComputerData(models.Model) pc = models.ForeignKey(Computer, on_delete=models.CASCADE) ip = models.GenericIPAddressField(null=True) last_on = models.DateTimeField() def __str__(self): return self.last_on.strftime('%Y-%m-%d %H:%M:%S') Views.py def computerlist_request(request): return render(request = request, template_name = "main/computerlist.html", context={"pc": Computer.objects.all(), "pcdata": ComputerData.objects.all()}) computerlist.html {% for p in pc, data in pcdata %} <tr> <td>{{pc.name}}</td> <td>{{data.ip}}</td> <td>{{data.time|date:"Y-m-d H:i:s"}}</td> </tr> {% endfor %} -
Carousel slider showing images in list with django
I’m new to django and I am creating a website which shows the product images on the home webpage in the form of a Carousel slider (bootstrap 4). {%extends 'blog/base.html'%} {%block content%} <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> <li data-target="#myCarousel" data-slide-to="3"></li> <li data-target="#myCarousel" data-slide-to="4"></li> <li data-target="#myCarousel" data-slide-to="5"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> {% for p in products %} {% if forloop.counter == 1 %} <div class="item active"> {% else %} <div class="item"> {% endif %} <img src="{{ p.image.url }}" alt="Image" width="460" height="345"> <div class="carousel-caption"> <h3>{{ p.name }}</h3> <p>{{ p.description }}</p> </div> </div> {% endfor %} </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> {%endblock content%} But this code only shows all the images in a straight line without the buttons on the side. I have provided the output: Images in Line I want all the images in the slider format with the navigation buttons Thanks -
MemoryError while saving large list of dicts in the Django database
At the very moment I try to save a 0.4mb list of complex objects to a json field I get a MemoryError exception. Does it really use so much ram memory to dump that into the database? It is a mysql database. I agree that data should not be stored in this way, but that's how the project is and I need to think of alternative ways of storing the data, but before changing the design I would like to know if there are workarounds for this memory error if this is an issue with django or python. Thanks in advance -
django- stream inside a template
I have a "Start Camera" button on my Index page. If clicked on that, I need to show Webcam feed on the same page (Index) and detect faces from the video. "Stop Camera" should stop the webcam. $(function() { $('.start-camera').on("click", function(e){ $(".item-container").html('<img src="/video_feed">'); }) }) urls.py urlpatterns = [ url(r"^$", views.index, name="index"), url(r'^admin/', admin.site.urls), url(r'^video_feed/', views.video_feed, name="video_feed"), ] views.py def index(request): return render(request, "web_app/index.html") def video_feed(request): return HttpResponse(gen(VideoCamera()), content_type='multipart/x-mixed-replace; boundary=frame') I am not mentioning the python scripts that contain the OpenCV code. That part is working correctly. The problem I am facing is: "video_feed" will keep serving HttpResponse until "Stop Camera" is pressed and the [img src= "/video_feed"] is removed from the DOM. But I cannot find a way back to index.html and actually see the webcam feed. If I could load the HttpResponse inside the index.html page, then my problem would be solved. But I have limited experience working with Django and cannot get my head around it. In Flask, I can just do this: @app.route('/video_feed') def video_feed(): return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame') This URL mapping does not return a view but only loads the response in the current index.html page. In Django, whenever I am registering a URL, I … -
How to fetch first form data and set that data in second form?
I have models Offer & OfferItem as below and I need to create an Offer and OfferItem at same template page. My problem is I want to save offer_form first then set saved offer record as related on itemOffer field then save offeritem_form how can I do it? Or may be my models and logic is completely wrong, if so is there any other way to do it? *I exclude HStoreField, cuz I will need to save multiple OfferItems at same page (may be I am wrong again I don't know) Here is my models etc. Models; class Offer(models.Model): offerCreate = models.DateTimeField(auto_now=False, auto_now_add=True) offerOwner = models.ForeignKey(User, on_delete=models.CASCADE) offerNumber = models.CharField(max_length = 150) offerCondi = models.TextField() offerTotal = models.FloatField() def __str__(self): return self.offerNumber class Meta: verbose_name = 'Offer' verbose_name_plural = 'Offers' class OfferItem(models.Model): itemOffer = models.ForeignKey('sales.Offer', on_delete=models.CASCADE) itemName = models.CharField(max_length = 150,null=True) itemProduct = models.ForeignKey('products.Product', on_delete=models.CASCADE) itemLeadtime = models.CharField(max_length = 150) itemCost = models.FloatField() itemPrice = models.FloatField() itemCurrency = models.ForeignKey('products.Currency', on_delete=models.CASCADE) itemQuantity = models.IntegerField() itemOfferprice = models.FloatField() def __str__(self): return self.itemName class Meta: verbose_name = 'OfferItem' verbose_name_plural = 'OfferItems' View; def createofferView(request): offer_form = CreateOfferForm(request.POST or None) offeritem_form = CreateOfferItemForm(request.POST or None) if offer_form.is_valid() and offeritem_form.is_valid(): offer_form.save() offeritem_form.save() messages.success(request, 'Success!') return … -
Django form sends mail twice
when creating a user from Django admin Panel, I am trying to send a mail that they have been added to the site. But, mail is getting triggered twice. Below is my code # Models.py class User(auth_models.AbstractBaseUser, auth_models.PermissionsMixin, TimestampedModel): email = models.EmailField(db_index=True, unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) is_staff = models.BooleanField(default=False, help_text='Allow the user access to the admin site') is_superuser = models.BooleanField( default=False, help_text='User has all permissions' ) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) # force_password_change= models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __unicode__(self): return self.email def __str__(self): if self.first_name == '' and self.last_name == '': return '{0}'.format(self.email) return '{0} ({1})'.format(self.get_full_name(), self.email) @property def token(self): return self._generate_jwt_token() def get_full_name(self): return "{0} {1}".format(self.first_name, self.last_name) def get_short_name(self): return self.first_name def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') def generate_password(self): password = User.objects.make_random_password() self.set_password(password) self.save() return password class Meta: verbose_name="Site Admin" verbose_name_plural= 'Site Admins' # Forms.py class UserCreationForm(forms.ModelForm): error_messages = { 'password_mismatch': "The two password fields didn't match.", } email= forms.EmailField(max_length=50, help_text="Required") password1 = forms.CharField(label="Password", widget=forms.PasswordInput) password2 = forms.CharField( label="Password confirmation", widget=forms.PasswordInput, help_text="Enter the same password as above, for verification." ) class Meta: model = … -
creation of tools or website for application deployment task
i’m python beginner and i want to make python tools for below requirement OR wanted to complete below task with Django website. Task: need to deploy some application which is on server over 400 machines and all are connected to VPN (IP is changing) so i have doubt how to implement/handle this with python any suggestion/guidance or steps. few challenges : suppose if all machines are not coming online then need to separate offline machines from list and get report of (online)completed machines. -
How to display custom errors in the template
I have function with custom errors, how to display these errors in the template def auth_join(request, room, slug): if request.method == 'POST': user = request.user.username form_auth = AuthRoomForm(request.POST) if form_auth.is_valid(): room_pass = form_auth.cleaned_data.get('room_pass') password2 = form_auth.cleaned_data.get('password2') if room_pass != password2: messages.error(request, 'Doesn\'t match') return HttpResponse('error') else: # messages.success(request, 'match') user = CustomUser.objects.get(username=user) room = get_object_or_404(Room, slug=slug) if user.has_perm('pass_perm', room): return HttpResponseRedirect(Room.get_absolute_url(room)) else: return HttpResponse('You don\'t have access to this page') else: form_auth = AuthRoomForm() return render(request,'rooms/auth_join.html', {'form_auth':form_auth}) I mean maybe try to do something like that,what i should use istead HttpResponse and how to implement in the template {% if form_auth.errors %} {% for field in form_auth %} {% for error in field.errors %} <div class="ui red message"> {{error}} </div> {% endfor %} {% endfor %} {% endif %} -
How to avoid storing in the database if an error occurs in the next iteration step
Input data is a list of dictionaries. The list can consist of several hundreds of dictionaries and looks like this. data = { "vendor_name": "Ullamcorper Duis LLP", "country": "Belgium", "nda": "", "modules": [ { "module": "" } ], "contacts": [ { "email": "jack@gmail.com", "contact_name": "Jack Jhonson", "primary": true }, { "email": "jack2@gmail.com", "contact_name": "Jack Jhonson", "primary": false } ] }, { "vendor_name": "Habitant Associates", "country": "Turkey", "nda": "", "modules": [ { "module": "" } ], "contacts": [ { "email": "eget.metus.eu@elitdictum.edu", "contact_name": "Trevor Smith", "primary": true }, { "email": "at.risus.Nunc@iaculis.ca", "contact_name": "Madonna Z. Kemp", "primary": false } ] }, .... .... ] Since some fields (for example, vendor_name) must be unique and if n-element and n+1 item are equal, the error "Vendor already exists" appears. And this is correct, of course. It so happens that some information is written into the database before the error occurs. But I need the writing to be done on the all or nothing principle. views.py class CsvToDatabase(APIView): serializer_class = VendorsCsvSerializer def post(self, request, format=None): r_data = request.data for data in r_data: if data['nda'] == '': data['nda'] = None for contact in data['contacts']: if contact['email']: contact['email'] = contact['email'].lower() for module in data['modules']: if module['module']: module['module'] = … -
Render HTML for REST API JSON data
What tools/solutions available for rendering html after REST API call returns JSON data? I have a Django webapp, where I built a set of REST API common for processing all data through the UI/browser or mobile app. The API will only return JSON, no HTML. I want to be able to draw tables, and do other HTML things on the browser-based on the data returned by the API, I cannot retrieve, or be loading html before the API calls. Do handlebars etc work in this situation? What are other effective options? -
Get most recent related objects for all objects
Suppose I have the following model: from django import models class Post(models.Model): user = models.ForeignKey(to=User, on_delete=CASCADE) created = models.DatetimeField(auto_now_add=True) I want to get some information about the most recent post (e.g. likes) from a group of users posts = User.objects.filter(**params).annotate(most_recent_post=Max('post__created')).annotate(likes=Count('post__likes', filter=Q(post__created=F('most_recent_post')) When I try to make this query, I get the following error: OperationalError: misuse of aggregation function MAX() -
Get items by date by clicking day field Javascript Django
I'm developing calendar app with Javascript and Django . I don't now how to display item by date by clicking the day . Is there any solutions ? I have a guess that I need to get elements by ajax on clicking the date . Here is some code : models.py class Item(models.Model): title=models.CharField(max_length=200) date = models.DateTimeField(default=datetime.now,blank=True) is_published=models.BooleanField(default=True) views.py def calendar(request): item = Item.objects.order_by('-date').filter(is_published=True) context={ 'item':item, } return render(request,'main/calendar.html',context) Javascript calendar draw methods drawAll() { this.drawWeekDays(); this.drawMonths(); this.drawDays(); this.drawYearAndCurrentDay(); this.drawEvents(); } Here is constructor of class Calendar drawYearAndCurrentDay() { let calendar = this.getCalendar(); this.elements.year.innerHTML = calendar.active.year; this.elements.currentDay.innerHTML = calendar.active.day; this.elements.currentWeekDay.innerHTML = AVAILABLE_WEEK_DAYS[calendar.active.week]; } drawDays() { let calendar = this.getCalendar(); let latestDaysInPrevMonth = this.range(calendar.active.startWeek).map((day, idx) => { return { dayNumber: this.countOfDaysInMonth(calendar.pMonth) - idx, month: new Date(calendar.pMonth).getMonth(), year: new Date(calendar.pMonth).getFullYear(), currentMonth: false } }).reverse(); let daysInActiveMonth = this.range(calendar.active.days).map((day, idx) => { let dayNumber = idx + 1; let today = new Date(); return { dayNumber, today: today.getDate() === dayNumber && today.getFullYear() === calendar.active.year && today.getMonth() === calendar.active.month, month: calendar.active.month, year: calendar.active.year, selected: calendar.active.day === dayNumber, currentMonth: true } }); constructor(options) { this.options = options; this.elements = { days: this.getFirstElementInsideIdByClassName('calendar-days'), week: this.getFirstElementInsideIdByClassName('calendar-week'), month: this.getFirstElementInsideIdByClassName('calendar-month'), year: this.getFirstElementInsideIdByClassName('calendar-current-year'), currentDay: this.getFirstElementInsideIdByClassName('display_day'), currentWeekDay: this.getFirstElementInsideIdByClassName('calendar-left-side-day-of-week'), prevYear: this.getFirstElementInsideIdByClassName('calendar-change-year-slider-prev'), nextYear: … -
Irregular behaviour of celery
I am very new to Celery and I am trying to use it to schedule a function, but its not working properly it seems. Here is my settings.py: (Along with the default settings given by django) CELERY_BROKER_URL = 'amqp://guest:guest@localhost' CELERY_ACCEPT_CONTENT = ['json'] CELERY_RESULT_BACKEND = 'db+sqlite:///results.sqlite' CELERY_TASK_SERIALIZER = 'json' celery.py: rom __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mera_project.settings') app = Celery('mera_project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() init.py: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] tasks_notes/tasks.py:(tasks_notes is my app name) from celery.decorators import periodic_task from celery.task.schedules import crontab from tasks_notes.models import BudgetInfo @periodic_task(run_every=(crontab(minute='*/15'))) def monthly_starting_value(): print("hi") return 0 views.py: from .tasks import monthly_starting_value def app_view(request): abcd = monthly_starting_value.delay() print("new"+str(abcd)) I had expected value zero and hi in my terminal, but instead of that I have got a random number as new 42bf83ef-850f-4b34-af78-da696d2ee0f2 and the random number keeps on changing in every 15 minutes. In my ``celery beat``` running terminal tab, I am getting something like: WARNING/ForkPoolWorker-9] hi Task tasks_notes.tasks.monthly_starting_value[42bf83ef-850f-4b34-af78-da696d2ee0f2] succeeded in 0.0009442089994990965s: 0 in every 15 minutes. I have even tried ``app.beat.conf_scheduleincelery.py``` and also tried running in admin phase, but its not working as expected. Where can I … -
How do I parse through this json data in a more efficient way with Python?
How do I parse through this json data in a more efficient way. I'd like to do it with a for loop so the code doesn't repeat itself. Here's the data endpoint: https://api.coingecko.com/api/v3/exchange_rates and the json response sample: { "rates": { "btc": { "name": "Bitcoin", "unit": "BTC", "value": 1, "type": "crypto" }, "eth": { "name": "Ether", "unit": "ETH", "value": 48.316, "type": "crypto" }, "ltc": { "name": "Litecoin", "unit": "LTC", "value": 169.967, "type": "crypto" } my view.py code: def btc_to_currency(request): exchange_endpoint = "https://api.coingecko.com/api/v3/exchange_rates" request_exchange_data = requests.get(exchange_endpoint) results_exchange_data = request_exchange_data.json() data_exchange = results_exchange_data["rates"] #print(data_exchange) btc = (data_exchange['btc']) xrp = (data_exchange['xrp']) xau = (data_exchange['xau']) xag = (data_exchange['xag']) return render(request, 'crypto/btc_to_currency.html', {'btc' : btc, 'xrp': xrp, 'xau': xau, 'xag': xag}) and my template html code: <table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth"> <thead> <tr> <th rowspan="2" class="is-size-7 has-text-centered">Name</th> <th rowspan="2" class="is-size-7 has-text-centered">Unit</th> <th rowspan="2" class="is-size-7 has-text-centered">Value</th> <th rowspan="2" class="is-size-7 has-text-centered">Type</th> </tr> </thead> {% load humanize %} <tbody> <tr> <th class="is-size-7 has-text-centered"><strong>{{ btc.name }}</strong></th> <td class="has-text-centered">{{ btc.unit }}</td> <td class="has-text-centered">{{ btc.value }}</td> <td class="has-text-centered">{{ btc.type }}</td> </tr> <tr> <th class="is-size-7 has-text-centered"><strong>{{ xrp.name }}</strong></th> <td class="has-text-centered">{{ xrp.unit }}</td> <td class="has-text-centered">{{ xrp.value|intcomma }}</td> <td class="has-text-centered">{{ xrp.type }}</td> </tr> <tr> <th class="is-size-7 has-text-centered"><strong>{{ xau.name }}</strong></th> <td class="has-text-centered">{{ xau.unit … -
save function in form and if status change a date should be created and then check or compare the status if true save the status to database
models.py class Item(models.Model): status_choices = [('Requested', 'Requested'), ('Processing', 'Processing'), ('Completed', 'Completed')] status = models.CharField(choices=status_choices, max_length=50, null=True, blank=True, ) completed_date = models.DateTimeField(blank=True, null=True) requested_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) froms.py class ItemForm(forms.ModelForm): class Meta: model = Item fields = ['status', created_at, requested at] def __init__(self, *args, **kwargs): super(ItemForm, self).__init__(*args, **kwargs) self.fields['status'].initial = 'Requested' def save(): pass i want to override my form and at the time of instance if i change the form value to completed. i want the date in my model filled with today's date in the field 'completed_at' and save it to database also can anyone help me? -
Strange non-breaking space when copying text from website in Chrome
I am developing a website in Django. It is a movie database. For creating a movie reference, I am using a join function like this: ''.join(i for i in movies) As a result, I get the following references for movies: Titanic. Directed by <i>James Cameron</i>. 1997. Everything is perfect on the backend side. On the frontend side, everything is visually OK, but when I copy the string with the movie reference and paste it into Microsoft Word, a non-breaking space appears before the italicized item instead of the regular space (I've tried italicizing other items as well, and it appeared everywhere before them): Titanic. Directed by°James Cameron. 1997. I do not add any non-breaking spaces, and I've tested out the backend side, no nbsp's appear there. Moreover, when I inspect the page in Chrome... it shows no non-breaking spaces: Titanic. Directed by <i>James Cameron</i>. 1997. How come that it appears on copying? And how can I avoid this behavior? P.S. I've tried this out on the book referencing site https://www.citethisforme.com/, and it's all the same. When adding a journal, this non-expected nbsp appears right before the italicized journal title element. -
Django create data with OnetoOneField
Hello thanks for your time: i'm trying to add some data to my model table trough management/commands/create_data.py: 1º Question in other project of mine i can call python manage.py create_data create_data.py although in this one is not working. How do i call the right command? 2º Question besides that i guess i'm gonna recieve an error at user field on People model because should be an id. How do i get the id? pets/models.py: User = get_user_model() class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person') birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.user) pets/management/commands/create_data.py: User = get_user_model() class GenerateUser(): username = None password = None def __init__(self, username, password): with open('User.txt') as file: for rows in file: self.username = slugify(rows) self.password = '12345' class GeneratePeople(): user = None documento = None birthday = None def __init__(self, documento, birthday): with open('People.txt') as file: for rows in file: t1 = rows.split(', ') self.user = slugify(t1[0]) self.documento = t1[1] self.birthday = t1[2] class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( 'file_name', type=str, help='ok') def handle(self, *args, **kwargs): username = GenerateUser.username password = GenerateUser.password user = GeneratePeople.user documento = GeneratePeople.documento birthday = GeneratePeople.birthday one = User( username=username, password=password ) one.save() peop = … -
Django m2m_changed signal for GenericRelation, is it possible?
Can it be used for a generic relation? I don't see it mentioned in the docs. A naive try of getting the through table: In [4]: Asset.related_images.through --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-4-d541db71a7a5> in <module>() ----> 1 Asset.related_images.through AttributeError: 'ReverseGenericManyToOneDescriptor' object has no attribute 'through' -
django check query return value or not
I need to get the destinationId value as query result from database, it works fine when there is matching value in database.If no match is there it results in error "matching query does not exist.".How can i solve this issue, also i need to run another query based ob=n the result,how can i check value exist or not? Am new to django and python, please help def get_route_list(request): if request.method == "POST": #Get the posted form areaDigit = request.POST['areaDigit'] productId = request.POST['productId'] destination_id=Routing_Dest_Area.objects.get(areaDigit=areaDigit).destinationId else: data = '' print(data) return render(request, 'routing/test.html',{'data':destination_id}) -
Implement serach in a corpus of document with Haystack an Whoosh
Hy, I am looking to add a search in some text (convert from pdf) to my app. I choice to use Whoosh. For the moment I have created an index of the documents with a Schema, create_in and add_document from Whoosh The index seems correct, I can read it with open_dir and reader from Whooosh. The link with my Django models is the name of the file in the Schema which contains an id, I am not sure it is the good way to link index with models ... Now I try to add a frontend form to allow user to search the index with a simple form CharFiled Google like and retrieve the original pdf document and I don't find the way to do this, the docs I found explain mainly how to search in models fields and not in an indexed corpus. Thanks for your time. -
Heroku cannot read '/etc/secret_key.txt', No such file or directory:
I successfully deployed a django app to heroku with my settings.py as such: SECRET_KEY = 'the_real_long_secret_key_itself', which of course is not recommended, but that was find for me just in this scenario as it is just a test and can be changed. Now back to my local environment, I decided to hide the key without changing it yet and according to django documents like this: # on settings.py with open('/etc/secret_key.txt') as s: SECRET_KEY = s.read().strip() And it works when I run server locally. But now when I try to commit & push like this: (herokuvirtualenv)tester1@test:~/$ git add -A (herokuvirtualenv)tester1@test:~/$ git commit -m "some editing" (herokuvirtualenv)tester1@test:~/$ git push heroku master It runs but ends up with this error message: remote: with open('/etc/secret_key.txt') as s: remote: FileNotFoundError: [Errno 2] No such file or directory: '/etc/secret_key.txt I have used search engines and there seems to be many ways to do this and it point that this should work, but there seems to be something I am omitting here. Could someone please help out?