Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django no such table after migrations
After trying all sort of migration im still getting this error I only get this error when trying to save the new object Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 779, in save_base force_update, using, update_fields, File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 908, in _do_insert using=using, raw=raw) File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1332, in execute_sql cursor.execute(sql, params) File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 99, in execute return super().execute(sql, params) File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: desporto_noticia Models import datetime from django.db import models from django.utils import timezone class Noticia(models.Model): noticia_texto = models.TextField() noticia_imagem_path = models.CharField(max_length=100) noticia_titulo = models.CharField(max_length=100, default='Default') pub_data = models.DateTimeField('data de publicacao') … -
Localhost redirected too many times to send emails in Django
I am trying to view the contact page where users can send emails. However, when I URL to "/contact" it shows an "error: localhost has redirected me many times." I cleared my cookies several times. It worked before and now this error persists. Can someone please check if there's any coding error I must have made? I appreciate your thorough feedback! views.py ef contact(request): if request.method!='POST': return redirect('/contact') error=False if not EMAIL_REGEX.match(request.POST['from_email']): messages.error(request, "Please enter proper email") error=True if len(request.POST['message'])<2: messages.error(request, "Please enter message") error=True else: message=request.POST.get('message') from_email=request.POST.get('from_email') email = EmailMessage( subject='Contact Form', body=message, from_email=settings.EMAIL_HOST_USER, to=[settings.EMAIL_HOST_USER], reply_to=[from_email] ) email.send(fail_silently=False) messages.success(request, "Thank you for your message! We will reply soon.") return render(request, 'first_app/contact.html') contact.html <h1 class=text-center>Contact</h1> {% if messages %} {% for message in messages %} <div class="alert alert-success p-2 pb-3"> <a class="close font-weight-normal initialism" data-dismiss="alert" href="#"><samp>×</samp></a> {{message}} </div> {% endfor %} {% endif %} <form action="/contact" method="POST"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlInput1">Email address</label> <input type="email" class="form-control" name="from_email" placeholder="Please enter e-mail" required> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Message</label> <textarea class="form-control" name="message" rows="3" placeholder="Please enter message" required></textarea> </div> <button type="submit" value="/contact" class="btn btn-dark">Submit</button> </form> -
AttributeError: 'module' object has no attribute 'home'
I've been following this guide on the first steps to setting up a website, but I'm getting an attributeerror when trying to launch the website in development mode. The link to the guide is: https://www.zeolearn.com/magazine/first-steps-to-create-the-website-with-django I've pasted the git bash output i get when i try to $ python manage.py migrate and the url.py file below it. $ python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 327, in execute self.check() File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 256, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 400, in urlconf_module return … -
restricting staff users to user dashboard
I want to restrict staff users from going to normal user dashboard def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: if user.is_active: return redirect('admin') esle: login(request, user) return redirect('users:home') # Redirect to a success page. ... else: # Return an 'invalid login' error message. ... I wan the staff types to only login from admin panel and they shouldn't be able to access users dashboard. -
I'm doing a project and am wondering is it possible and if so how could I write a queries to create the context for my table
I'm trying to create a context to render into a html table. I want to populate the table with the name of each currency the user has purchased,total current amount owned of that currency, total purchased amount, total sold amount, total current value of specified currency, total purchased value, and total sold value. I,m really struggling to do this is it possible? and if so could i get some advice on how Function Below def portfolio(request): count = Transaction.objects.filter(owner=request.user).values('currency').distinct(),count context = { } return render(request, 'webapp/portfolio.html', context, {'title': 'Portfolio'}) Html Table below <table class="table"> <thead> <tr> <th scope="col">Coin</th> <th scope="col">Current</th> <th scope="col">Purchased</th> <th scope="col">Sold</th> <th scope="col">Current Value</th> <th scope="col">Purchased Value</th> <th scope="col">Sold Value</th> </tr> </thead> <tbody> {% for total_transaction in total_transaction %} <tr> <td>{{total_transaction.currency}}</td> <td>{{total_transaction.current_amount}}</td> <td>{{total_transaction.purchased_amount}}</td> <td>{{total_transaction.sold_amount}}</td> <td>{{total_transaction.current_value}}</td> <td>{{total_transaction.purchased_value}}</td> <td>{{total_transaction.sold_value}}</td> </tr> {% endfor %} </tbody> </table> Transaction Model Below class Transaction(models.Model): currency = models.CharField(max_length=20) amount = models.IntegerField() total_price = models.DecimalField(max_digits=8, decimal_places=2) date_purchased = models.DateTimeField() note = models.TextField(default="") owner = models.ForeignKey(User, on_delete=models.CASCADE) amount_per_coin = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def save(self, *args, **kwargs): self.amount_per_coin = self.total_price / self.amount super(Transaction, self).save(*args, **kwargs) def __str__(self): return str(self.pk)+','+self.currency + ', '+str(self.amount) def get_absolute_url(self): return reverse('transaction-detail', kwargs={'pk': self.pk}) @property def coin_value(self): try: current_price = requests.get("https://min-api.cryptocompare.com/data/price?fsym="+self.currency+"&tsyms=EUR") price = … -
How do you flush your db and loaddata fixtures without Nonetype lookup errors?
I flushed my database as I was ready to throw it onto Github and I was going to load some fresh fixtures with less data. However when I run python manage.py loaddata user.json or any other fixture, I get Nonetype errors for where my views are looking for data and can't find any. Is there a way to load these fixtures straight into the db without running the code? Am I missing something? $ python manage.py loaddata menu.json Traceback (most recent call last): File "manage.py", line 15, in <module> .... class CreateMenu(CreateView): File "C:\Users\gblac\Desktop\PandaFiles\PersonalRepo\Django\Django_1\django_env1\cornershop_backend_test\backend-test\django_project\menu\views.py", line 38, in CreateMenu success_url = reverse_lazy('DetailOption',kwargs={'pk':menu.pk}) AttributeError: 'NoneType' object has no attribute 'pk' (env_backend_test) -
I'm having trouble using 'success_url' with Django
In views I have the following classes: class AddPersonView(CustomCreateView): template_name = "register/add.html" form_class = PersonForm model = Person obj = Person.objects.all().count() if obj > 0: obj = Person.objects.last() success_url = reverse_lazy('register:edit_person_view', kwargs={'pk': obj.id}) def get_context_data(self, **kwargs): context = super(AddPersonView, self).get_context_data(**kwargs) class EditPersonView(CustomUpdateView): template_name = "register/edit.html" form_class = PersonForm model = Person obj = Person.objects.all().count() if obj > 0: obj = Person.objects.last() success_url = reverse_lazy('register:edit_person_view', kwargs={'pk': obj.id}) def get_context_data(self, **kwargs): context = super(EditPersonView, self).get_context_data(**kwargs) return context My intention is that when you submit submit on the person's registration page the new page is that person's edit page. But the way I'm using it, after adding or editing a person, the next page is opening with the id of the previous record. For example, if I now register a person with id 12 and give submit the page I should open it would be mysite.com/register/edit/12, but it is opening mysite.com/register/edit/11. I have tried to do the following: Instead of using the variable sucess_url, I used this function in both classes: def get_success_url(self): return reverse('register:edit_person_view', kwargs={'pk': self.kwargs('pk')}) However, by giving submit to the page I get this error: TypeError at /cadastro/editar/12/ argument of type 'NoneType' is not iterable During handling of the above … -
Should django render_to_string response be used in innerHTML?
Let me start by saying that this is my first Django project, so consider the possibility that I'm doing something fundamentally wrong. I'm working on a webpage that will show a report in an HTML table. I think the process I'm using to get the data and build the table is too complicated. It works, but I think there is probably a better way. Any suggestions are appreciated. At this point I have a Django project that consists of a single web page and the basic Django infrastructure. That page presents the user with some options to control a report and a button to start report generation. When the report generation is initiated, an XMLHTTPRequest is made to a url that is routed (via Django) to a view. That view calls an API to retrieve data and does some Python processing of the data. Then it calls the render_to_string function with the data and a template that uses django_tables2 to render a table. It returns the render_to_string response (wrapped in an HttpResponse) to the report web page. The report web page sets the tables innerHTML to the XMLHTTPRequest responseText. Here is the flow in a more succint version: User clicks … -
Correcting Django User Model Foreign Key issue
I am using the built-in django user model. I keep getting the error django.db.utils.IntegrityError: FOREIGN KEY constraint failed I did not use the user model in any other models and vice-versa. models.py looks like this from django.contrib.auth.models import User from django.utils import timezone from django.db.models import CharField from django.db.models import BooleanField from django.db.models import TextField from django.db.models import DateTimeField class Course(models.Model): id = models.AutoField(primary_key=True) name = CharField(max_length=100) class Project(models.Model): id = models.AutoField(primary_key=True) desc = CharField(max_length=150) name = CharField(max_length=50) storyboard_file_path = TextField() storyboard_completed = BooleanField(default=False) filming_complete = BooleanField(default=False) audio_complete = BooleanField(default=False) production_complete = BooleanField(default=False) aggregation_complete = BooleanField(default=False) video_file_path = TextField() final_review_complete = BooleanField(default=False) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="projects", null=True, blank=True) class Status(models.Model): status_id = models.IntegerField(primary_key=True) desc = CharField(max_length=150) name = CharField(max_length=50) class Event(models.Model): project_id = models.ForeignKey(Project, on_delete=models.CASCADE, null=True, blank=True) status_id = models.ForeignKey(Status, on_delete=models.CASCADE, null=True, blank=True) datetime = models.DateTimeField(auto_now_add=True, blank=True) serializers.py looks like this from rest_framework import serializers from .models import Event from .models import Project from .models import Course from rest_framework_jwt.settings import api_settings class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', "password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff", "is_active", "date_joined", "groups", "user_permissions") def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) … -
Could not resolve URL for hyperlinked relationship using view name
I'm trying to apply HyperlinkedModelSerializer to my User_Info model. When I try to do so I get an error saying: Could not resolve URL for hyperlinked relationship using view name "user_info-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I am supplying my models, views, serializers, and urls below. Could it be that I am inheriting from AbstractBaseUser in my model rather than models.Model? models.py class My_User_Info_Manager(BaseUserManager): def create_user(self, email, name=None, password=None, phone_number=None, reseller=None): user = self.model( email = self.normalize_email(email), name = name, phone_number = phone_number, reseller = reseller, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name=None, password=None): user = self.create_user( email, name=name, password=password ) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class User_Info(AbstractBaseUser): email = models.EmailField(max_length=225, unique=True, db_index=True, primary_key=True) name = models.CharField(max_length=255, null=False) phone_number = models.CharField(max_length=30, null=True) reseller = models.CharField(max_length=255, null=True) username = "Required for FTP Services" ### attributes and methods for superuser to access django admin is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) def has_perm(self, perm, obj=None): return self.is_superuser def has_module_perms(self, app_label): return self.is_superuser objects = My_User_Info_Manager() USERNAME_FIELD = 'email' serializers.py class UserInfoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User_Info # get model # add … -
Django: Message error does not appear when using option value for POST
When the user selects the following option values--it POSTs successfully. However, I am trying to send an error message when the user clicks "submit" without selecting any. When it "submits" without selecting, it gives an error: MultiKeyValueDictKeyError: 'venue'. How do I code it properly for error messages to show when the user submits without selecting? I appreciate your thorough feedback! views.py def add(request): if not 'user_id' in request.session: return redirect('/chrisgrafil') if request.method!='POST': messages.error(request, 'Please select the following options') return redirect('/dashboard') else: Ticket.objects.create(venue=request.POST['venue'], quantity=request.POST['quantity'], loop=request.POST['loop'], purchaser=User.objects.get(id=request.session['user_id'])) return redirect ('/confirmation') dashboard.html <form action="/add" method="POST"> {% csrf_token %} <div class="text-center"> {% if messages %} {% for message in messages %} <div class="alert alert-danger p-2 pb-3"> <a class="close font-weight-normal initialism" data-dismiss="alert" href="#"><samp>×</samp></a> {{message}} </div> {% endfor %} {% endif %} <label><strong>Location of Venue:</strong></label> <select class="form-control" name="venue"> <option value="" selected disabled>Please select</option> <option value="San Bernardino">San Bernardino</option> <option value="Los Angeles">Los Angeles</option> <option value="Riverside">Riverside</option> </select> </form> models.py class User(models.Model): first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) email=models.CharField(max_length=100) password=models.CharField(max_length=100) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) class Ticket(models.Model): venue=models.CharField(max_length=100) quantity=models.PositiveIntegerField() price=models.DecimalField(default=25.00, max_digits=5, decimal_places=2, null=True, blank=True) loop=models.CharField(max_length=100) purchaser = models.ForeignKey(User, related_name="purchases", on_delete=models.PROTECT) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) -
Django 2.1 how to use custom function to display context
I have a sidebar that displays popular posts ordered by amount of their comments. Piece of post's content is displayed using {{ post.message_html|truncatechars:60|safe }} in template. To get popular_posts I use context_processors.py: def get_popular_posts(request): context = {} context["popular_posts"] = ( Post.objects.all() .annotate(comments_count=Count("comments")) .order_by("-comments_count")[:3] ) return context How can I have the post.message_html processed by some custom function (the same) for each of popular_posts? Where this function should be written? models.py: class Post(models.Model): user = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey( Group, related_name="posts", null=True, blank=False, on_delete=models.CASCADE ) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( "posts:single", kwargs={"username": self.user.username, "pk": self.pk} ) class Meta: ordering = ["-created_at"] unique_together = ["user", "message"] and here is my .html template that I include in other template: <div class="left-bar"> <h4 style="text-align: center;">POPULAR POSTS:</h4> <hr> {% for post in popular_posts %} <div class="jumbotron"> <a href="{% url 'posts:single' username=post.user.username pk=post.pk %}">{{ post.message_html|truncatechars:60|safe }}</a> <hr> <span class="text-muted popular"> <p>comments: {{ post.comments.count }}</p> <p>author: {{ post.user.username }}</p> </span> </div> {% endfor %} </div> -
How to convert a list to html <ul> using a for loop in django template
This is my first post, I am just getting started with python and django. I have managed to successfully connect to a public (non authenticated) API. When I display the results - I can access all the fields however one of the fields is returned as a list - Other roles. I can display the whole list (unformatted), comma separated - but I can't figure out how to iterate over the list and render it as an <ul>. The returned list looks like this: SOC: 3112 Title: Electrical and electronics technicians Description: Electrical and electronics technicians perform a variety of miscellaneous technical support functions to assist with the design, development, installation, operation and maintenance of electrical and electronic systems. Qualifications: Entrants usually possess GCSEs/S grades, an Intermediate GNVQ/GSVQ Level II or a BTEC/ SQA award. NVQs/SVQs in Servicing Electronic Systems are available at Levels 2 and 3. Tasks: plans and prepares work and test schedules based on specifications and drawings; sets up equipment, undertakes tests, takes readings, performs calculations and records and interprets data; plans installation methods, checks completed installation for safety and controls or undertakes the initial running of the new electrical or electronic equipment or system; diagnoses and … -
How to send dynamic modal form fields to django
I'm creating dynamic modal form field and I want to send generated field value to django but just one field is sent to my django server. I woner if this is caused by the fact the input field have the same name. Any suggestion please ? <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { var max_fields = 10; var wrapper = $(".container1"); var add_button = $(".add_form_field"); var x = 1; $(add_button).click(function(e) { e.preventDefault(); if (x < max_fields) { x++; $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box } else { alert('You Reached the limits') } }); $(wrapper).on("click", ".delete", function(e) { e.preventDefault(); $(this).parent('div').remove(); x--; }) }); <div class="modal fade" id="multipleset{{ecriture.id_ecriture}}" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h6 class="modal-title" id="exampleModalLabel">Ajouter une &eacute;criture</h6> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form action="{% url 'multipleset' %}" method="post" enctype="multipart/form-data">{% csrf_token %} <div class="modal-body"> <div class="container1"> <button class="add_form_field">Add New Field &nbsp; <span style="font-size:16px; font-weight:bold;">+ </span> </button> <div><input type="text" name="mytext[]"></div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button> <button type="submit" class="btn btn-primary">Ajouter</button> </div> </form> </div> </div> </div> -
POST multiple files using Django test client in same request
I am trying to build some tests for uploads on my Django site. It allows multiple files to be uploaded so I need to test when multiple files are uploaded. Testing one file works great: from django.test import Client def test_stuff(self): myfiles = open('....\file.csv','r') c = Client() response = c.post('/', {'file':myfiles}) But trying it with a list of files doesn't work. def test_stuff(self): myfiles = [] for file in myfiles: myfiles.append(open('....\file.csv','r')) c = Client() response = c.post('/', {'file':myfiles}) And neither does: def test_stuff(self): myfiles = [] for file in myfiles: myfiles.append(open('....\file.csv','r')) c = Client() response = c.post('/', files={'file':myfiles}) or def test_stuff(self): myfiles = [] for file in myfiles: myfiles.append(open('....\file.csv','r')) c = Client() response = c.post('/', files=myfiles) My view gets the files from request.POST.get('myfiles'), but FILES is empty. Is there a way to POST multiple files with django test client or should I use something else? -
Permission Denied to Upload Django
i'm try upload file with django(xlsx) this is my code: myfile = request.FILES['document'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) on the model i have setup the folder "media" to uploads, get this error: Permission denied: '/var/www/html/inventariosRG/media/my_file.xlsx' this error i'm try fixed with this: PATH = 'media/' myfile = request.FILES['document'] try: import subprocess RUTA_ABSOLUTA = os.path.join(os.path.dirname(os.path.dirname(__file__)),PATH) subprocess.Popen('sudo chmod -R 777 '+RUTA_ABSOLUTA, shell=True) except Exception as e: raise Exception ("Error ",e) fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) this code only show the same error "permission denied..." please i'm try set the permission by command on django, any suggest thanks..!! -
Is it ok to make an API call within a function in the model.py, why has my application slowed so much after doing it?
I'm creating a crypto-currency app, I'm populating some tables with crypto data, in order to get some of this data I need to calculate api values against database values. I have done this by creating functions, and doing an api call in the models.py file, but it has slowed my application down so much. Am I doing something wrong? Is there a better way I could code this? models.py below. Has slowed immensely since adding the 4 properties class Transaction(models.Model): currency = models.CharField(max_length=20) amount = models.IntegerField() total_price = models.DecimalField(max_digits=8, decimal_places=2) date_purchased = models.DateTimeField() note = models.TextField(default="") owner = models.ForeignKey(User, on_delete=models.CASCADE) amount_per_coin = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def save(self, *args, **kwargs): self.amount_per_coin = self.total_price / self.amount super(Transaction, self).save(*args, **kwargs) def __str__(self): return str(self.pk)+','+self.currency + ', '+str(self.amount) def get_absolute_url(self): return reverse('transaction-detail', kwargs={'pk': self.pk}) @property def coin_value(self): try: current_price = requests.get("https://min-api.cryptocompare.com/data/price?fsym="+self.currency+"&tsyms=EUR") price = json.loads(current_price.content) return price["EUR"] except: return 0 @property def total_value(self): value = self.coin_value * self.amount return round(value, 2) @property def profit_loss(self): value = float(self.total_value) - float(self.total_price) return round(value, 2) @property def profit_loss_percent(self): value = ((float(self.total_value) - float(self.total_price))/self.total_value)*100 return round(value, 1) ``` table I'm adding to below ``` {% for transaction in transactions %} <tr> <td>{{transaction.currency}}</td> <td>{{transaction.amount}}</td> <td>{{transaction.amount_per_coin}}</td> <td>{{transaction.total_price}}</td> <td>{{transaction.coin_value}}</td> <td>{{transaction.total_value}}</td> <td>{{transaction.date_purchased|date:"j N … -
Nginx 502 Bad Gateway error when call api
I have a Angular build and an Django backend providing API's running on one server. I've configured them in nginx with the frontend having a proxy to the backend server. The backend is running on the url 127.0.0.1:8000/api and the frontend is running on localhost Config: worker_processes 1; events { worker_connections 1024; } http { server { listen 80; charset utf-8; server_name localhost; root /usr/share/nginx/html; index index.html index.htm; include /etc/nginx/mime.types; gzip on; gzip_types text/css text/javascript application/x-javascript application/json; location /api { proxy_pass http://127.0.0.1:8000/api; } location / { try_files $uri $uri/ /index.html; } } } Now when I do any api call from the frontend I get the a 502 Bad Gateway error GET http://localhost/api/posts/post/management 502 (Bad Gateway) -
Connecting to database-Unknown database error
I have mac, python 3.7, using xampp 7.3.4. I've created a database ("tradingsystem") in "phpMyAdmin". in settings.py I wrote: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'tradingsystem', 'USER': 'root', 'password': '', 'HOST': 'localhost', 'PORT': '' } I did python3 manage.py migrate and I got django.db.utils.OperationalError: (1049, "Unknown database 'tradingsystem'"). I used @Filly solution (here) and it did worked. It created "tradingsystem" database but I don't know where it is and I can't see it in "phpMyAdmin" page. Can I do something make tradingsystem show in phpMyAdmin? if not, where is the database (or how can I find it)? how can I connect to it and manage it? -
How to retrieve information from ManyToMany joining table
I have a Django application with the following models: class Topic(models.Model): key = models.CharField(max_length=255, primary_key=True) class Person(models.Model): first_name = models.CharField(max_length=255) interests = models.ManyToManyField(Topic, through='Interest') class Interest(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) source = models.ForeignKey(TopicSource, on_delete=models.CASCADE) The many-to-many relationship between a person and a topic is enforced with the interest table. However, this joining table contains an extra information which is the source of the information. From the shell, it is quite easy to retrieve the list of topics a person is interested in: >>> from app.models import Person, Topic, Interest >>> p1 = Person.objects.all()[0] >>> p1.interests.all() <QuerySet [<Topic: discrete_mathematics>, <Topic: statistics>]> But, it does not seem possible to retrieve the extra information from the joining table: >>> [item.source for item in p1.interests.all()] Traceback (most recent call last): File "<console>", line 1, in <module> File "<console>", line 1, in <listcomp> AttributeError: 'Topic' object has no attribute 'source' It makes sense since the interests attribute points to the Topic (interests = models.ManyToManyField(Topic, through='Interest')) Is there a way to also retrieve the source? -
How to change base url to login url?
I want to add a login page to the root url, so to access the site you must login. However, I have already built the site and I am unable to get it behind the login page. I tried to create use LoginRedirectView, but it does not work. My base url is /catalog/ where nothing shows 404 error and all of these pages come up with out login. What's the best way to put the full site behind a login? #urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', LoginRedirectView.as_view(), name='redirect-to-login'), path('home/', views.index, name='index'), path('lookup/', views.lookup, name = 'lookup'), path('home/results/', views.results, name='results'), ] #Add URL maps to redirect the base URL to our application from django.views.generic import RedirectView urlpatterns += [ path('', RedirectView.as_view(url='catalog/', permanent=True)), path('accounts/', include('django.contrib.auth.urls')), ] #views.py class LoginRedirectView(RedirectView): pattern_name = 'redirect-to-login' def get_redirect_url(self, *args, **kwargs): return 'accounts/login/' -
Django InlineModelAdmin not displaying inlineformset correctly
I'm developing a Django application in which a lot of models have foreign keys and m2m relationships. This results in many ModelChoiceField being displayed in the Django admin for my models. To make model choice more bearable, I installed the django-select2 app in my project. I have been trying to implement select2 in the inline forms the admin site displays when editing related objects, but the form doesn't render the ModelSelect2Widget (it renders a simple select; it doesn't even include the select2 library). What I tried was creating a ModelForm in forms.py overriding the relevant fields widgets, then, using inlineformset_factory, had a variable holding the factory class. Lastly, in admin.py, added my custom inline formset using the formset property of the InlineModelAdmin class. forms.py class FichaTecnicaForm(forms.ModelForm): class Meta: model = models.FichaTecnica exclude = ('pelicula',) widgets = { 'responsable': ModelSelect2Widget, 'cargo': ModelSelect2Widget, 'pais': ModelSelect2Widget } FichaTecnicaInline = inlineformset_factory(models.Pelicula, models.FichaTecnica, form=FichaTecnicaForm) admin.py class FichaTecnicaInline(admin.TabularInline): model = models.FichaTecnica formset = forms.FichaTecnicaInline extra = 0 # Some other code here # This is where the inlines are invoked class PeliculaAdmin(admin.ModelAdmin): inlines = [ FichaTecnicaInline, # some other inlines, not relevant... ] I was expecting that the inline form set would display the select2 widget … -
Django overlay UpdateView over a ListView
It is a bit of an open question, but I don't know where to start looking for an answer. I would like to have a simple ListView page, where there are items of a Model. If you click on an item, an overlay div comes (this is done with CSS/JavaScript). I would like to have the UpdateView's form (belonging to the clicked item) on this overlay div. So I am still at the same URL and I would prefer not to change it. Is this possible? If yes how? I am not asking you to write me code, just could you direct me somewhere to look for a solution? Thank you. -
Django - delete button on form not redirecting to the correct path
I have a html template on which multiple messages are posted and can be deleted using a 'delete' button that has been created. My code seeks to search for the id of the item to be deleted and delete it, redirecting to /deleteMessage and concatenating with the id number. I don't fully understand the process and have an error I cannot spot. html form <ul> {% for g in all_items %} <li> {{ g.content }} <form action="/deleteMessage/{{g.id}}/" style="display: inline;" method="post">{% csrf_token %} <input type="submit" value="Delete"/> </form> </li> {% endfor %} </ul> views.py relevant code def deleteMessage(request,GuestBookItem_id): item_to_delete =GuestBookItem.objects.get(id=GuestBookItem_id) item_to_delete.delete() return HttpResponseRedirect('/worldguestbook/') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('worldguestbook/',worldguestbookView), path('login/',loginView), path('addMessage/',addMessage), path('deleteMessage/',deleteMessage), ] I imagine it is this line that is causing the error - an error in concatenation and not redirecting to the right path. **<form action="/deleteMessage/{{g.id}}/"** Error message: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/deleteMessage/17/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ worldguestbook/ login/ addMessage/ deleteMessage/ The current path, deleteMessage/17/, didn't match any of these. -
How to use javascript to dynamically filter a many-to-many relationship in django
I have a django model where a many-to-many relationship exists. A physician can be at multiple facilities, and a facility can employ multiple physicians. In a separate app, I want to be able to add lab orders. A lab order will come from a facility, and then when a facility is selected, I want the physicians to filter down to only physicians associated with that facility. I've tried to write a view to facilitate this in addition to adding javascript to my html but I have gone wrong somewhere and I don't know where. I am new to django. physicians app class Physician(models.Model): npi = models.CharField(max_length=15, primary_key=True) class Facility(models.Model): facility_id = models.CharField(max_length=10, primary_key=True) name = models.CharField(max_length=100) accessioning app class Order(models.Model): accession_id = models.CharField(max_length=20, primary_key=True) patient_id = models.ForeignKey('Patient', on_delete=models.PROTECT) facility_id = models.ForeignKey('physicians.Facility', on_delete=models.PROTECT) npi = models.ForeignKey('physicians.Physician', on_delete=models.PROTECT) accessioning/views.py def order_new(request): if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): order = form.save(commit=False) else: form = OrderForm() return render(request, 'accessioning/order_add.html', {'form': form}) def search(request): patient_list = Patient.objects.all() patient_filter = PatientFilter(request.GET, queryset=patient_list) return render(request, 'accessioning/patient_list.html', {'filter': patient_filter}) def load_physicians(request): facility_id = request.GET.get('facility') physicians = Physician.objects.filter(facility_id=facility_id).order_by('name') return render(request, 'hr/physician_dropdown_list_options.html', {'physicians': physicians}) order_add.html {% extends 'accessioning/base.html' %} {% block content %} <h2>New Order</h2> <form method="POST" …