Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save relation between two models when creating one of them
I have three (simplified) models, let's call them Location, Thing and Where: class Location(models.Model): name = models.CharField() class Thing(models.Model): name = models.CharField() class Where(models.Model): location = models.ForeignKey(to = Location) thing = models.ForeignKey(to = Thing) Then I used the generic CreateView to create a Location. But I struggle to create a view to create a Thing. What I want to have is a form like this: class ThingForm(forms.Form): name = forms.CharField() location = forms.ModelChoiceField(queryset = Location.objects.all()) This form takes the data used to create a new Thing, but it also takes the date to create a new Where. However, I don't know how to create the new Where. My view looks like this: class ThingCreateView(generic.CreateView): model = Thing form_class = ThingForm success_url = 'somewhere/' I read that I have to override the view's form_valid function to do some stuff after the form data was validated: def form_valid(self, form): where = Where(location = form.location, thing = ???) where.save() return super().form_valid(form) The question is: What to put as thing? As far as I understood the documentation, the newly created Thing is not yet saved, thus I can't refer to it in the database's Where table. How can I create a relation between Thing … -
Django Get object if it has foreignkey
I'm creating an article app (in django) where articles can have images. I want to get articles only when they have at least one image. I already tried: Article.objects.all().annotate(num_extra=Count("Image")).order_by("-num_extra") But that only returned a sorted queryset starting with the most images and thats not wat I want. Is there a way to do that? -
Converting IntegerField to Int or Automated Testing ensuring value > 0
I am trying to ensure some IntegerField values are nonnegative. I have created a class like so (in the models file): class Category(models.Model): name = models.CharField(max_length=128, unique=True) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) #solution block attempts are inserted here I want to ensure views and likes are nonnegative. The test function is: class CategoryMethodTests(TestCase): def test_enusre_views_are_positive(self): """ ensure_views_are_positive should result True for Categories where view are zero or positive """ cat = Category(name='test', views=-1, likes=0) cat.save() self.assertEqual((cat.views >= 0), True) I have tried the following solutions, inserted at the comment line in the Category class, with errors posted corresponding to each: First attempt: if views < 0: views = 0 TypeError: '<' not supported between instances of 'IntegerField' and 'int' Second attempt: if int(views) < 0: views = 0 TypeError: int() argument must be a string, a bytes-like object or a number, not 'IntegerField' Third attempt: @property def ensure_views_are_positive(self): if self.views < 0: views = 0 return views This does not get any error message, but fails testing with: AsssertionError: False != True Probably because I am not calling the function anywhere. I am not really sure where to call it (and would prefer it be automated in the class). … -
django: What's the up-to-date way to flush the queryset results cache?
In the current (2.0) version of Django, what today is the best way to force Django to ignore any queryset result caches that it may be harboring and to re-retrieve information from the database? https://docs.djangoproject.com/en/dev/topics/db/queries/#caching-and-querysets ... explicitly talks about the cache, but doesn't actually say how to force it to be emptied. I'd prefer to do this the "official" way. Surely there must be one. -
How to pass arguments to a Serializer in django-rest-framework?
I have a serializer as: class DataSerializer(serializers.Serializer): skip_place = True name = serializers.CharField(max_length=None) place = serializers.CharField(max_length=None,required=False) def validate_place(self,value): if not skip_place and len(value)<=0: raise serializers.ValidationError("Place is required.") Now observe skip_place. If I call the DataSerializer instance as: DataSerializer(data=data, skip_place=False) Then it should validate over place as in the code. But I was not able to pass the argument skip_place=True. I get an error: TypeError: __init__() got an unexpected keyword argument 'skip_place' -
How to create a mapper app using django-admin?
I need to write a mapper app using django-admin site. I've described a model Article, for which the mapping (validation) should be performed. Here is what my app should allows me to do: 1) Using admin panel, browse .csv file with table-data (allow site administrator to open file from local storage, or add from remote url). 2) Create some-kind of 'Add object' page for each row in loaded data, on which Django should display Article's fields as usual, but with value choices from the row data. 3) If the data from .csv is valid for each field as It was described in Article model in models.py, then export this Object into a JSON-file, instead of saving in database; Else - Skip this row. from django.db import models class Article(models.Model): identifier = models.CharField(unique=True, max_length=255) number = models.CharField(max_length=255) preview_image = models.CharField(max_length=255) tile_image = models.CharField(max_length=255) width = models.FloatField(blank=True, null=True) length = models.FloatField(blank=True, null=True) vendor_code = models.CharField(max_length=255, blank=True, null=True) verified = models.IntegerField() class Meta: managed = False db_table = 'article' Basically, I need some info how to browse files in Django, if It's possible; how to make the file data to be available on my 'Add Article' page as choises= parameter, and export as … -
Management system for a construction site
I'm trying to create a small financial management system for a construction project, the idea is to create a web app that allows daily logging of activities (i.e: work hours, materials... Ect) for onsite technicians, and display of dashboards (i.e: total hours per day, different costs, kpis...) For managers, via a login interface that decides if its a manager or not. I'm thinking of using django+sqllite3 along with plotly and dash, but i would love your insights on what tools are appropriate for such task i.e : handling the login process, dispalying the forms and drawing the dasboards. Any help would be greatly appreciated Thanks in advance PS : i'm still fairly beginner, so sorry for any stupid questions that you might have encountered. -
Feedparser/RSS. How to pass dictionary from views.py to .html in django
I am trying to add simple RSS parser for my application. The objective is to grab RSS channel and display news from it on a single page. I am managed to do this for 1 single object, but can't do for X amount (10 for example). Project assumes I have views.py and RSS.html as output. So, code that IS working for one single parse object. views.py: import feedparser def rss(request): feeds = feedparser.parse("https://www.informationweek.com/rss_simple.asp") entry = feeds.entries[0] return render(request, 'posts/rss.html', feeds { 'title': entry.title, 'published': entry.published, 'summary': entry.summary, 'link': entry.link, 'image':entry.media_content[0]['url'] } ) RSS.html: <h3>{{ title }}</h3> <i>Date: {{ published }}<p></i> <b>Summary:</b><p> {{ summary }}<p> <b>Link:</b><a href="{{ link }}"> {{ link }}</a><p> <b>Image:</b><p><img src="{{ image }}"></img><p> I can't understand how to pass all feeds into RSS.html. I try to pass it through views and it doesn't work. Code that doesn't work: views.py: return render(request, 'posts/rss.html', feeds) RSS.html {% for entry in feeds %} <li><a href="{{entry.link}}">{{entry.title}}</a></li> {% endfor %} Please, help. Thanks! -
How to wrap whole content in a div in Django CKeditor and save in database
I am using Django CKeditor 5.6.1 and trying to save content that I have edited on CKeditor to a database with wrapping its content inside a div tag. So, how can I do that? For eg: I have a CKeditor content as below: And when I save this to a database it would be saved as: <h2><strong>My Heading</strong></h2> <p>This is my paragraph</p> But what I want to save is, wrap this content inside a div tag and add a class to that div like below: <div class="ckeditor-content"> <h2><strong>My Heading</strong></h2> <p>This is my paragraph</p> </div> -
Django Dumpdata with Specific DB
I have a Django project that will need consistent daily backups of the connected databases and it will run on Google App Engine while in Production. My application will have 1 database for each client (at the moment this is only 1, but the number will grow), and then a universal database to hold specific items universally accessible from the project. GAE has DB instance backups, but these are for the whole system and as far as I can tell this allows me no selective restorations, so I have decided that it will be best to simply backup each client-database individually. Because the project will be run on GAE, I have read that I will not be allowed to run sub-processes or any type of true system command while it is live (so bye-bye pg_dump), so I have been left thinking my best method to automate backups for individual DBs are going to be through Django commands, or more specifically dumpdata. My issue currently is, I am running into issues dumping data for a specific DB (I can't seem to find the right arguments to pass). 1) Can someone help me figure out the code below to backup my client … -
django paypal redirect with post data
I wanted to integrate paypal with django so I used django-paypal but when I render paypal form its fields are editable by inspect element So I cant directly set on submit to paypal redirect And I cant use paypal encrypted form because it required MdCrypto library and that is not available in python 3 So I thought of passing hashed amounts and other values so no one can directly set another one.This hint was taken from https://stackoverflow.com/a/33040436/7698247 But this leads to another problem if I need to validate it I had to make a request on my server and find out the actual values and redirect to actual paypal post url but I cant redirect to a url along with post data , Neither hitting post request directly will make any difference , becuase payment process has to be carried further. After more searching I found the question of django redirecting along with post data and I found this solution https://stackoverflow.com/a/3024225/7698247 but it has make used of session and both the views are of the same hosted project.In my case one view is mine and other is of the paypal What Can I do, What will be the best option?I … -
How to pass pk argument from url into view in Django?
I am having issues passing the pk from the URL into my view. I had this working before when all the URL's paths were situated in the same file but due to poor structure of files I had to re-organise things. I cannot figure out why this is no longer working. Details do exist as I've hard-coded the PK in the view and everything was displayed. It is probably something simple but would really appreciate some help. URL - http://127.0.0.1:8000/club_home/1/ index.html <h2>Our Clubs</h2> {% for club in all_clubs %} <a href="{% url 'clubs:club_home_with_pk' pk=club.pk %}"> <li>{{ club.club_name }}</li> </a> {% endfor %} urls.py: urlpatterns = [ url(r'^', views.club_home, name='club_home'), url(r'^(?P<pk>\d+)/', views.club_home, name='club_home_with_pk'), url(r'^edit/$', views.edit_club, name='edit_club'), ] views.py: def club_home(request, pk=None): if pk: club = ClubInfo.objects.filter(pk=pk) elif request.user.is_authenticated: club = ClubInfo.objects.filter(user=request.user) # photo = model.club_logo.ImageField(storage=profile_pics) args = {'club': club, } return render(request, 'club_home_page.html', args) club_home_page.html <h3>Club Details</h3> <p> {% csrf_token %} {% for info in club %} <li>{{ info.club_name }}</li> <li><img src="{{ info.club_logo }}" height="50px" width="50px"/></li> <li>{{ info.club_address1 }}</li> <li>{{ info.club_address2 }}</li> <li>{{ info.club_address3 }}</li> <li>{{ info.club_town }}</li> <li>{{ info.club_county }}</li> <li>{{ info.club_country }}</li> </p> -
Maintaining aspect ratio when resizing images with django-imagekit
I'm trying to set up responsive images for a photography website using django-imagekit. I wish to create 12 images in backend whenever a new image is uploaded - 3 viewports, 2 pixel densities and preferably 2 formats(webp, jpeg). I cannot seem to find any information that would indicate that it is possible to resize the images while maintaining the aspect ratio in django-imagekit. Also no mention of webp format in documentation. For example i use imagekit in admin for thumbnails: class AdminThumbnailSpec(ImageSpec): processors = [ResizeToFill(100, 100)] format = 'JPEG' options = {'quality': 60 } I would be happy to at least find a way to resize only width therefore retaining the aspect ratio. -
(Django) Can I change a Boolean type Model class attribute (and other attributes that aren't Fields)?
I've been learning a bit of Django by using Eric Matthes's *Python Crash Course *and stumbled upon the following problem. Namely, I had this code: class Topic(models.Model): text = models.CharField(max_length=200) public = models.BooleanField(default=False) public_2 = False def __str__(self): return self.text Then, in a view function, if I set public = True and public_2 = True, verifying in the shell, I would have topic.public = True, but public_2 = False. Why is this and is there any way to change the public_2 attribute? Here's the view function: def new_entry(request, topic_id): topic = get_object_or_404(Topic, id=topic_id) if topic.owner != request.user: raise Http404 if request.method != 'POST': # No data submitted; create a blank form. form = EntryForm() else: # POST data submitted; process data form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.public = True new_entry.public_2 = True new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) If there is no way to change this, are there other limitations on what types of attributes of the Model class can be changed? -
Django forms, display field.value as human-readable
I have following code in some of my html's: {% for field in gate_form %} {% if field.name in fields_to_show %} <tr> <td>{{ field.label_tag }}</td> <td>{% if field.errors %} <font color="red">{{ field.errors }}{% endif %}{{ field }}</font></td> </tr> {% else %} <tr> <td>{{ field.label_tag }}</td> <td>{% if field.errors %} <font color="red">{{ field.errors }}{% endif %}{{ field.value }}</font></td> </tr> {% endif %} {% endfor %} How to show field.value as human-readable (for example user root instead 1)? Is possible to use here get_FOO_display()? -
How to get a single record from a related table in Django?
I have this model (simplified version): class Photo(models.Model): image = models.ImageField(null=True, blank=True, upload_to='photos') photographer = models.CharField(max_length=255) class Genre(models.Model): title = models.CharField(max_length=255) class Decade(models.Model): title = models.CharField(max_length=255) class Album(models.Model): title = models.CharField(max_length=255) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) decade = models.ForeignKey(Decade, on_delete=models.CASCADE) photo = models.ForeignKey(Photo, on_delete=models.CASCADE, null=True, blank=True) As you can see some albums have photos. What I want to do is show a list with all genres, which will show how many albums there are in that genre for a particular decade, plus a photo for that genre. The photo should be the photo from an album in that genre. I can't get the first record's photo because it may not have a photo, so it should get the photo of an album that has a photo. Example: Genres: 1 | Rock 2 | Punk 3 | Jazz Albums: 1 | Rock All | genre = rock | decade = sixties 2 | Rock It Up | genre = rock | decade = sixties 3 | Jazz Basiq | genre = jazz | decade = nineties 4 | Jazz Uno | genre = jazz | decade = sixties 5 | Punkio | genre = punk | decade = sixties Photos: 1 | … -
Xampp need to restart each time I chnage my code in django
each time I change my code in Django I need to restart xampp to see the result I have set MaxRequestsPerChild 1 to solve my problem but it is not a good way for it because it cause restart xampp each time each project on xampp change and cause me downtime. I am looking for a way that do not restart apache and apache each time see my changes and run the code -
How can I send variables to paypal api and get them back with python SDK?
I am making a marketplace-type app with sellers and buyers and am trying to integrate PayPal API as a means to pay between users. I need to be able to send the seller's username(on my website) as a parameter to PayPal API and get it back after a successful payment so I can notify the seller he has been paid. How can this be accomplished? from paypalrestsdk import Payment from django.http import HttpResponseRedirect def payment_page(request): if request.method == 'POST': approval_url = 'http://127.0.0.1:8000/' paypalrestsdk.configure({ "mode": "sandbox", # sandbox or live "client_id": "client_id", "client_secret": "client_secret"}) payment = paypalrestsdk.Payment({ "intent": "sale", "payer": { "payment_method": "paypal"}, "redirect_urls": { "return_url": "http://localhost:8000/success", "cancel_url": "http://localhost:8000/fail"}, "transactions": [{ "item_list": { "items": [{ "name": "item", "sku": "item", "price": "5.00", "currency": "USD", "quantity": 1}]}, "amount": { "total": "5.00", "currency": "USD"}, "description": "This is the payment transaction description."}]}) if payment.create(): print("Payment created successfully") for link in payment.links: if link.rel == "approval_url": # Convert to str to avoid Google App Engine Unicode issue # https://github.com/paypal/rest-api-sdk-python/pull/58 approval_url = str(link.href) print("Redirect for approval: %s" % (approval_url)) return HttpResponseRedirect(approval_url) else: print(payment.error) else: print('loading page') return render(request, 'app/payment.html') def success(request): //Here I also want to capture seller username and buyer username payment_id = request.GET.get('paymentId') payer_id = … -
How to run more than one django sites using same virtual environment as subdirectories in apache?
I hv an unmanged vps. I have 3 django sites sitename_dev, sitename_staging, sitename_live which are run using a virtual env. I have configured my apache as follows. in /etc/apache2/conf-available/wsgi.conf #from virtual env LoadModule wsgi_module "/path/to/virtualenv/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so" WSGIPythonHome "/path/to/virtualenv" # dev site Include /path/to/sitename_dev.conf #staging #Include /path/to/sitename_staging.conf in path/to/sitename_dev.conf WSGIScriptAlias /sitename_dev /path/to/sitename_dev/sitename_dev/wsgi.py WSGIPythonPath /path/to/sitename_dev <Directory /path/to/sitename_dev/sitename_dev> <Files wsgi.py> Require all granted </Files> </Directory> in path/to/sitename_staging.conf WSGIScriptAlias /sitename_staging /path/to/sitename_staging/sitename_staging/wsgi.py WSGIPythonPath /path/to/sitename_staging <Directory /path/to/sitename_staging/sitename_staging> <Files wsgi.py> Require all granted </Files> </Directory> With this config my.ip/sitename_dev/ opens. But if I uncomment the staging site line, to include the staging site in /etc/apache2/conf-available/wsgi.conf, both my.ip/sitename_dev and my.ip/sitename_staging give 500 error. How can i run 3 sites as subdirectories ? specs: OS: ubuntu 16.4 LTS server: apache2 2.4.18 python version of virtual env & wsgi: 3.6 -
Pagination using Cursor Pagination
I have an api endpoint where I paginate tags using CursorPagination. class Tag(models.Model): name = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) class CursorSetPagination(CursorPagination): page_size = 15 page_size_query_param = 'page_size' ordering = '-created_at' class TagViewSet(ModelViewSet): serializer_class = TagSerializer queryset = Tag.objects.all() pagination_class = CursorSetPagination Now on the mobile client user is on the first page. The response will be like the following { "next": "http://0.0.0.0:8000/api/tags/?cursor=cD0xMDk1ODQ%3D", "previous": null, "results": [ { "id": 109598, "name": "foobar" }, { "id": 109597, "name": "displeas" } ] } A few new tags has been created. So how does my mobile client know about this update? -
Django trigram_similar search returns no result (Django 2.1 with Postgresql 10.5 backend)
I followed the instruction on https://docs.djangoproject.com/en/2.1/ref/contrib/postgres/lookups/#std:fieldlookup-trigram_similar to install trigram search on my search engine. I added 'django.contrib.postgres' in my INSTALLED_APPS in settings.py and installed the pg_trgm extension on my PostgreSQL database. The trigram search returns no result, but there is no error, just blankness where there should be search results. My search engine worked fine with icontain searches. Here is the code for my search engine with trigram_similar: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.filter(Title__trigram_similar=search_term) Title is a CharField in my model cross_currents: class cross_currents(models.Model): Title = models.CharField(max_length=500) This is what my Django shell gave me: In [6]: cross_currents.objects.filter(Title__trigram_similar='modern') Out[6]: <QuerySet []> The HTML page also returns nothing. However, when I do cross_currents.objects.filter(Title__icontains='modern') many results show up. Any idea why my trigram search returns nothing? -
Django encrypted paypal m2crypto python3
I was trying to add Paypal Integration with Django with the help of django-paypal https://django-paypal.readthedocs.io/en/stable/ Since I dont wanted the values to be changed by form I switched from PAypalPaymentForm to PayPalEncryptedPaymentsForm paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': str(subscription_rule.price_in_usd), 'item_name': "Software License Key", 'invoice': "Test Payment Invoice", 'currency_code': 'USD', "custom": "some extra data", 'notify_url': 'http://mynotifyurl.com/', 'return_url': 'http://{}{}'.format(host, reverse('payment_done')), 'cancel_return': 'http://{}{}'.format(host, reverse('payment_canceled')), } form = PayPalEncryptedPaymentsForm(initial=paypal_dict) but this requires a library M2Crypto that is available only in python 2 offically.So I cloned the unofficial edition of m2crypto in my site packages located at https://gitlab.com/m2crypto/m2crypto When I added this I got an import error for _m2crypto What Can I do now? -
Django static files can't be loaded on the google compute engine
I have run the python manage.py runserver command on my computer(windows 10) and it work but when I put all of codes on the google cloud platform compute engine(Ubuntu 16) and run the same command it shows all of the static files are not found. Do anyone knows how to fix it? settings.py (ignore some irrelative parts) import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_swagger', 'restaurants', # 餐廳APP 'webpack_loader', # 整合vue和django套件 'corsheaders' # 處理跨域請求套件 # 'gunicorn', # 部署用 ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'foodies.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '../static')], '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 = 'foodies.wsgi.application' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, '../frontend/dist'), ) WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': '', 'STATS_FILE': os.path.join(BASE_DIR, '../webpack- stats.json'), } } CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True # 允許所有header請求 CORS_ALLOW_HEADERS = ('*') static files path index.html url.py from django.contrib import admin from django.urls import path, include from rest_framework_swagger.views import get_swagger_view … -
Circular dependency when using util function in Django
Using Django I have some circular import dependency. e.g: # Views.py: import NonDjangoUtils class GetSomething(APIView): def get(self, *args, **kwargs): return NonDjangoUtils.util.calculate_something(kwargs['some_field']) And in: # NonDjangoUtils.util.py: import my_django.models def calculate_something(field): return my_django.models.SomeTable.object.filter(bla=field)[0].some_value This causes the following error when trying to use the site. Which as I understand it after debugging relates to circular dependency between the models, and external util functions Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000021FF85C8378> Traceback (most recent call last): File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\django\urls\resolvers.py", line 396, in check for pattern in self.url_patterns: File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\django\urls\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\django\urls\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\Program Files\Python36\lib\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 … -
How o fix "Operational Error; no such table:main.blog_post__old"?
I need to delete existing entries from my database. For deleting i am using class based view with the method super().delete(*args,**kwargs) but i am repeatedly getting the same error.. is there any way i can fix it?? views.py file, deleteview class DeletePost(LoginRequiredMixin, generic.DeleteView): model = models.Post success_url = reverse_lazy("blog:all") def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id=self.request.user.id) def delete(self, *args, **kwargs): messages.success(self.request, "Post Deleted") return super().delete(*args, **kwargs) models.py file User = get_user_model() class Post(models.Model): user=models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) title = models.CharField(max_length=150, default=('New Post')) created_at = models.DateTimeField(auto_now=True) message = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:all') class Meta(): ordering = ['-created_at'] unique_together = ('user','message') {% extends "blog/blog_base.html" %} {% block post_content %} <h3>Are you sure you want to delete this post?</h3> {% include "blog/_blog_detail.html" with post=object hide_delete=True %} <form method="POST"> {% csrf_token %} <input type="submit" value="Confirm Delete"> <a href="{% url 'blog:single' username=user.username pk=object.pk %}">Cancel</a> </form> {% endblock %}