Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ordering by nested field in django-elasticsearch-dsl-drf
Sorry for a newbie question... Have an issue with nested field ordering - ordering is not working, what have I done wrong? documents.py: class ProductDocument(Document): name = fields.StringField( fields={ 'raw': fields.StringField(analyzer='keyword'), 'suggest': fields.CompletionField(), } ) brand = fields.NestedField( properties={ 'id': fields.IntegerField(), 'name': fields.StringField( analyzer='keyword', fields={ 'suggest': fields.CompletionField(), } ), } ) views.py: class GetProductViewset(DocumentViewSet): document = ProductDocument serializer_class = GetProductSerializer` filter_backends = [ FilteringFilterBackend, CompoundSearchFilterBackend, SuggesterFilterBackend, OrderingFilterBackend, ] ordering_fields = { 'name': 'name.raw', 'brand': { 'field': 'brand.name', 'path': 'brand', }, } ordering = ('brand', 'name',) Thank you in advance -
Setting up Django and Webpack on dev server using api subdirectory
Context: I'm using Django as a backend and Vue/Vuetify as a separate frontend. I use Apache to serve the frontend and Django is strictly for api calls in a client/server setup. I've set up WSGIScriptAlias to serve from [base_url]/api instead of the site root. I deployed the project and it's serving django request/repsonses from /api as expected. In my dev environment, I am running 2 concurrent dev servers. I'm running the webpack dev server (port 10000) for the frontend project, and the django runserver on a separate port (10001) to service my requests when developing. in webpack I've set up the following: devServer:{ hot: true, port: 10000 historyApiFallback: true, host: 'localhost', //django api proxy:{ '/api': { target: 'http://localhost:10001', pathRewrite: {'^/api' : ''}, secure: false } } } The idea here is that any time I request something from http://localhost:10000/api then it will redirect automatically to localhost:10001, which mimics how the production instance works since production cuts off the /api portion of the request. Problem: When I run the dev webpack and django server, I can successfully request localhost:10000/api and get a django response, but I noticed that when I attempt to access http://localhost:10000/api/admin, which should bring up the django admin … -
How to use cron to increase model class field at some rate in Django?
I was trying to increase dummy views of products in a product page at some rate and finally decided to use cron. I used django-crontab 0.7.1 for this. I did exactly like this answer and this documentation. My cron.py is: from . models import Products, Views import datetime def my_scheduled_job(): products = Products.objects.all() views = Views.objects.all() delta = (datetime.date.today()-products[0].dateUploaded) if delta.days == 0: Day = 1 else: Day = delta.days + 1 for product in products: #this is to calculate dummyView for each product DummyView = Day * views[0].X[product.id-1] * views[0].Y[product.id-1] DummyViewPerMinute = (DummyView/(24*60)) product.views += DummyViewPerMinute product.save() Command to see my active cron: $python manage.py crontab show Currently active jobs in crontab: a98d13d636dc8b4373d916ae9a5cb1b5 -> ('* * * * *', 'productsHome.cron.my_scheduled_job') Views don't seems to update after refresh, I don't think cron.py is really runnning, how can I make this cronjob run every minute? Also can I use cronjob after deploying this project to services like PythonAnywhere? -
Django - Passing context through message framework
In my project, I have a form which allows a user to signup for an account. If the user enters invalid data, e.g the username they entered is already in use, then I redirect them to the same page whilst using django's message framework to display an error. This works perfectly as the error is displayed in the template. Currently if a user enters invalid information, all the data is lost. What I want is to re-display the templates with all the previous data inside so they can correct it. How can I accomplish this? views.py: form = SignUpForm() context = {} if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): try: user = User.objects.get(username=form.cleaned_data['username']) messages.error(request, 'Username has already been taken') return redirect('signup') except User.DoesNotExist: ....... template: {% if messages %} {% for message in messages %} <span style="position: absolute;">{{message }}</span> {% endfor %} {% endif %} -
Customize django PasswordResetForm method get_users
I am new to Django, i wish to extend the PasswordResetForm and customize the get_users() method. I have a custom user model and instead of having the field "is_active " i have "active" and this raise an error Cannot resolve keyword 'is_active' into field. Choices are: active, >admin, email, email_verified, id, kyc_verified, last_login, logentry, >password, profile, staff, transaction I tried redefining my user model back to have the required field as "is_active" but i keep getting an error when migrating. django.core.exceptions.FieldError: Unknown field(s) (active) specified >for User Even when i change all instance of "active" to "is_active" Model Class class User(AbstractBaseUser): email = models.EmailField(max_length=254, unique= True) active= models.BooleanField(default=True) admin= models.BooleanField(default=False) staff= models.BooleanField(default=False) email_verified = models.BooleanField(default=False) kyc_verified = models.BooleanField(default=False) USERNAME_FIELD = 'email' #used to identify users EMAIL_FIELD = 'email' objects = UserManager() Form class ModifiedPasswordResetForm (PasswordResetForm): def get_users(self, email): active_users = UserModel._default_manager.filter(**{ '%s__iexact' % UserModel.get_email_field_name(): email, 'active': True, }) return (u for u in active_users if u.has_usable_password()) View def password_reset(request): if request.method == 'POST': form = PasswordResetForm(request.POST or None) if form.is_valid(): form.save(from_email='info@cryptoswapify.net',) messages.success(request, 'Password reset',extra_tags='alert') return redirect('passwordreset') else: messages.error(request, 'Please provide a valid email address',extra_tags='alert') return render(request, 'crypto/password_reset.html', {'form': form, }) form = PasswordResetForm() return render(request,'crypto/password_reset.html', {'form' : form}) i expect … -
How can I create an object with Djongo when it has EmbeddedFields?
I have two models using Djongo: from djongo import models class Sector(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Meta: abstract = True class Collaborator(models.Model): name = models.CharField(max_length=100) birth = models.DateField() salary = models.IntegerField() status = models.BooleanField() register_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) sector = models.EmbeddedModelField( model_container=Sector, ) objects = models.DjongoManager() def __str__(self): return self.name I want to execute this: Collaborator.objects.create( name='bla', # all normal fields... sector=None, # obviously I need something but None here, but what? ) But I get this error: ValueError: Value: None must be instance of Model: class 'django.db.models.base.Model' I can't instantiate a Sector since it is abstract. If I remove the abstract property from Sector it works fine instantiating it and then passing to the create function, but the idea here is to keep it that way since in Djongo website they say: In case you don’t plan on using your embedded model as a standalone model (which means it will always be embedded inside a parent model) you should add the class Meta and abstract = True This way Djongo will never register this model as an actual model. It is a good practice to define embedded models as abstract models and this … -
Django Template Variable Not Loading
Forgive me; I am very new to Django. In my django template, I am having trouble loading one specific variable from views (which is a string). All my other variables are loading well and good, and I know this variable exists as "h" in the code below. I have tested this fact and know it as a fact. And yet, it is not displaying! index request from views.py w/ post as the issue: def index(request): con = sqlite3.connect('db.sqlite3') template = loader.get_template('searching/index.html') if request.method == 'POST': keyword = None years = None keyword = request.POST.get("keyword") years = request.POST.get("year") if years is not None: years = int(years) cursor = con.cursor() cursor.execute('SELECT * FROM searching_insight WHERE year = ?', (years,)) documents = cursor.fetchall() results = YearSearchTFIDF(years) script, div = YearsOnlyCharter(results, years) elif keyword is not None: keyword_for_query = "%" + keyword + "%" keyword_for_query = keyword_for_query.lower() cursor = con.cursor() cursor.execute('SELECT * FROM searching_insight WHERE body LIKE ?', (keyword_for_query,)) documents = cursor.fetchall() results = KeywordSearchTFIDF(keyword.lower()) if results == "No results found": div = "<div>No results found. Try again.</div>" return render(request, 'searching/index.html', {'errorsearch': "No documents found. Please try again."}) else: ordereddict1 = collections.OrderedDict(sorted(results.items(), key = lambda t: t[0])) results = dict(ordereddict1) script, div = KeywordOnlyCharter(results, … -
How to save a Foreign Key in Django without instance, but a hard coded value
Suppose I have these 2 models: class Shipment(models.Model): id = models.BigIntegerField(primary_key=True) order_id = models.ForeignKey('orders.Order', null=True, blank=True, on_delete=models.SET_NULL) class Order(models.Model): id = models.BigIntegerField(primary_key=True) ean = models.BigIntegerField(null=True, blank=True) The orders are already populated in the database, now I just want to link the shipments to the related order. But I have a list of hardcoded JSON to populate my shipment model. { "shipmentId": 541757635, "orderId": 23598235, } So the orderId in that JSON represents the primary key of a Order model that is already present in the database. How can I loop over this to connect the shipment model with the correct order model based on the order_id? Maybe a loop like this: for shipment in shipments: shipment = Shipment.objects.create(id=shipment.shipmentId, order_id=shipment.orderId But is this possible because there is no instance, just a hard coded value in the JSON? -
Is it necessary to learn both Python and Django? [on hold]
I want to learn python. So is it necessary to learn django after learning python. -
Click HTML link then add 1 to database record
I want to track how many clicks each link gets and want this to be stored in the database here under the courses model: https://github.com/justdjango/video-membership/blob/master/courses/models.py Line 9 specifically (will loop through multiple links) is the link I would like to track the number of clicks for: https://github.com/justdjango/video-membership/blob/master/courses/templates/courses/course_list.html Each time a course title link is clicked from that loop or if a specific course slug from course_detail.html page is accessed (example - /courses/course_slug) after clicking that link, add 1 to a record called page_views. What would the code be to accomplish this? -
Django: How to create a new user with a custom registration form
I am trying to make a custom registration form in Django, using HTML and CSS and not Django's form.as_p and Bootstrap. I have the following code in views.py: def signUp(request): if request.POST: username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password_confirm = request.POST['password-confirm'] if(valid_form(username, email, password, password_confirm)) { #create the new user } else { #send some error message } return render(request, 'index.html') I have my own function valid_form to check if the form fields entered by the user are valid. However, I am not sure how I can create the new user using Django's User Model. In all of the code examples regarding registration forms I have seen something like this: def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('main-page') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) Where they use form.save() to create the new user. Since I am not using Django's form model, how can I create a new user after validating form data? Any insights are appreciated. -
Django CMS admin-reverse
I am very new to django CMS, I am trying to add toolbar of my blog. This is my cms_toolbar.py file from cms.toolbar_base import CMSToolbar from cms.toolbar_pool import toolbar_pool from blog.models import BlogPluginModel from cms.utils.urlutils import admin_reverse class PollToolbar(CMSToolbar): def populate(self): menu = self.toolbar.get_or_create_menu( 'blog_pluginmodel', # a unique key for this menu 'blog', # the text that should appear in the menu ) menu.add_modal_item( name='Add a new blog', # name of the new menu item url=admin_reverse('blog_pluginmodel'), # the URL it should open with ) toolbar_pool.register(PollToolbar) But fires me an error below: NoReverseMatch at /en/ Reverse for 'blog_pluginmodel' not found. 'blog_pluginmodel' is not a valid view function or pattern name. I am not getting how can i fix this.. Can anyone help me in this case? What admin_reverse actually? -
why django templates for loop is rendering destroyed UI
I am trying to render some products using Django templates, but I get destroyed UI on production (it works locally) this is my code {% for product in products %} <div class="my-4 py-2 px-4 card rounded"> <a href="{{ product.get_absolute_url }}" class="text-dark text-decoration-none"> <div class="row"> <div class="col-sm-12 col-md-3"> {% if product.product_images.count %} <img src="{{ product.product_images.first.image.url }}" alt="{{ product.name }}" class="img-thumbnail border-0 rounded-10" width="300px" height="300px" /> {% else %} <img src="{% static 'products/images/no-image.png' %}" alt="no product image" class="img-thumbnail border-0 rounded-10" width="300px" height="300px" /> {% endif %} </div> <div class="col-md-9 mx-auto p-3"> <div class="row"> <div class="col pb-2"> <h3 class="card-title mb-0 text-{% if LANGUAGE_CODE == 'en' %}left{% else %}right{% endif %}"> {{ product.name|title }} </h3> <h5 class="text-{% if LANGUAGE_CODE == 'en' %}left{% else %}right{% endif %}"> <span class="badge badge-light text-secondary"> <span># </span><span>{{ product.category.name }}</span> </span> </h5> <hr> <div class="text-secondary"> {{ product.description|safe|truncatewords:20 }} </div> </div> </div> <div class="row py-3"> <div class="col-md-12 col-lg-6"> <span class="text-muted">{{product.created}}</span> </div> <div class="col-md-12 col-lg-6"> <form action="{% url 'cart:cart_add' product.id %}" method="post" class="d-flex justify-content-end align-items-center"> {{ cart_product_form }} {% csrf_token %} <input type="submit" value="{% trans 'Add to cart' %}" class="btn btn-outline-primary mx-2" /> </form> </div> </div> </div> </div> </a> </div> {% endfor %} but the product cards are overlapping on production and … -
Is there a way of using lookup_field to viewsets (Default router) instead of generic view (Simple Router)? (DRF)
I want to use slug as my pk by using lookup_field. The error I have is "Could not resolve URL for hyperlinked relationship using view name "service-detail". I figured that if I use generic view(ListAPIView or RetrieveAPIView), it'll work because in urls I can set up a simple route like path('services/slug/'). But I would like to know if there is a way of doing this with Viewsets. Which means how can I set up the urls (Default Router instead of Simple Router) to handle this? serializers.py class ServiceSerializer(serializers.HyperlinkedModelSerializer): title = serializers.CharField(required=True) slug = serializers.SerializerMethodField(read_only=True) description = serializers.CharField(required=False) price = serializers.IntegerField(required=True) service_image = ServiceImageSerializer(many=True) class Meta: model = Service fields = ('url', 'slug', 'title', 'description', 'price', 'service_image') lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field':'slug'} } def get_slug(self, instance): return slugify(instance.vendor.username + "-" + instance.title) views.py class ServiceViewSet(viewsets.ModelViewSet): queryset = Service.objects.all() serializer_class = ServiceSerializer lookup_field = 'slug' urls.py router = routers.DefaultRouter() router.register('categories', CategoryViewSet) router.register('services', ServiceViewSet) router.register('images', ServiceImageViewSet) urlpatterns = [ path('', include(router.urls)), ] -
Generate Django sitemap while using site framework
I am using sites framework with RequestSite (no SITE_ID set) to generate content based on domain. I need to generate sitemaps for each domain with different results but I didnt find a way how to make this two frameworks work together. Is there any way to get Site of the current request in Sitemap? (getting it from SITE_ID config is not an option for me). -
Get JSON data with Django
I am playing around with GeoIP2 and requested the following in my view. g = GeoIP2() city = g.city('google.com') tests = Test.objects.all() args = { 'tests': tests } return render(request, 'app/home.html', args) I receive a JSON response with a bunch of data, I am interested in "city" for example. {'city': None, 'continent_code': 'NA', 'continent_name': 'North America', 'country_code': 'US', 'country_name': 'United States', 'dma_code': None, 'latitude': 37.751, 'longitude': -97.822, 'postal_code': None, 'region': None, 'time_zone': 'America/Chicago'} My model # Create your models here. class Test(models.Model): city = models.CharField(default='', max_length=100) def __str__(self): return self.browser_family Despite some googling and Youtube videos I am not quite sure how I should grab for example "city" out of the JSON response. I looked at previous threads here but not quite sure it can be applied here, seems like other threads were for more sophisticated stuff. Any suggestions out there? Thanks in advance -
How to create a Select-Field from a queryset and implement it in a form
i have created a simple book-app, with 3 models, Book, Author, Genre. Everything works fine and now I want to create a Select-Field for the genre. The content of the Select-Field should be a queryset from the existing genres. The Select-Field should be in a template and when I chose a genre and click the Search-Button it should list the genre and its books. As I can't realize that I need your help for the following: Where I have to generate the Select-Field and can I implement it? What do I have to do in the views.py? Here what I have done so far in forms.py: class GenreSelectForm(forms.Form): categories = forms.ModelChoiceField(queryset=Genre.objects.all()) Furthermore I created a template (genre_select.html) as follows: {% block content %} <h4>Searching</h4> <form action="" method="GET"></form> {{ form.as_p }} <button type="submit">Search</button> {% endblock %} However I don't know if this is the right way and how to implement it. Here is my models.py from django.db import models class Genre(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name @property def get_books(self): return Book.objects.filter(genre__name=self.name) class Author(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=128) author = models.ForeignKey(Author, on_delete=models.CASCADE) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) isbn = models.CharField(max_length=10) price = models.DecimalField(max_digits=7, … -
ProgrammingError: relation "account_account" does not exist
I improved the registration form with django-user-accounts==2.1.0. Everything works fine on my local server, but on the heroku server I see the following error: Django Version: 2.2.6 Exception Type: ProgrammingError Exception Value: relation "account_account" does not exist LINE 1: ...nt"."timezone", "account_account"."language" FROM "account_a... Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py in _execute, line 84 I deleted the database and makemigrations/migrate again, it's did not help. -
How to access other model's primary key in urlpatterns?
I am getting NoReverseMatch when routing to a specific path. It is not able to find the primary key <int:pk> for only one urlpattern while getting results for all other similar paths. I am assuming this error is because the model here is different, ex, Not getting error for: class PostUpdateView(): model = A and the error I am getting is for: class AddCommentView(): model = B urlpatterns = [ path('post/<int:pk>/update/', PostUpdateView.as_view(), name = 'post-update'), path('post/<int:pk>/comment', AddCommentView.as_view(), name = 'post-comment')] Both classes are in same views.py file because I need model A's primary key in my routing url so that I can reverse to the original page. Error: Reverse for 'post-comment' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/comment$'] What is the correct way to include both models' keys in same route? Note: A's primary key is present in B as foreign key. -
Can't save form in Model Django
I am trying to save a form in my Model, but it isn't working as expected. When I am filling in the fields for the first time and press the button 'submit' the page is just reloading. When I try the second time, I get this error: django.db.utils.OperationalError: no such column: user_profile_product.product_user_id My code: Views.py def post_product(request): form = ProductForm() template_name = 'user_profile/add_product.html' if request.method == 'POST': form= ProductForm(request.POST) if form.is_valid(): name = form.cleaned_data['product_name'] description = form.cleaned_data['product_description'] price = form.cleaned_data['product_price'] user = request.user product = Product(name, description, price, user) product.save() return render(request, 'home_page/home.html', {'product': product}) else: form = ProductForm() return render(request, template_name, {'form':form}) Models.py class Product(models.Model): product_name = models.CharField(max_length=150 ) product_description = models.CharField(max_length=300) product_price = models.DecimalField(max_digits=6, decimal_places=2) product_user = models.ForeignKey(User, on_delete=models.CASCADE) Forms.py class ProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(ProductForm, self).__init__(*args, **kwargs) product_name = forms.CharField(max_length=150, required=True) product_description = forms.CharField(max_length=300, required=True) product_price = forms.DecimalField(max_digits=6, decimal_places=2) class Meta: model = Product fields = ('product_name', 'product_description', 'product_price') -
"from django... import..." unresolved import error
I'm following a Django crash course, and all there is right now are the __init__.py, settings.py, urls.py, wsgi.py in the project folder, as well as manage.py. Django is already installed through pipenv. In both urls.py and wsgi.py, there's are imports from Django from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pollster.settings') application = get_wsgi_application() respectively. The error that shows up is unresolved import 'django.core.wsgi'Python(unresolved-import) for all of the Django imports. I don't understand why, because with the VSCode Python shell shows no error when doing import django or any of the from django import... I've searched on Stackoverflow and it seems that this isn't really a problem, but I'm still not sure what exactly unresolved import means or what to do about it. -
How to use Axios/Vue.js to call data from SQLite/Django backend?
Status Quo: Whenever a user visits my web application, Axios makes a request to a third party API to fetch data and populate the frontend with that data. Desired status: Whenever a user visits my web application, Axios shall fetch the data from the SQLite database which itself is populated every XX seconds by a python request to reduce API calls. Now I implemented a SQLite database using Django models and views. So far so good, the API gets fetched and updates the database table properly. However, how can I now use the database data to populate the frontend? (1.) Due to several reasons I want to query the SQL data with Axios/Vue.js. After surfing through SO and Google I've seen that Axios somehow needs to call a view and the view will then query the database? (2.) That being said, do I need another view.py file that calls the SQL database? (3.) If I would insert the needed view function into the existing view.py file it would initiate another API call, wouldn't it? And how can I implement the link to the view function to Axios? Instead of a third party API url would I use some path for … -
Django Get whole filepath after upload
I'm building my first project with Django and I've some trouble with the filepath. I use a model to store the information to a db and pass get some fields/metadata from views e.g. size, filename,... My problem is now that Django automatically renames the file, if there is already a file with a similiar name. That's okay. But I don't find a way, how I can store the new name and filepath in my database. initial_obj.file.url just gives me "/media/filename.txt" but the right path is: "media/userfiles/2019/11/10/filename_1nswmaP.txt" views.py def model_form_upload(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): initial_obj = UploadModel(file = request.FILES['file']) initial_obj.status = 'Übermittelt' initial_obj.uploaded_by = request.user.username initial_obj.filename = initial_obj.file.name initial_obj.filesize = initial_obj.file.size initial_obj.filepath = initial_obj.file.url initial_obj.save() return redirect('home') else: form = UploadForm() return render(request, 'upload/fileupload.html', { 'form': form }) models.py from django.conf import settings class UploadModel(models.Model): file = models.FileField(upload_to='userfiles/%Y/%m/%d/') uploaded_at = models.DateTimeField(auto_now_add=True, blank=True) uploaded_by = models.CharField(max_length=255) status = models.CharField(max_length=255, choices = [("Fertig", "Fertig"),("Übermittelt","Übermittelt"),("In Bearbeitung","In Bearbeitung"),("Support","Support")]) filepath = models.CharField(max_length=999) filename = models.CharField(max_length=255) filesize = models.CharField(max_length=255) def __str__(self): return self.title -
How to make cursor adapt to the content of the new loaded page without moving it
I have an html page with links and button. When I put the cursor over each kind it changes to pointer. For links: When I'm clicking one, in my next page, the cursor remains in the same state (i.e. pointer) even though it's sitting on a non-clickable item. For buttons (input type=submit): When I'm clicking one, in my next page, the cursor does not change to pointer even thought is sitting this time on a button. Can I do something from HTML to adapt the cursor to new context in this two cases ? If it's relevant, I'm using Django's template engine to generate HTML. -
read data from PL and show plot in Django
I am very beginner in Django and Python. I have table in Postgres as below: ID |Date |Name |Price 1 , 2011.01.01 , A , 100 2 , 2011.01.02 , A , 200 3 , 2011.01.03 , A , 150 and I want to read this table in Django and show plot for 'A' company based on the date, actually in my plot X is Date and Y is Price value.