Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NO SUCH TABLE DJANGO ERROR EVEN AFTER MAKING MIGRATIONS
I am getting Operational Error accessing http://127.0.0.1:8000/orders/create/ The error I get: OperationalError at /orders/create/ no such table: orders_order I have already tried making migrations. But the issue won't go away My models.py look like this: from django.db import models from ecom.models import Product # Create your models here. class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) #item info class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items',on_delete=models.PROTECT) product = models.ForeignKey(Product,related_name='order_items',on_delete=models.PROTECT) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * self.quantity and my views.py looks like this: from django.shortcuts import render from .models import OrderItem from .forms import OrderCreateForm from cart.cart import Cart # Create your views here. def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) # clear the cart cart.clear() return render(request, 'order/created.html', {'order': order}) else: form = OrderCreateForm() return render(request, 'order/create.html', {'cart': cart, 'form': form}) The line which Django … -
Feed customization and email notification based on it
There is a blog. It have a three model classes, who is subcategory of each other. And fourth model is post. They have a structure like that: ├───Category1 │ ├───Subcategory11 │ │ ├───subsubcategory111 │ │ ├───subsubcategory112 │ │ └───subsubcategory113 │ ├───Subcategory12 │ │ ├───subsubcategory121 │ │ ├───subsubcategory122 │ │ └───subsubcategory123 │ └───Subcategory13 │ ├───subsubcategory131 │ │ ├───post1311 │ │ ├───post1312 │ │ └───post1313 │ ├───subsubcategory132 │ │ ├───post1321 │ │ ├───post1322 │ │ └───post1323 │ └───subsubcategory133 │ ├───post1331 │ ├───post1332 │ └───post1333 It is necessary to implement the mechanism of email alerts about creation/update/deletion of the categories \ subcategories \ posts as follows: - the user can subscribe to a category (add to favorites) - then he will receive notifications about all movements of the category itself and its child objects (subcategories, posts - when adding \ editing \ deleting thereof) - the user can subscribe to a subcategory (add to favorites) - then he will receive notifications about all movements in this subcategory and its child objects (posts - when adding \ Editing \ removing add) - the user can subscribe to the post (add) - then it will receive notification of all movements (editing \ delete \ commentary) … -
How can Django mysql continuous deployment be implemented on windows server
I have a Django app currently running on local dbsqilte3. I used to deploy earlier using git, where git would sync sqilte3 databases both on the server and on my local machine. And I used to simply push/pull changes. Now I would like to migrate it to MySQL. How can I implement sync and at the same time experiment on the MySql database independent of server instance? I am running a windows server. I have a guess in this method's implementation. Won't I first install MySQL on the server and local machines independently and then somehow using some third party software I would be able to sync my databases or at least push updates and still not lose data that's already on the server? Any help with articles, migrations, agile methodology is much appreciated. As this is my first project with continuous deployment. -
Django admin template customization
I have a django admin site with multiple apps and also multiple admin sites inside and I need to add a logo for all pages. I've made it work by adding a index_template a and extending the base_site.html with my logo. Admin Site class xxxxAdminSite(admin.AdminSite): site_header = "xxx" site_title = "xxx" index_title = "xxx" index_template = "index.html" Base Site.html {% extends "admin/base.html" %} {% load static from staticfiles %} {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} <h1 id="site-name"> <img src="{% static 'xxx.png' %}" height="40px" /> </h1> {% endblock %} {% block nav-global %}{% endblock %} The problem is I'm currently changing the pages for all scenario's of the admin site eg. change_form_template, change_list_template, etc. But I need to add change_form_template and change_list template for all my admin.ModelAdmin's ModelAdmin class xxxxAdmin(admin.ModelAdmin): change_form_template = 'change_form.html' change_list_template = 'change_list.html' delete_confirmation_template = 'delete_confirmation.html' object_history_template = 'object_history.html' Any cleaner way to do it? Something like all model admins to point to a single eg. change_form?. -
OperationalError, no such column: hospi_treatmentgiven.patient_id
I am having three Models, and each model is connected to another with ForeignKey, and migrations are also running successfully but when I am trying to add TreatmentGiven manually from admin, I am getting Operation error class Patient(models.Model): firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) phone = models.CharField(max_length=20) alternate_phone = models.CharField(max_length=20) address = models.TextField() patient_id = models.AutoField(primary_key=True) gender= models.CharField(max_length=6, choices=Gender) class Ipd(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,blank=True) reason_admission = models.CharField(max_length=200, blank=True) provisional_diagnosis = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) weight = models.CharField(max_length=10,blank = True) bill_responsible = models.CharField(max_length=100,blank = True) bill_relation = models.CharField(max_length=100,blank = True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=True) date_of_admission = models.DateField(("Date"), default=datetime.date.today) condition_admission = models.CharField(max_length=20, choices=Admission_condition) consultant = models.CharField(max_length=20, choices=Consultant) def __str__(self): return self.patient.firstname class TreatmentGiven(models.Model): patient = models.ForeignKey(Ipd,on_delete = models.CASCADE,default = None) medicine_name = models.CharField(max_length = 100,null = True) types_of_doses = models.CharField(max_length = 100,null = True) route = models.CharField(max_length = 100,null = True) number_of_days = models.IntegerField(null = True) -
Celery task not starting at the start time provided
I have a Django app that utilizes celery in order to handle user scheduled tasks. I'm currently having a problem where I set start time for the PerodicTask and it does not start at that specific time, rather sometime later instead. Environment: Celery 4.3 Django 2.2 Python 3.7 task = PeriodicTask(name="foo",task="bar_task", start_time=DateTime5MinutesAhead, interval=EveryHourInterval) task.save() I expect the task run first in 5 minutes from when the task was created and then every hour after that. Instead, it seems to run at some arbitrary point later, completely ignoring the start_time argument. Am I mistaken on what the start_time argument is for? I've tried with IntervalSchedule as well as CrontabSchedule and neither seem to start at the exact start time. Bonus: What's actually really weird in my findings is that if I use IntervalSchedule set to every minute it actually DOES, in fact, start on correctly and run correctly, but if I set it to anything else it no longer works. -
Can't properly install Django-requests module
I followed the steps in this doc: https://django-request.readthedocs.io/en/latest/index.html Except step 4, which I'm not sure what it means: "Make sure that the domain name in django.contrib.sites admin is correct. This is used to calculate unique visitors and top referrers." However, I get this error, when I try to load my app: django.db.utils.OperationalError: no such table: request_request -
'str' object has no attribute 'items' using Django Rest Framework
I have a working Django project and when I deploy it to my server I get this error: AttributeError at /api/myData/ Django Version: 2.2.2 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'items' Exception Location: /pathToProject/lib/python3.7/site-packages/rest_framework/fields.py in to_representation, line 1729 On my local machine I am using Python3.6 but on the server I have 3.7. Requirements are the same. Any idea why this happens? settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', ‘myapp’, ‘myapp2’, ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_EXPOSE_HEADERS = ( 'Access-Control-Allow-Origin: *', 'Access-Control-Allow-Methods: GET, POST, PUT, DELETE', 'Access-Control-Allow-Headers: Authorization', ) CORS_ORIGIN_WHITELIST = ( 'http://127.0.0.1:3000', 'http://127.0.0.1:8000', ) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',) } ROOT_URLCONF = ‘MyProject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'MyProject.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': ‘somedatabasename’, 'USER': 'postgres', 'PASSWORD': ’somepassword’, 'HOST': 'localhost', 'PORT': '5432', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] STATIC_URL = '/static/' -
Is there a way to apply a filter to a URL generated with the URL tag in Django?
For part of my user interface I need a URLencoded URL. This code doesn't work, but it's intended to give an impression of what I'd like to do: {% url 'team_event_calendar' id=team.id | urlencode %} Basically, get a particular URL - in this case "team_event_calendar" for a particular team, and then URLencode it. I suppose I could make a new version of the URL tag which URLencodes everything, but is there a way to do it with just Django's built-in tags? -
Big django queryset in Python's if conditional expression
I have a queryset that was used in below code. result = 1 if queryset else 0 In case of small queryset it's okay but when queryset gets bigger (more than 500 000 results) program freezes, it takes some time to stop it. What is happening behind the scenes when Django's queryset is tested in the code above? Is some extra work performed during that check? Even though the queryset is big, there is no problem with calling count() or iterator() or any other methods, it is that conditional expression where the problem appears. -
Decide which model to retrieve data on Django Rest Framework
I'm trying to build a simple API which should do the following: A user makes a request on /getContent endpoint, with the geographical coordinates for this user. By content, it means audio files. Every time they send a request, we should just get a random object from a Model and return the URL field from it, to be consumed by the front end. For this, it can be a random one, it doesn't matter much which one. Also, we should keep tracking about the requests each user makes. This way, we can check how many requests the user has made, and when they were made. Every 5 requests or so, the idea is to send the user a customized content based on their location. My idea is to store this content in another model, since it would have many more fields in comparison from the standard content. Basically, at every request, I'd check if it's time to send a special content. If not, just send the random one. Otherwise, I'd check if the time is appropriate, and the user is within a valid location based on the special content's data in the model. If this validation passes, we send the … -
Django: Is there a way to make client render Python 3 functions locally?
I have a project that I want a client to run a for/while loop on his/her machine. Is there a way to do such a thing since views are run on server-side, such as below: views.py from django.shortcuts import render def index(request): for i in range(0,10000): # Do stuff return render(request, 'app/index.html') Javascript was one of the option for client side but I have some libraries that are from Python 3 I want to run. -
Django values_list extremely slow on large dataset
Getting a values_list in django is extremely slow on a large dataset (6M+ items). I have a Django application with a DB structure like: class Taxon(models.Model): name = models.TextField() class Specimen(models.Model): taxon = models.ForeignKey("Taxon", related_name='specimens') class Imaging(models.Model): taxon = models.ForeignKey("Specimen") image = models.ImageField(("Imaging")) And need to get a list of all (images, taxon) belonging to a Taxon, if there are more than "100" images of that taxon. This worked fine in development with a small database: image_list = list(Imaging.objects .annotate(items_per_taxon=Count('specimen__taxon__specimens__images')) .filter(items_per_taxon__gte=100) .values_list('image', 'specimen__taxon')) But takes 30 minutes on a full dataset (6M Taxon rows, and 2M image rows). Is there a way of indexing the 'foreign key of a foreign key' or creating a virtual column in postgres that can make this faster? -
Can you remove a clean_field from a form in a view?
I have a form in which I validate a field (clean_title). What I want to do is, delete the clean_title method in aCreateView view, is there any way to do it? The problem as such is that I don't want the title field validation in anUpdateView view, I just want that validation in a CreateView view. (I don't want to create another form I want to reuse this one.) In case you can't do what I want to do, is there any other alternative? # forms.py class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['title', 'subtitle', 'image', 'description', 'status'] widgets = { 'title': forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Titulo'}), 'subtitle': forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Subtitulo'}), 'image': forms.FileInput(attrs = {'class': 'custom-file-input'}), 'description': forms.Textarea(attrs = {'class': 'form-control', 'placeholder': 'Descripcion'}), 'status': forms.Select(attrs = {'class': 'custom-select'}), } labels = {'title': '', 'subtitle': '', 'image': '', 'description': ''} def clean_title(self): title = self.cleaned_data.get('title') if Course.objects.filter(title = title).exists(): raise forms.ValidationError('Ya existe un curso registrado con ese titulo, elige otro.') return title -
Input from template to a view in Django
As you can tell, i'm new to Django, but already love it. I have a functional scraping server that scrapes 7 selects from a diagnostics page on one server. All environments I want to use this will have many of these servers with the same data to monitor performance. I would like to use this function to scrape this data from all entered target servers by input from the html template. Adding each server to monitor that will show up below the input text field from the main html page. I have completed this with a static url, but have been unsuccessful passing the different urls to scrape from the html template to the views url variable I have for the static address. I've attempted to create forms and pass that to the html template without success, including editing the views file. Reverted the code back to the original working code to not cause more confusion. html template: <form method="POST"> {% csrf_token %} <div class="field has-addons"> <div class="control is-expanded"> <input type="text" class="input" placeholder="Relay Name"> </div> <div class="control"> <button type="submit" class="button is-info"> Add Relay </button> </div> </div> </form> Views.py: import requests, bs4 from django.shortcuts import render from django.http import HttpResponse from … -
Cognito/AWS Amplify SDK to use with Django
I decided to use Django for building the REST APIs for our Mobile App. For setting the login (custom and social both), decided to go with AWS Cognito/Amplify. Does Cognito/SDK provide any SDK(Python) to share/authenticate the JWT token with Cognito. Or is there any other mechanism to authenticate the users through Cognito to use Django REST APIs. Is there enough support from Congnito/ Amplify to build backend with Django? -
how to get content inside div in django?
i have the code below, i want to get the code inside the div and store it in the database. usually in the with attribut name i have no problem. for this html <input type="text" name="post_title"/> in my views.py i have if request.POST: title = request.POST['post_title'] but now i have <div id="editor"> <p>Hello World!</p> <p>Some initial <strong>bold</strong> text</p> <p><br /></p> </div> i want to get the html code inside the div with id editor. -
How to loop over dictionary to display in frontend in django and implement user input
Ive created my own dictionary from the tweepy api results. it displays the data I want on the frontend. However, how do I go about looping over my dictionary so html is produced for each dictionary created. I also wish to have user input determine the query parameter but not sure how do it This is what I've tried but no avail.. {% for tweet in twitter_data %} <div class="tweet-container"> <img src="{{twitter_data.profile_dp}}" alt="avatar" class="avatar" /> <time class="tweet-time">{{twitter_data.created_at}}</time> <div class="push"> <div class="user"> <div class="user-string"><span class="name">{{twitter_data.user_name}}</span><span class="username">@{{twitter_data.user_screen_name}}</span></div> </div> <blockquote class="tweet"><span class="at">@lorem_bot </span>{{twitter_data.text}} <span class="tag">#lorem2015</span></blockquote> <div class="icons"> <i class="fa fa-reply"><span class="icon-number"> 10</span></i> <i class="fa fa-retweet"><span class="icon-number"> {{twitter_data.retweet_count}}</span></i> <i class="fa fa-star"><span class="icon-number"> {{twitter_data.fav_count}}</span></i> <i class="fa fa-ellipsis-h"></i> <i class="fa fa-eye"></i> </div> </div> </div> {% end for %} from django.shortcuts import render import requests import tweepy import json # Create your views here. CONSUMER_KEY = 'm' CONSUMER_SECRET = 'Xu' ACCESS_KEY = '116' ACCESS_SECRET = 'wz' auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API(auth, wait_on_rate_limit=True) def index(requests): for tweet in tweepy.Cursor(api.search, query="xbox", q="{xbox}", count=1, result_type="recent", include_entities=True, lang="en").items(): twitter_data = { 'text': tweet.text, 'user_name': tweet.user.name, 'user_screen_name': tweet.user.screen_name, 'created_at': tweet.created_at, 'profile_dp': tweet.user.profile_image_url, 'retweet_count': tweet.retweet_count, 'fav_count': tweet.favorite_count } context = {'twitter_data': twitter_data} return render(requests, 'twitter/twitter.html', context) -
Django page shows status failure
today, my website looks like this: { "kind": "Status", "apiVersion": "v1", "metadata": { }, "status": "Failure", "message": "forbidden: User \"system:anonymous\" cannot get path \"/\"", "reason": "Forbidden", "details": { }, "code": 403 } Just a blank page with this error on it. Also it is not secured via HTTPS anymore. Yesterday, everything worked fine. I tried to restore the droplet on digitalocean, but still the same. What should I do now? Thank you very much -
How to add username to the filefield?
I am making use of file fields in my model and I want it to be saved as username_field.jpeg (or whatever format it is in), for example for rent_agreement I want to store it as username_rent_agreement.jpg. How am I supposed to do it? Please Help. Thanks in advance. -
I am confused what form_valid() or form_invalid() accomplished
I just started to use class based views instead of functions so sorry if this is an obvious question but what does form_valid() and form_invalid() do in a class that inherits from FormView? Django says that "This method is called when valid form data has been POSTed. It should return an HttpResponse" but what I don't get is how is it validated? I have additional checks I need to perform on the form before I can save the data (such as when signing up, making sure the two passwords entered are the same). How would I be able to add more checks if I want to? Here's the code I've been working with forms.py class SignupForm(forms.Form): email = forms.EmailField() alias = forms.CharField(max_length=15) password = forms.CharField(max_length=128, widget=forms.PasswordInput) confirm_pass = forms.CharField(max_length=128, widget=forms.PasswordInput) # used to verify if the passwords match def pwd_match(self): if self.is_valid(): cd = self.cleaned_data if cd.get('password') == cd.get('confirm_pass'): return True else: return False def fields_correct(self): if self.pwd_match() and self.is_valid(): return True return False views.py class SignupFormView(AjaxFormMixin, FormView): form_class = SignupForm template_name = 'forum/signup.html' success_url = reverse_lazy('home') def form_valid(self, form): # here I want to make sure that the passwords match and then save the user Thanks ahead of time! -
Django manage.py runserver command does not work
So I downloaded python (latest version) with everything checked and added it to PATH.I installed django, created everything I need, got the django files, but when i run python manage.py runserver it ptinys a lot of stuff, but in the end it prints I don't know anything about django or pip or python shell, I was following a tutorial but this doesnt work for me. C:\djangoproject>python manage.py runserver Traceback (most recent call last): File "C:\Program Files (x86)\Python\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Program Files (x86)\Python\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Program Files (x86)\Python\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Program Files (x86)\Python\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Program Files (x86)\Python\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Program Files (x86)\Python\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\Program Files (x86)\Python\lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", … -
How to use click event on <a> tag
How to use click event on tag without id Hello everybody, I have a html tag bellow: <a class="fc-day-grid-event fc-h-event fc-event fc-start fc-end fc-draggable fc-resizable" href="https://www.youtube.com/watch?v=XXXXX"><div class="fc-content"> <span class="fc-title">event</span></div><div class="fc-resizer fc-end-resizer"></div></a> this html code was built automatically by jquery so I can't add id or "onlick" event on this tag. What I want is when I click on this tag, it will open a new windows with href for me. I tried to use $('.fc-day-grid-event).on('click, function() { ...// }); But it's not working. How should I do for this case? Please help. -
IBM-Cloud Django Application integration with APP-ID
I've deployed a Python & Django Application in IBM Cloud Foundry and trying to integrate APP-ID for SSO. I received the OIDC provider information from the metadata provided from the APP-ID. But my question is how do I integrate the APP-ID with DJANGO APPLICATION for a Successful integration of SSO? Here is an example of how flask application, can be used but is there an example or process of how a Django application is done? https://dzone.com/articles/securing-your-python-app-with-openid-connect-oidc-1 For this integration, I tried to use below links for OIDC client in Django App and IBM APP-ID information for integration but no luck. APP-ID: https://dzone.com/articles/securing-your-python-app-with-openid-connect-oidc-1 OIDC: https://django-oidc-rp.readthedocs.io/en/stable/getting_started.html -
How can you use a single translation file in django?
I have many django apps in a single project that all have translations. Many of these translations are repeated across the different apps. I struggle to keep the translations consistent and hence I would prefer a single file for all translations in all apps. Is this possible? If so, how?