Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
One-to-many relationship in django - how to force the parent to have at least one child
I have two models, artwork thats store information about an art piece and media who store information about the media atached to the art piece, in summary an artwork can have one(not zero) or many medias and a media only can belong to an artwork. My problem is that I can do that django force artwork to have at least one media before to be created and I'm not sure about how to work around this, maybe changing the manager? Thank you in advance -
I am getting a fie not found error while trying to call my php script inside of django view via subprocess?
I am trying to call a Php script from my Django view inside the post method, I am using subprocess for this and I am inputting the correct path but it's giving me the File Not Found Error. Here's what I tired subprocess.call(["php", "D:\\projects\\python\\salesproject\\static\\js\\form_submit.php"]) subprocess.call("php D:\\projects\\python\\salesproject\\static\\js\\form_submit.php") -
DRF JWT Authentication object has no attribute 'id'
I'm using a library suggested by DRF (djangorestframework_simplejwt), installed using pip install djangorestframework_simplejwt Added it to settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } Created two endpoints from imported views from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ # JWT Token path('api/token/', TokenObtainPairView.as_view(), name='token_obtain'), # get a new token before the old expires. path('api/token/refresh/', TokenRefreshView.as_view, name='token_refresh'), ] The users are being created without any problem in the database and the passwords are being hashed. If i go to http://localhost:8000/api/token/, then get the following view Posting the correct user with its password and then I get the following error [17/Apr/2020 12:06:51] "POST /api/token/ HTTP/1.1" 500 122221 Internal Server Error: /api/token/ Traceback (most recent call last): File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File … -
Override actions defined in parent class Django admin
I am upgrading a Django project from Django 1.11. I have successfully upgraded the project upto Django 2.1. When I upgraded to Django 2.2, I got this error message "(admin.E130) name attributes of actions defined in class AdimClass(not real name) must be unique" The admins classes are class AAdmin(admin.ModelAdmin) def custom_action(self, request, queryset): # perform custom action ..... def custom_action_2(self, request, queryset): # another custom actions ..... action = [custom_action, custom_action_2] class BAdmin(AAdmin): def custom_action(self, request, queyrset): # performs different actions but has the same name as AAdmin action ..... actions = AAdmin.actions + [custom_action] problem: (admin.E130) name attributes of actions defined in class AdimClass(not real name) must be unique If I remove the custom_action from AAdmin, the error is resolved but the action is no more available for other classes which inherits AAdmin. Goal: keep the action in parent class AAdmin and override it on child class BAdmin. Note: The code is working fine upto Django 2.1. -
How to temporarily disable Django indexes (for SQLite)
I'm trying to create a large SQLite database from around 500 smaller databases (each 50-200MB) to put into Django, and would like to speed up this process. I'm doing this via a custom command. This answer helped me a lot, in reducing the speed to around a minute each in processing a smaller database. However it's still quite a long time. The one thing I haven't done in that answer is to disable database indexing in Django and re-create them. I think this matters for me as my database has few tables with many rows. Is there a way to do that in Django when it's running live? If not in Django then perhaps there's some SQLite query to remove all the indexes and re-create them after I insert my records? -
How to order foreign key objects returned in a Queryset in the same order of their relationship with related object using django-orm
I want to know of a way to achieve this for a very simple case. I have Room object with Facilities as it's foreign key. Suppose related mapping for Rooms is R1->F4, R2->F1, R3->F2, R4->F3 querying database on filtering Room object returns < R1, R2, R3, R4 > So, I want to know how to query database by filtering Facilities object to return < F4, F1, F2, F3 > -
How to provide token key, while accessing webpage in browser
i am developing web app using django_restframework with token authentication. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( #'rest_framework.authentication.BasicAuthentication', #'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', )} token will be generated when user done registration in registration page. Next i want user to login, here i have provide permission_class=[AllowAny.] Next is home page, here i provide permission_class = [IsAuthenticated,] while accessing home page, it shows in browser HTTP 401 Unauthorized Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Token { "detail": "Authentication credentials were not provided." } i can see token was there in database.in postman,i have provided token key in header,so got the output.but while using browser i really dont know how to achieve this.please help me to solve this issue.... -
ValueError: invalid literal for int() with base 10: on Django
I later added a new ForeignKey field to the model. But I encountered such an error. Although I delete this field and delete the database and migrate again, I keep getting this error. models.py / gayrimenkul class Post(models.Model): seller = models.ForeignKey('user.User',max_length=120,blank=False,null=False,verbose_name="İlan Sahibi",on_delete=models.CASCADE,default="admin") title = models.CharField(max_length=120,blank=False,verbose_name="Başlık",help_text="Başlık Giriniz.") slug = models.SlugField(max_length=122,default='',unique=True,null=False,verbose_name='Slug Alanı',editable=False) price = models.FloatField(blank=False,verbose_name="Fiyat") content = RichTextField(verbose_name="Detay") img = models.ImageField(blank=True,verbose_name='Post Resim',default='',upload_to=upload_to) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) The linked model in the ForeignKey field is 'user.User' because I created my own user model. C:\Users\adilc\Desktop\Gayrimenkul\Gmn>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, gayrimenkul, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying gayrimenkul.0001_initial... OK Applying gayrimenkul.0002_post_seller...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\adilc\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\adilc\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\adilc\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\adilc\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\adilc\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\adilc\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\commands\migrate.py", … -
How to Serve a React App with Django on Elastic Beanstalk?
I used to have my app on Heroku and the way it worked there was that I had 2 buildpacks. One for NodeJS and one for Python. Heroku ran npm run build and then Django served the files from the build folder. I use Code Pipeline on AWS to deploy a new version of my app every time there is a new push on my GitHub repository. Since I couldn't figure out how to run npm run build in a python environment in EB, I had a workaround. I ran npm run build and pushed it to my repository (removed the build folder from .gitignore) and then Django served the files on EB. However, this is not the best solution and I was wondering if anyone knows how to run npm run build the way Heroku can do it with their NodeJS buildpack for a python app on EB. -
Can't get an object deletion - ?csrfmiddlewaretoken= appears at the end of the current URL in the urlbar (django)
I am building a simple social network in django. In the "home" of my social, I have the list of all posts published by all users, with author and publishing date. Under each post of the logged user, a "delete" button appears. If the user clicks on it, it returns a specific view of that post, with a message "do you really wish to delete this post?" and two buttons to confirm or cancel the post deletion. However, as I click on button "confirm deletion", the page reloads to the same point, and nothing changes except for the fact that ?csrfmiddlewaretoken=--random-sequence-- appears at the end of the current url in the urlbar. What am I missing? Here is my template: <h3>Do you want to delete this post?</h3> <div class="posts"> {% include "posts/_post.html" with post=object hide_delete=True %} </div> <form class="POST"> {% csrf_token %} <input type="submit" value="Confirm Delete" class="btn btn-danger btn-large"> <a href="{% url 'posts:delete' pk=post.pk %}" class="btn btn-simple btn-large btn-default">Cancel</a> </form> and my DeletePost view based on generic.DeleteView: class DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView): model = models.Post select_related = ('user', 'group') success_url = reverse_lazy('posts: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) -
Django Deployment - Stuck with own app installation
New to Django. I can't resolve deployment problem in the Advanced Tutorial: How to write reusable apps: https://docs.djangoproject.com/en/3.0/intro/reusable-apps/ Python version 3.8|Django version 3.0.4|setuptools version 40.8.0|IDE - Pycharm Until point where i need to install own package, everything is fine. I attempt to install my package: (venv) C:\Users\juras\PycharmProjects\django tutorial\mysite> python -m pip install --user django- polls/dist/django-polls-0.1.tar.gz Processing c:\users\juras\pycharmprojects\django tutorial\mysite\django-polls\dist\django-polls- 0.1.tar.gz Installing collected packages: django-polls Running setup.py install for django-polls ... done Successfully installed django-polls-0.1 But it seems, app was not installed, as i cant find that module, what is more, when im trying to uninstall app as per documentation: (venv) C:\Users\juras\PycharmProjects\django tutorial\mysite>python -m pip uninstall django-polls Skipping django-polls as it is not installed. Folder django-polls contains: - LICENSE without any extension - MANIFEST.in - README.rst - README.rst - setup.cfg - setup.py Every file created as text with changed extension, if this matter anything at all.. Folowing other threads related to similar problem, i checked Installed apps: INSTALLED_APPS = [ # 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ] Also urls are exact as per information from README file. urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] Here is an error when im trying to migrate: ModuleNotFoundError: No module named 'polls' … -
How to create a number of dictionaries based on a given number in python?
I have an HTML page that handles several forms. When making a post request (i.e. submitting the values of the fields of the different forms) i received in django/python this dictionary: form-0-Name:Dupont form-0-Town:Paris form-1-Name:Macron form-1-Town:Marseille From this dictionary, how to create a number of dictionaries based on the number of forms that i receive? In this example, i would like to create two dictionaries named (form_0 and form_1) such that form_0: {Name: Dupont,Town:Paris} and form_1:{Name: Macron, Town:Marseille}. -
Uploading and uploaded file without saving
I have a web server that acts as a proxy between users and a file server. Users can upload their files to my web server and I upload them to the file server. I want to be able to do this without saving the temp uploaded file but every time I get unexpected end of file error from the file server. This is my code (I'm using django rest framework for my APIs). headers = {"content-type":"multipart/form; boundary={}".format(uuid.uuid4().hex)} files = [] for f in requests.FILES.getlist('file'): files.append((f.name, open(f.file.name,'rb'), f.content_type)) files_dict = {'file': files} r = requests.post(url, files=files, headers=headers) -
I am able to upload any file to my server while using image2 in django ckeditor. how to restrict it?
snapshot of write.php uploaded/selected I am unable to find any solution to this problem. -
Is there a way to not save an object but the fields in Django?
I created a new UserProfile model. Code below: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver import logging logger = logging.getLogger(__name__) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=1) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.userprofile.save() This code is getting triggered by the signal and working but it saves a UserProfile object, not the individual fields (image attached). What am I doing wrong? Do I need to write a custom Manager? Or do I need to override the save() method somehow? Thanks in advance -
Django Choices Not Being DIsplayed
Good day, I am trying to create a django model that contains a choice whether the user has read or not read a book. For that I have made a choice list. But i am unable to display it on the admin panel. All other fields are getting displayed other than the choice field. Can you please tell me where I am going wrong. I am new to django and have referred from the documnetation. Following is the code: class Book(models.Model): YES = 'y' NO = 'n' DID_READ_CHOICES = [ (YES,'Yes'), (NO,'No'), ] title = models.CharField(max_length=100) author = models.ForeignKey( Author, on_delete=models.SET_NULL, null=True, related_name='author_books' ) genre = models.ManyToManyField(Genre, help_text='Select a genre for this book') summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book',blank=True,null=True) read = models.CharField( max_length=1, choices=DID_READ_CHOICES, default=NO, ), objects = BookManager() class Meta: ordering = ['title'] def __str__(self): return self.title Thank you -
How to change part of the form inside the template by ajax
i have a small problem it is in Classified-Ads site by django when i make ads there are main form for title, descriptions, img , categorys and there are some special form for exmple:if the user choice cars categorys i wont to show some special form like Kilometers , Color , Body Type , Engine Capacity (CC) but if he choise mopile phone there are different forms will be showing like model , processor , ram I hope I can communicate the idea my solution is : make some special forms class like this forms.py class carf(forms.ModelForm): class Meta: model = catugry fields = ['name', 'main' ] class mobilef(forms.ModelForm): class Meta: model = catugry fields = ['name','sub', 'end' ] and in template make ajax code to send Id of choosing category <script> $("#id_main").change(function () { var url3= ("{% url 'ads:ff'%}") // get the url of the `load_cities` view var mainff = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url3, // set the url of the request (= localhost:8000/hr/ajax/load-cities/) data: { 'mainff': mainff, }, success: function (data2) { // `data` is the return of the `load_cities` view function $("#fff").html(data2); console.log(data2); … -
I can't seem to use the DateTimeField in django without errors
My django blog app has the parameters, title, pub-date, body and image. when i create a blog model on the admin page i get an error. here's what the code looks like. ProgrammingError at /admin/blog/blog/add/ column "pub_date" is of type integer but expression is of type timestamp with time zone LINE 1: ..._date", "image", "body") VALUES ('My first blog', '2020-04-0... ^ HINT: You will need to rewrite or cast the expression. Here is the model i created: ''' from django.db import models class Blog(models.Model): title = models.CharField(max_length=250) pub_date = models.DateTimeField() image = models.ImageField(upload_to='images/') body = models.TextField() ''' -
Django App deployed to Heroku - psycopg2.errors.NotNullViolation as data is not passed through Ajax
I have successfully deployed my app to Heroku but one feature is not working properly, although it's working good on my local env. From Heroku logs i can see the following: 2020-04-17T09:50:34.538062+00:00 app[web.1]: Internal Server Error: /shop/add_to_cart/11/ 2020-04-17T09:50:34.538078+00:00 app[web.1]: Traceback (most recent call last): 2020-04-17T09:50:34.538079+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute 2020-04-17T09:50:34.538079+00:00 app[web.1]: return self.cursor.execute(sql, params) 2020-04-17T09:50:34.538080+00:00 app[web.1]: psycopg2.errors.NotNullViolation: null value in column "quantity" violates not-null constraint 2020-04-17T09:50:34.538081+00:00 app[web.1]: DETAIL: Failing row contains (23, null, null, 23, 11). The mentioned quantity is passed through ajax: $('.add-product-to-cart').on('click', function (e) { e.preventDefault(); let product_id = $(this).attr('data-product-id'); let quantity = $('#input-product' + product_id).val(); let csrftoken = $('input[name=csrfmiddlewaretoken]').val(); $.ajax({ url: 'add_to_cart/' + product_id + '/', type: 'POST', data: { 'product_id': product_id, 'qty': quantity, 'csrfmiddlewaretoken': csrftoken, }, success: function (data) { alert("Produkt dodany"); } }); }); Again this code works on local. The html bit that ajax refers to, is as per below: <div class="bottom-area d-flex px-1"> <div class="m-auto w-100"> <form method="POST" action="{% url 'shop:add_to_cart' product.id %}" class="d-flex align-items-center justify-content-center" id="add-product-to-cart-form"> {% csrf_token %} <div class="d-flex align-items-center justify-content-start pr-2"> <input type="number" name="qty" id="input-product{{ product.id }}" class="quantity input-number py-0" value="{{ product.min_qty_value }}" min="{{ product.min_qty_value }}" max="500" step="{{ product.min_qty_value }}" style="padding: 0 0 0 10px; border-radius: … -
Unable to serve django static files using uwsgi to the nginx
I'm using uwsgi as the server and nginx as the reverse proxy for running the django project. Project structure is as follows(here i have listed only required folder/files): war ├── katana │ ├── wapps │ │ ├── app1 │ │ └── app2 │ └── wui │ ├── settings.py │ └── wsgi.py └── static ├── css │ └── test.css ├── img │ └── test.img └── js └── test.js The static configuration in settings.py is as follows: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] DATA_UPLOAD_MAX_MEMORY_SIZE = 10242880 STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') The wsgi.py is as follows: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "katana.wui.settings") application = get_wsgi_application() The uwsgi is server is started using: uwsgi -b 65535 --socket :4000 --workers 100 --cpu-affinity 1 --module katana.wui.wsgi --py-autoreload 1 The nginx conf is as follows: events { worker_connections 1024; ## Default: 1024 } http { include conf/mime.types; # the upstream component nginx needs to connect to upstream uwsgi { server backend:4000; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8443 ssl http2 default_server; # the domain name it will serve for server_name … -
How to make channel client in views.py?
I am making a chatbot in views.py will receive an HTTP request by the user and views.py interacts with the bot and return to the user. I am using channels to communicate between views.py and chatbot API. following is the views code and channel consumer code. #views.py @api_view(['POST']) def conv(request): ws = create_connection(url) ws.send({"message":request.data["msg"]}) rec = ws.recv() return {"msg" : rec} #consumers.py class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) After receiving from the channel the connection disconnects and I am unable to maintain chat session on the consumer end. -
testing stripe on boarding view django
i am trying to test the view pasted below. However i can't figure out how i would go about doing this. I can get so far as mocking the get request, but how can i grab the values from the view to test them against values they should be. Here is the view : class StripeAuthorizeView(LoginRequiredMixin, View): def get(self, request): url = 'https://connect.stripe.com/express/oauth/authorize?' user = self.request.user if user.account_type == 'Business': business_type = 'company' else: business_type = 'individual' params = { 'response_type': 'code', 'scope': 'read_write', 'client_id': settings.STRIPE_CONNECT_CLIENT_ID, 'redirect_uri': f'http://127.0.0.1:8000/accounts/stripe/oauth/callback', 'stripe_user[email]' : user.email, 'stripe_user[business_type]' : business_type, 'stripe_user[url]' : 'http://127.0.0.1:8000/accounts/user/%s/' %user.pk, } url = f'{url}?{urllib.parse.urlencode(params)}' return redirect(url) I need to be able to test that the url is the correct url, the view is sending the correct client id and pre filling in the correct fields, eg user.email etc. The scary thing is if i can't write some tests for it, if someone was to accidentally change them it will cripple my platform. Really need to be testing that the view is getting passed the correct data to the stripe api. Any help will really be helped. -
allow html file to be shown in iframe django
I am working on this Django project and I am trying to show the html file 'addition.html' in an iframe on 'main.html'. If I understand things correctly, I have to specify frame-ancestors options in my CSP options (as e.g. explained here). However, I do not fully understand: Which file can the CSP be specified? What line of code is needed in order to allow my main page to show the addition in the frame. Any help is much appreciated. -
Can't get the DeleteView of a post in a social network project
I am building a simple social network in django. In the "home" of my social, I have the list of all posts published by all users, with author and publishing date. Under each post of the logged user, a "delete" button appears. If the user clicks on it, it should return a specific view of that post, with a message like "do you really wish to delete this post?" However, as I click on it, the code returns this error: NoReverseMatch at /posts/delete/7/ Reverse for 'single' with no arguments not found. 1 pattern(s) tried: ['posts/by/(?P[-\w]+)/(?P\d+)/$'] Why does it says that it cannot get the reverse for 'single' with no arguments, while in the template the delete button has a link to 'delete' view function? Here is my urls.py, inside urlpatterns: url(r'by/(?P<username>[-\w]+)/(?P<pk>\d+)/$', views.PostDetail.as_view(), name='single'), url(r'delete/(?P<pk>\d+)/$', views.DeletePost.as_view(), name='delete'), Here is my views.py: class DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView): model = models.Post select_related = ('user', 'group') success_url = reverse_lazy('posts: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) Here is my piece of template showing the post and asking the user if he/she really wants to delete it: {% if user.is_authenticated and post.user.username == user.username %} <a href="{% url … -
ProgrammingError at /admin/group_manager/automaticgroup/
I have encountered this problem on my django admin page, I really don't understand what is happening but I'm unable to view my table content on the admin page in the django server and it is returning errors. I succeeded in doing migrations, I wonder if it did migrations well but then they confirmed that no new migrations was detected. So, this is what happens, after running: python manage.py runserver It returns this: Starting development server at http://127.0.0.1:8000/ and when I click on it and go to the admin section "http://127.0.0.1:8000/admin" and click on my newly created table, it returns this error page. Please could someone help me :-( This is a screenshot of my error message Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/group_manager/automaticgroup/ Django Version: 2.2 Python Version: 3.6.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'profile_manager.apps.ProfileManagerConfig', 'group_manager.apps.GroupManagerConfig', 'trip_manager.apps.TripManagerConfig', 'relationship_manager.apps.RelationshipManagerConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',`enter code here` 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\Glory\Desktop\django\opentravels\venv\lib\site-packages\django\db\backends\utils.py" in _execute 84. return self.cursor.execute(sql, params) File "C:\Users\Glory\Desktop\django\opentravels\venv\lib\site-packages\django\db\backends\mysql\base.py" in execute 71. return self.cursor.execute(query, args) File "C:\Users\Glory\Desktop\django\opentravels\venv\lib\site-packages\MySQLdb\cursors.py" in execute 209. res = self._query(query) File "C:\Users\Glory\Desktop\django\opentravels\venv\lib\site-packages\MySQLdb\cursors.py" in _query 315. db.query(q) File "C:\Users\Glory\Desktop\django\opentravels\venv\lib\site-packages\MySQLdb\connections.py" in query 239. _mysql.connection.query(self, query) The above exception ((1146, "Table 'opentravels.group_manager_automaticgroup' doesn't exist")) …