Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
[Django]Showing ImproperlyConfigured error "SQLite 3.8.3 or later is required (found 3.7.17)", but work normal in manage.py runserver
Please help to provide any ideas to direct wsgi or apache to the correct sqlite3 library. I was trying to deploy a website with basic modules and a "hello world" front page at a CentOS web server. However, internal server error was raised and only happens in web surfing (port 80) at www.example.com. The (port 80) runs fine when "python3 manage.py runserver" is called (Django version: 2.2.2). Here above is the details of error, which is about the incorrect version of SQLite 3.8.3 or later is required (found 3.7.17). I used to reinstall sqlite3 and not work. When changing No matter in root environment and virtual environment, both python2 and python3 can open the sqlite3 with version 3.28.0 (venv) [root@...]# python Python 2.7.5 (default, Apr 9 2019, 14:30:50) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.sqlite_version '3.28.0' (venv) [root@...]# python3 Python 3.6.8 (default, May 2 2019, 20:40:44) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.sqlite_version '3.28.0' >>> the code related in httpd.conf is ===== #<VirtualHost ip-address:80> ServerName example.com RewriteCond %{REQUEST_URI} ^/((sub_site/.*$)|(sub_site$)) RewriteRule … -
How to generate a unique 10 length number for account ID and saving it to a corresponding model field in Django
view model How to generate a unique 10 length number for account ID and saving it to a corresponding model field in Django -
ImportError: cannot import name 'memoize' when doing python3 manage.py migrate
I have an issue with migration in Django using python3 manage.py migrate it shows me about memoize I have installed django-memoize and included it on my settings.py but it still shows the error. Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/mycomputer/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/mycomputer/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/mycomputer/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mycomputer/.local/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/mycomputer/.local/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/home/mycomputer/.local/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/mycomputer/.local/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/mycomputer/.local/lib/python3.6/site-packages/adminsortable/admin.py", line 15, in <module> from django.shortcuts import render File "/home/mycomputer/.local/lib/python3.6/site-packages/django/shortcuts/__init__.py", line 14, in <module> from django.core import urlresolvers File "/home/mycomputer/.local/lib/python3.6/site-packages/django/core/urlresolvers.py", line 19, in <module> from django.utils.functional import memoize, lazy ImportError: cannot import name 'memoize' It should have migrated after installation of memoize. -
Will the inexistence param query filter raise Exception?
I have a Server model, when I query it, I use bellow filter condition: qs = qs.filter(switchesport__switches__is_listing=True) but there I have a question, the Server items may do not have the switchesport.switches, I mean the server.switchesport=None. Could I use the query filter? will it get an Exception? -
why can't my odering and list_view go together with fieldsets in django admin class
I'm trying to organize my admin page. I tried to use list_display to show the columns, and fieldsets to organize the section. admin.py class PencilManugacturerAdmin(admin.ModelAdmin): ordering = ['manufacturer_name'] list_display = ['manufacturer_name', 'id'] fieldsets = [("Manufacturer", {'fields': ["manufacturer_name"]})] models.py class PencilManufacturer(models.Model): manufacturer_for_type = models.ForeignKey(PencilType, default=1, verbose_name="Type", on_delete=models.SET_DEFAULT) manufacturer_name = models.CharField(max_length=100) manufacturer_description = models.CharField(max_length=300) manufacturer_img = models.ImageField(upload_to='images', blank=True) def __str__(self): return self.manufacturer_name class Meta: unique_together = ['manufacturer_name'] I expect to have my admin page to have columns and the section when I add data. If I don't comment out the fieldsets (and leave the 2 others active), or the ordering and list_display (and leave the fieldsets active), it will show these errors: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) … -
Django application on EC2 and RDS ( Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?)
I have created an EC2 instance on AWS and deployed my django application on it. Also created RDS postgres database on AWS. Whenever I access my public ip, I get the following error, OperationalError at / could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Both EC2 and RDS instances are connected. Verified by following, Connected RDS postgres using pgadmin4 on my local PC. Created supersuser on ec2 console and it populated the postgres. Nginx configuration: server { listen 80; server_name 18.218.45.241; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/Crowdsocial_project; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/Crowdsocial_project/crowdsocial.sock; } } Gunicorn configuration: [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/Crowdsocial_project ExecStart=/home/ubuntu/Crowdsocial_project/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/Crowdsocial_project/crowdsocial.sock main.wsgi:application [Install] WantedBy=multi-user.target EC2 Security group: RDS Security group: Settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep … -
How to add CSS styling to Django Input Popup from Incorrect Input
Looking to add CSS styling (preferably Bootstrap classes) to the error popup on a Django Form CharField when the incorrect length is entered. I already figured out how to add style to the text input itself (as can be seen in the attrs section of the code), but not sure how to add styling to the popup. The min length must be 5 and when less than this is entered a popup appears saying "Please lengthen this text to to 5 characters..", that is what I want to style. class CityForm(forms.Form): zipcode = forms.CharField(label='zipcode', max_length=5, min_length=5, widget=forms.TextInput(attrs={'placeholder': 'Enter a Zipcode', 'class' : 'form-control form-control-m text-center'})) -
Django (admin.e104) must inherit from 'InlineModelAdmin'
First of all - sorry for poor language, English is not my native. Trying to put some model as inline in the other two models gives some strange error (in title). I have two models of orders - remote and local. And In each of them i need to insert products in some unlimited quantity. Another aim - to show full list of products ordered locally and remotely in different lists. Solution for second aim - using second model of product inheritated from first with it's own manager (objects). Solutions for aim number one - to use inlines in admin classes of orders for appending exactly proper product in order (local product to local order and remote product - to remote order). Adding inline of local product to admin of local purchase works great. But adding inline of remote product to inlines field of admin file of remote order returns error for admin class of remote order - must inherit from 'InlineModelAdmin'. It also returns error even after removing inline from admin file of local order. Code example is next. Some code like this in models.py: class RemotePurchaseModel(models.Model): title = models.CharField number = models.IntegerField ... class LocalPurchaseModel(models.Model): title = models.CharField … -
Mongodb error in Django using Djongo : pymongo.errors.OperationFailure: unsupported type in filter
I am trying to connect a Django project to a MongoDB cluster and when running: py manage.py runserver or py manange.py migrate It keeps showing the same error : Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\recorder.py", line 73, in applied_migrations if self.has_table(): File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\introspection.py", line 48, in table_names return get_names(cursor) File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\introspection.py", line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\djongo\introspection.py", line 46, in get_table_list for c in cursor.db_conn.collection_names(False) File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymongo\database.py", line 715, in collection_names nameOnly=True, **kws)] File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymongo\database.py", line 677, in list_collections **kwargs) File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymongo\database.py", line 631, in _list_collections session=tmp_session)["cursor"] File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymongo\database.py", line 514, in _command client=self.__client) File "C:\Users\marlo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymongo\pool.py", line 579, in … -
Saving subclassed modelchoicefields from a form into Database Django
I have two apps maxes and workouts. I have subclassed a multiple choice field in the maxes app and in the forms it queries the workout app to pull all the lift names. This way I don't have to put the data in twice, it works and I get a list of all the lifts that I have put in my workout app. BUT when I go to save the data, it is putting in the workout name. I believe this is because I have declared the workout name with self in the models.py How do I save the lift name from the workouts table into my maxes database I have already tried to add in the sublcass field into the .save(). I have also changed to a raw form and not a model one maxes--fields.py from django.forms.models import ModelChoiceField class workoutsliftModelChoice(ModelChoiceField): def label_from_instance(self, obj): return str(obj.lift) maxes -- forms.py class maxesModelForm(forms.ModelForm): lift = workoutsliftModelChoice( label=("Lift"), queryset=wplans.objects.all(), required=True ) reps = forms.IntegerField() weight = forms.IntegerField() class Meta: model = maxes fields = [ 'lift', 'weight', 'reps' ] maxes -- views.py def maxesList(request, *args, **kwargs): maxesInputForm = maxesModelForm(request.POST or None) maxesListTemplate = maxes.objects.all() if maxesInputForm.is_valid(): maxesInputForm.save() maxesInputForm = maxesModelForm() context_form = … -
Hourly rental market place using Django?
To keep it simple and short. I have an idea about hourly rental market place but only know Python. Now I am stuck with an issue about how to integrate date and time, for sellers to state the availability of the product and hourly rate, and for buyer to book that item for certain hours. Every similar site I check has Ruby on Rails as framework, is that for a reason? Can I not achieve that using Django? -
How to share variables between classes?
I have 2 classes which require the other one to either run a function or call an object from the each other. The problem is that the object of one is "not defined" causing the other to not be able run the function. This throws the an exception and makes it revert to the default value which I want to be updated. Seems like a chicken and egg problem but I am sure this is normal in Python and I just do not understand how to solve it. class CreateSettings: def __init__(self, name, default): self.name = name self.default = default def getvalue(self): print(float(Settings.objects.values( str(self.name)).last().get(str(self.name)))) try: self.default = float(Settings.objects.values( str(self.name)).last().get(str(self.name))) return self.default except (NameError, AttributeError): return self.default man_serv_bonus_default = CreateSettings('manager_service_bonus_max', 300.00) class Settings(models.Model): manager_service_bonus_max = models.CharField( max_length=16, default=man_serv_bonus_default.getvalue()) The Settings class is used by the user to update settings through a form. The CreateSettings class will be used to initially set the values in the form and update the values after any time a user has submitted the form. How do I get around this? -
How to validate if clients age is >= 18 and whats the proper way of validating the fields
Whats the best way to check if a clients age is >= 18 and whats the best validation method for the fields! I have tried some different methods but all of them have errors! Most of these implementations i have found them on this site or by reverse engineering the Django's UserCreationForm Is this way that i am doing it the "correct" but i am missing something or there is a better way? Register Form class AccountCreationForm(forms.ModelForm): username = forms.CharField( label='Username', widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter username', 'id': 'registerUsernameInput' }, ), ) email = forms.EmailField( label='Email', widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter email', 'id': 'registerEmailInput' }, ), ) password1 = forms.CharField( label='Password', widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', 'id': 'registerPassword1Input' }, ), ) password2 = forms.CharField( label='Confirm Password', widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': 'Confirm Password', 'id': 'registerPassword2Input' }, ), ) date_born = forms.DateField( widget=forms.SelectDateWidget( years=[x for x in range(1940,timezone.now().date().year + 1)], attrs={ 'class': 'form-control', } ) ) class Meta: model = Account fields = ['username', 'email', 'password1', 'password2', 'date_born'] def save(self, commit=True): user = super(AccountCreationForm, self).save(commit=False) user.username = self.cleaned_data.get('username') user.email = self.clean_email() user.password = self.clean_password2() user.date_born = self.clean_date_born() if commit: user.save() return user def clean_password2(self): password1 = self.cleaned_data.get('password1') … -
Link to another template with form attribute
I have a form with a delete button. I had all code delete function and confirmation. My probleme is to add href references in the delete button. I use a ModelForm and I think link is not working: Error message: Reverse for 'confirm-delete' with arguments '('',)' not found. 1 pattern(s) tried: ['import\/confirm_delete\/(?P[0-9]+)\/$'] Tried several method to define the good url but still not working. I think the problem is that the argument to identify pk is not easy this is my group_edit.html page in which the button does not work: {% block page %} <form method="POST"> {% csrf_token %} <div class="col-lg-4 col-md-4 col-sm-4 content"> {% bootstrap_form form %} <button type="submit" class="btn btn-pink pull-right">Save</button> <button type="reset" class="btn btn-warning pull-left"><a href="{% url 'confirm-delete' form.group_id %}"></a>Delete</button> </div> <a href="{% url 'group-list' %}">Back to list</a> </form> {% endblock %} this is my views.py for delete : def confirm_delete(request, group_id): obj = get_object_or_404(Group, group_id=group_id) if request.method == "POST": obj.delete() messages.success(request, 'Deleted') # message for inform user of success - See messages in html file return render(request, 'imports/group_list.html') context = { "obj": obj } return render(request, "imports/confirm_delete.html", context) this is urls.py: path('confirm_delete/<int:group_id>/', views.confirm_delete, name='confirm-delete'), my confirmation page for deleting: {% block page %} <form method="post">{% csrf_token … -
Django: Displaying set of related data to current user
I want to display data from my database in given way: User set of emails At this moment I have something like that: models.py class Person(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) objects = PersonManager() class Email(models.Model): person= models.ForeignKey(Person,editable=False,on_delete=models.CASCADE) email= models.EmailField() objects = EmailManager() def __str__(self): return self.email class PersonManager(models.Manager): def get_by_natural_key(self,name,surname): return self.get(name=name,surname=surname) In my views.py I override get_context_data() method. Now, in my html file I have: {% for user in users %} //person {% for email in user.email_set.all %} {{ user.attr }} {{ email }} {% endfor %} {% endfor %} In this way, ordering is not by user, but by emails, for example: insted of user1 email1, email2 is user1 email1 user1 email2 -
How to properly maneuver through the values in a class in python?
I'm trying to display an object in html. The object is a digit ranging from 1 to 10 (from now on called "mood") and was previously recorded in models.py. The mood is connected to a different class called "day" through models.ForeignKey. In views.py I recall both "day" and "mood", that was previously recorded, so that the html page can be rendered with the appropriate day info and appropriate mood value for that day. Currently when I do that, instead of displaying a digit from 1 to 10, I get this " < Query Set [ < Mood: 7>]> " instead. views.py def day(request, day_id): # show all data for the day day = Day.objects.get(id=day_id) mood = day.mood_set.order_by('mood') context = {'day': day, 'mood': mood} return render(request, 'mood_collector/day.html', context) models.py class Mood_Morning(models.Model): day = models.ForeignKey( Day, on_delete=models.CASCADE, ) mood = models.FloatField(null=True, blank=True, default=0.0) def __str__(self): return '%d' % self.mood <p> Day: {{day}} </p> <p> Mood: {{mood}}</p> I expect the output to be " Mood: (insert digit 1-10) " instead I get " Mood: < QuerySet [< Mood: 7>]> " -
Django view looping and loosing ajax data
I have a search input on my home page. Previously I was saving the data in a database and my method passed results correctly to a template. However, the data had to be stored temporally so I started sending it via AJAX. After refactoring the code the results are received and formatted in my view, yet I cannot successfully render context in result template. Here's faulty method in views.py: def item_list(request): products = {} progress = 120 out = {} if request.is_ajax(): query = request.POST.get('items') products = format_products(query) out = Sets.objects.filter(ItemInSet__item__name__in=[name for name, metrics in products.items() if metrics == '1']).exclude(ItemInSet__item__name__in=[name for name, metrics in products.items() if metrics == '0']).distinct() if request.POST: if 'update' in request.POST: checks = request.POST.getlist('checks') time = request.POST.get('time') progress = None if checks: out = out.filter(level__in=checks) if time: out = out.filter(prep_time__lte=time) progress = {'value': time} if out: paginator = Paginator(out, 10) # show 10 per page page = request.GET.get('page', '1') try: out_paginated = paginator.page(page) except PageNotAnInteger: out_paginated = paginator.page(1) except EmptyPage: out_paginated = paginator.page(paginator.num_pages) else: out_paginated=out return render(request, 'item_list.html', {'products': products, 'results': out_paginated, 'progress': progress}) The template is rendered and after reaching {% empty %} tag 'No results matching your query.' is printed. Is the view somehow … -
How to add extra field to ManyToMany field's table without data loss
I want to add extra field to manytomany field's table which already created and populated. I know I can use 'through' parameter and specify custom model, but this approach will create new table and this not suitable for me. Is there any way to do it using already created table using django orm? -
What is the easiest approach to build server-side to my code?
This question is mostly theoretical: I am a beginner in developing server side applications, and I would like some opinions on the best way to put a server-side interface between my database and my website. I have the following structure: a local API written in django-rest, sending results to a Postgres database a Vue.js application Now, I need server-side code to handle the following things: login, secure authentication (possibly with tokens) fetch results from the database The server-side code does not need to interact with the local API, only with the database Is it easier to use Django or stick with all JS (node, ...)? Is it possible to use ajax/axios with Django? How do I handle secure authentication? -
How make a condition based on current date when hosting on Heroku?
I'm scrapping a website, and I'd like to have a condition based on the current date to create or not an object. I'd like to get the current date from Heroku, as I'll be hosting the webapp there. And I'm guessing they'll never fail with the date. Note: Any additional tip on how to set the current date (time zone) for Lima/Perú on Heroku is welcome. But I'm not sure how to get the current date of the Heroku server, so I can use it in my view: pseudo code: def today_editorial(request): #if editorial was created before just query it #else create object and return it, while saving in DB try: today_editorial = Editorial.objects.get(date=today_date) except: today_editorial = Editorial.objects.create( date=today_date, title=title) return render(request, 'editorial.html', {'today_editorial ': today_editorial}) -
In Django, When I updated the published date How I get the get_absolute_url is updated?
I built a Django blog application (from Django2 by example book ) and I updated the published date I found the get_absolute_url function is not updated it always get the original link models.py #-- models.py -- #Create custom manager from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from slugify import slugify class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager,self).get_queryset().filter(status='published') def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, slugify(self.slug)]) class Post(models.Model): objects = models.Manager() published = PublishedManager() STATUS_CHOICES = (('draft','Draft'),('published','Published'),) title = models.CharField(max_length = 250) slug = models.SlugField(max_length=250, unique_for_date = 'publish',allow_unicode=True) author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now,blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, slugify(self.slug)]) Views.py #--views.py-- from django.shortcuts import render, get_object_or_404,get_list_or_404 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.views.generic import ListView from .models import Post def post_list(request): object_list = Post.published.all() paginator = Paginator(object_list, 3) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request,'blog/post/list.html',{'page':page,'posts':posts}) # Create second views def post_detail(request, year, month, day, post): post = get_object_or_404(Post,slug=post,status='published',publish__year=year,publish__month=month,publish__day=day) return render(request,'blog/post/detail.html',{'post':post}) class PostListView(ListView): queryset = Post.published.all() … -
Saleor e-commerce: How to batch insert products through python code or API
I am trying to do some tests on saleor e-commerce cms by adding some products automatically from some cvs file through python Unfotunately I have only found some examples GraphQL API for reading the existing products from the database Saleor Product Bulk upload script but I can not find nothing for add a product with GraphQL API. Any suggestions? -
Django - Add record to Many-to-many field (SelectMultiple widget) in form view
I'm trying to add records to manytomany field in form view and i don't know how to do it. I want something like the "plus" button in django's admin default site, to add new options in the selection field (and in the model's table). Or a popup that allows the user to complete the model's form. Thanks! -
Calling a view through requests module does not create proper session data
Supposing I have two views like below: def get_session_key(request): return JsonResponse({'session_key': request.session.session_key}) def test(request): import requests r = requests.get('http://127.0.0.1:8000/get_session_key') return HttpResponse(r) Why will calling get_session_key on its own return a valid response - containing the session key - whereas calling this function from test through requests will return {"session_key": null}? Is there a way to use requests for calling this view and still get a valid session key? -
TypeError at /snippets/1/
I am following wsvincent django rest framewok tutorial. I have done everything thats written there but when I run localhost/snippets/1/ it raises the following exception TypeError at snippets/1/ init() takes 1 positional argument but 2 were given. Kindly help if you know whats wrong. localhost/snippets runs fine. Here is the traceback. http://dpaste.com/00B8VHB models.py from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles # Create your models here. LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) class Meta: ordering = ('created',) def __str__(self): return self.title serializers.py from rest_framework import serializers from .models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields=('id','title','code','linenos','language','style',) views.py from django.shortcuts import render from rest_framework import generics from .serializers import SnippetSerializer from .models import Snippet # Create your views here. class SnippetSerializer(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class=SnippetSerializer class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Snippet.objects.all() serializer_class=SnippetSerializer urls.py from django.urls import path,include from rest_framework.urlpatterns import format_suffix_patterns from . import views urlpatterns=[ path('snippets/',views.SnippetSerializer.as_view()), path('snippets/<int:pk>/',views.SnippetDetail.as_view()), ] …