Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Foreign Key in Model causing IntegrityError NOT NULL constraint failed:
I have a model where a user posts a job vacancy, then other users can submit applications. The submit application model is called CandidatesSubmission & pulls the 'title' from a different app/model. I not sure what I'm doing wrong in this line: title = models.ForeignKey('jobs.JobsPost', on_delete=models.CASCADE) but it causes "IntegrityError NOT NULL constraint failed: candidates_candidatessubmission.title_id." I have tried adding null=True, blank=False but which stops the error but the title isn't saved to the database. Any suggestions on what I'm doing wrong would be great. Thank you class CandidatesSubmission(models.Model): title = models.ForeignKey('jobs.JobsPost', on_delete=models.CASCADE) Fee = models.CharField(max_length=50, null=False, blank=False) CandidateFirstName = models.CharField(max_length=50, null=True, blank=False) CandidateSecondName = models.CharField(max_length=50, null=True, blank=False) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
How track track field type in change log of a database Row
I have been working on Django and I wanted to track the changes of a table and I am thinking of a table to keep track of the changes on a field-based tracking system like audit_field (table_name, id, field_name, field_value, status, datetime) with the status column ready to track if this change has been approved or not and is visible on the model. but I wanted to keep track of the field types too to use database validation against it. FYI I am working on Django and Mysql database -
How to access media through URL after uploading
I am trying to make a blog application, where every post has a featured image. When I upload the image from admin dashboard, I can see the image in my folder. But, when i try to access the url of the image or show the image from source, it's showing nothing. Here is my code: models.py class Post(models.Model): PRIVACY=( ('0', 'Public'), ('1', 'Private') ) title = models.CharField(max_length=250) image = models.ImageField(upload_to="gallery/") description = models.TextField() status = models.CharField(max_length=8, choices=PRIVACY, default='0') tags = TaggableManager() published = models.DateField(auto_now_add=True) slug = models.SlugField(max_length=58,blank=True,) def save(self, *args, **kwargs): slug_save(self) # call slug_save, listed below super(Post, self).save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('src:post_detail',args=[self.slug]) def get_image(self): return self.image.url views.py def home(request): posts = Post.objects.order_by('-published') template = 'home.html' context = {'posts': posts} return render(request, template, context) def post_detail(request,post): post = get_object_or_404(Post, slug=post) return render(request,'detail.html',{'post': post}) urls.py app_name = 'src' urlpatterns = [ path('', views.home, name='home'), path('<slug:post>/',views.post_detail,name='post_detail'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) else: urlpatterns += staticfiles_urlpatterns() **home.html {% extends 'base.html' %} {% block content %} {% for post in posts %} <section class="post"> <h3><a class="post-title" href="{{post.get_absolute_url}}"> {{ post.title }} </a></h3> <span class="post-meta"> {{ post.published }} <a href="{{post.get_image}}"> <img src="{{ post.image.url }}" /></a> </span> <p class="post-excerpt"> {{ … -
Django Rest - Show Item base on User login
I want implement simple role Admin and User. Admin can see every user's item and user can see their only item. My Viewset class IncidentViewset(viewsets.ModelViewSet): queryset = Incident.objects.all() serializer_class = IncidentSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = IncidentFilter def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) if 'page' in request.query_params: page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) In laravel this can be done by auth()->user()->id = user_id, but dont know in Django. Thanks in advance... -
Django Custom User Model Optional Field and Integer Field with Specific Format
fellow devs! I am writing a custom user model in Django but I can't figure out how can I make a user input middle name for those who have it or won't force it for those who don't. This code works but I have to type a space to bypass the middle name field, which isn't the ideal behavior I want. Also, I want to know if it's possible to set a custom primary key to the field id_number. from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, username, firstname, lastname, middlename, id_number, password=None, active=True, staff=False, admin=False): if not email: raise ValueError('User must have a valid Email Address!') if not username: raise ValueError('User must have Username!') if not password: raise ValueError('User must set Password!') if not firstname: raise ValueError('User must have First Name!') if not lastname: raise ValueError('User must have Last Name!') if not id_number: raise ValueError('User must have a valid ID number!') user = self.model( email=self.normalize_email(email), username=username.lower(), firstname=firstname.capitalize(), lastname=lastname.capitalize(), middlename=middlename.capitalize(), id_number=id_number ) user.set_password(password) user.staff = staff user.admin = admin user.active = active user.save(using=self.db) return user def create_staffuser(self, email, username, firstname, lastname, middlename, id_number, password=None): user = self.create_user( email, username=username, lastname=lastname, firstname=firstname, middlename=middlename, id_number=id_number, password=password, staff=True ) return user … -
How do I return to the comments section after deleting an individual comment in django?
I am trying to delete an individual comment from my comments page and then simply remain on the same page. My delete view is fired from a modal within a for loop like this: {% for comment in comments %} {% if comment.author == user %} <button type="button" data-toggle="modal" data-target="#comment-delete{{comment.id}}" class="btn btn-danger">Delete</button> <div class="modal fade" id="comment-delete{{comment.id}}" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times</button> <h3 class="modal-title">Do you really want to delete?</h3> <div class="modal-body"><p>{{ comment.content }}</p></div> <div class="modal-footer"> <form action="{% url 'comment_delete' comment.id %}" method="post"> {% csrf_token %} <button type="submit" class="btn btn-outline-danger">Yes, Delete</button> <button type="button" data-dismiss="modal" class="btn btn-secondary btn-outline">Cancel</button> </form> </div> </div> </div> </div> </div> </div> {% endif %} {% endfor %} Here is my Comment model: class Comment(models.Model): content = models.TextField(max_length=150) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post_connected = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.content[:5] My relevant urls: urlpatterns = [ path('post/<int:pk>/comments/', PostDetailView.as_view(), name='post_detail'), path('post/<int:pk>/', CommentDeleteView.as_view(), name='comment_delete'), And this is my deleteview: class CommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment # success_url = '/' # def get_success_url(self): # return reverse('post_detail', kwargs={'pk': Post.pk}) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False As you can see I have tried to use the get_success_url method … -
Django projects with Postgres stopped working after brew install
I was trying to get Selenium to work, and so followed the suggestion here to brew install geckodriver in the relevant virtual environment (pipenv). After having done that, my other virtual environments stopped working. I was able to get most of them to work again by re-installing pipenv outside of any virtual environment (using pip3 install pipenv). But all of my Django projects that rely on Postgres still don't work: I'm able to start their virtual environment (with pipenv shell), but python manage.py runserver gives me the following traceback: Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", … -
AttributeError: 'tuple' object has no attribute 'encode' (django contact form)
I am creating a Contact page for my django project. forms.py has name, subject, sender and message. Here's the view: def contact(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] sender_email = form.cleaned_data['sender_email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] send_mail(subject, message, sender_email, ['***@gmail.com']) return render(request, 'contact_us.html', {'form': form}) The template: <h1>Contact Us</h1> <form method="POST"> {%csrf_token%} {{form.as_p}} <div class="form-actions"> <button type="submit">Send</button> </div> </form> After I click Send I get this error: AttributeError: 'tuple' object has no attribute 'encode' and I can't seem to figure out what's wrong despite checking other questions of the same type the last couple of days. I have followed instructions from link 1 and link 2 to set up the SMTP server (2 different cases) and it gives me the same error. How can I fix that? Thank you! -
angular 9 production files fail in django. Error 404
well, I worked in a little project and everything was fine, when I made a build files everything is wrong. {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Frontend</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="{% static 'styles.1165db34b7e7158143e4.css' %}"></head> <body> <app-root></app-root> <script src="{% static 'runtime-es2015.40ead21e007fa8741f0a.js' %}" type="module"></script> <script src="{% static 'runtime-es5.40ead21e007fa8741f0a.js' %}" nomodule defer></script> <script src="{% static 'polyfills-es5.86f7ad57e8b901d60e04.js' %}" nomodule defer></script> <script src="{% static 'polyfills-es2015.ae2ff135b6a0a9cb55e7.js' %}" type="module"></script> <script src="{% static 'main-es2015.f1b8c0450fffd3db5039.js' %}" type="module"></script> <script src="{% static 'main-es5.f1b8c0450fffd3db5039.js' %}" nomodule defer></script></body> </html> this is my routes.py urlpatterns = [ path('admin/', admin.site.urls), path('login/', include('apps.index.urls')), path('api/v1.0/', include('apps.abogado.api.urls')), path('api/v1.0/', include('apps.despacho.api.urls')), path('api/v1.0/', include('apps.proceso.api.urls')), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In angular this is my login <div class="login-div"> <div class="image-div"> <img [src]="'/assets/logo.svg'"> </div> <form action="" class="formulario"> <div class="fields"> <div class="username"><input type="text" class="user-input" name="username" placeholder="usuario" [(ngModel)]="user.username"></div> <div class="password"> <input type="password" class="pass-input" name="password" placeholder="contraseña" [(ngModel)]="user.password"></div> </div> <button type="submit" class='signin-button' (click)="login()" >Login</button> </form> with this code the user is redirect to dashboard login(user:object) { return this.http.post('http://127.0.0.1:8000/api/token/', JSON.stringify(user), this.httpOptions).subscribe( res => { this.almacenarCredenciales(res, user); this.router.navigateByUrl('dashboard/proceso/todas-notificaciones') } ); } after make the login, the user is redirect to dashboard, there is where happens … -
Share variables to included templates in django
In views.py the thing object is being passed to index.html. def index(request): return render(request, "myapp/index.html", { 'things': Thing.objects.all() }) index.html is setup like this: {% block body %} {% for thing in things %} {{ thing.attribute }} <button type="button" class="btn" data-toggle="modal" data-target="#exampleModal"></button> {% endfor %} {% endblock %} I would like to separate the html that renders the modal referred to by the button into another html file to keep things organized. I was able to do this by referencing the modal html file with include as shown below: {% block modal_code %} {% include 'myapp/modal_code.html' %} {% endblock %} But I could not figure out how to share the things object with the model code so the modal could dynamically display the object's content. Is there a way to do this? -
Pass values from url to django model?
I want to take a value from my url using POST, pass that variable to my model and save in my database. Can anyone help? -
how to make a database connection PAGE/FORM in django
please help I'm so lost on this. Everything i search on this just tries to explain how to connect django to a database. which is not the goal. The goal is: I'm trying to make a form where users can insert their database credentials and connect. Don't leave yet! I already have it working - but I don't know how to link the users responses to the script that connects to the database. Here's my form and some of the code (it's django so code is everywhere): The db html page: {% extends 'base.html' %} {% block content %} <h1>New DB Connection</h1> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input class="btn btn-info ml-2" type="button" value="Cancel" onclick="history.back()"> <button class="btn btn-info ml-2" onclick="location.href='{% url 'output_script' %}'">Connect!</button> <hr> {% if df %} {{ df }} {% endif %} </form> {% endblock content %} The views.py file: Here's where it gets hard - How do i link the inputs in the DBCreateView class and assign them to the variables in the output function?! Sorry if this seems easy, but it's beyond me. class DbCreateView(CreateView): # if request.POST: # form = model = db template_name = 'db_new.html' fields = ('USERNAME','PASSWORD','ACCOUNT','WAREHOUSE','DATABASE', 'SCHEMA', 'ROLE') … -
Django user authentication does not work, how can I fix my login?
I am using the django-email-verification app and I had to change how a User is signed up but I left the login authentication part the same. Every time I try to login it does not allow me to sign in and says that the credentials are wrong. Also I used emails as usernames. I'm thinking its the: user = auth.authenticate(username=request.POST['username'], password=request.POST['password']) that needs to be changed. Please how do I fix the login? from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import auth from django.contrib.auth import get_user_model from django_email_verification import sendConfirm def signup(request): if request.method == 'POST': if request.POST['pass1'] == request.POST['pass2']: try: user = User.objects.get(username=request.POST['username']) return render(request, 'accounts/signup.html', {'error': 'Email is already registered'}) except User.DoesNotExist: '''user = User.objects.create_user(request.POST['username'], password=request.POST['pass1']) auth.login(request, user)''' user = get_user_model().objects.create(username=request.POST['username'], password=request.POST['pass1'], email=request.POST['username']) sendConfirm(user) return redirect('home') else: return render(request, 'accounts/signup.html', {'error': 'Passwords must match'}) else: return render(request, 'accounts/signup.html') def login(request): if request.method == 'POST': user = auth.authenticate(username=request.POST['username'], password=request.POST['password']) if user is not None: auth.login(request, user) return redirect('home') else: return render(request, 'accounts/login.html',{'error':'username or password is incorrect.'}) else: return render(request, 'accounts/login.html') def logout(request): if request.method == 'POST': auth.logout(request) return redirect('home') -
Syntax Error in django migrate with SQL Server
I have an error in python manage.py migrate in all models with ForeignKey fields. django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Sintaxis incorrecta cerca de '.'. (102) (SQLExecDirectW)") The table is created and the index is created too, but in the add constraint statement for the foreign key the error is shown. The model. class Book(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey('Author', related_name='books', on_delete=models.PROTECT) name = models.CharField(max_length=20) class Meta: db_table = u'Library].[Book' # this line sets the schema for the table in MSSQL DB the sqlmigrate output: python manage.py sqlmigrate catalogos 0018_prueba -- -- Create model Prueba -- CREATE TABLE [Library].[Book] ([id] int IDENTITY (1, 1) NOT NULL PRIMARY KEY, [name] nvarchar(20) NOT NULL, [author_id] int NOT NULL); CREATE INDEX [Library].[Book_author_id_66e91062] ON [Library].[Book] ([author_id]); ALTER TABLE [Library].[Book] ADD CONSTRAINT [Library].[Library_author_id_66e91062_fk_Library].[Author_id] FOREIGN KEY ([author_id]) REFERENCES [Library].[Author] ([id]); # this raises error when is executed in sql server the last line adds the foreign key but it raises the error, the table is created succesfully, the index is created too and in the django_migrations table, the migration is applied but the foreign key does not exists. How can i avoid this error?, This happens in all my models with foreign … -
Django cron vs Django celery vs Django schedule
I am currently looking into implementing this specific task: once a scheduled message reached its supposedly-sent date, the system will then automatically send the message (convert from saved drafts status to sent). After some very light research, seems like there are many ways to do this but which technology is the best for my situation? Django cron, celery, or schedule (https://schedule.readthedocs.io/en/stable/)? What are the pros and cons of each? Thank you! -
HTTP Requests between Pi and existing Full Stack Web Application
I would like to send API data via https requests between Raspberry Pi GPIO and my Existing Django Backend in order to store on my existing database(django/sqlite). It's for a portable IOT device. What is the best method to achieve this? Do I still require the flask server on the Pi? If so, will I be required to deploy my Rasp Pi Flask Server onto the web? I look forward to hearing from someone. This is the missing piece in the puzzle, so your help will be much appreciated! Thank you! -
Access kwargs in Django Forms
With reference to the picture above, I am trying to access the kwargs pk in the forms.py. In the views.py kwargs pk is not empty and has a value of 57. My problem is, how to access this pk in forms.py. When poping the 'pk' it returns an error. I have written some code here but cannot retrieve pk kwargs. Here is mi code in the form.py: project_id = kwargs.pop('pk') #THIS RETURNS AN ERROR super(ModelCreateForm, self).__init__(*args, **kwargs) project = Project.objects.get(id=project_id) In my views.p I have: kwargs = super(ModelCreateView, self).get_form_kwargs() pk = self.request.GET['pk'] kwargs['pk']=pk return kwargs -
How to insert multi rows in django
I need your help to insert multi rows in Django I've a form: start from,end to,number of_book,branch,active date,active for example: start from=101 end to=125 start from=126 end to=150 start from=151 end to=175 start from=176 end to=200 and the other inputs is static My Form -
django importing problems but everything is working properly
i'm using django 3.1 and i have python3 and in my file when i import something saying from lorem import ipsum it says no name 'ipsum' in module lorem for example: from django.conf.urls import url from django.contrib import admin from django.urls import path , include there is says: No name 'path' in module 'django.urls' No name 'include'in module 'django.urls' -
How do I make a ForeignKey field use Multiple Dropdowns from the same list, and remove duplicates as they are selected, in Django?
I am trying to set up a Django project that will reference a list of users. In one of my models, I am using ForeignKey fields to point at the table of users. I have several slots setup, linked to the table of users, and I would like to be able to select a user from that table when adding data. But I would also like the users name to be removed from the rest of the dropdowns if they are selected in one of the dropdowns. For Example. I have 3 users in my table. John, Mark, Andy In the entry page, I would like to have 3 dropdown fields. Each of them linked to the users table. In the first field when I click it, all three users should pop up as options, John, Mark and Andy. After selecting John, the second field should only give me the option to select Mark or Andy. After selecting Mark for the second field, the third field should give the option to select Andy, or stay blank. My models.py is setup like this: class Users(models.Model): name = models.CharField(max_length=15) class Session(models.Model): Slot1 = models.ForeignKey(Users, on_delete=models.CASCADE, related_name='Slot1') Slot2 = models.ForeignKey(Users, on_delete=models.CASCADE, related_name='Slot2') Slot3 … -
Yahoo social login not working django-allauth
I'm trying to implement Yahoo Social Login, using django-allauth, I've so far been able to successfully do this with google, and I believe also with Facebook and Amazon, however, those require HTTPS to work, and my localhost server is using HTTP, so I'll only find out once I host it online, if anyone could help me test on localhost, that would be great also, but the main issue is that when I sign in to Yahoo, I get an error message on the yahoo page saying Uh-oh! Looks as if something went wrong. Please try again later. Then underneath it says Developers: Please specify a valid request and submit again. Having searched on the web, I have reason to believe that is because of yahoo getting an invalid URL request, here is a link to That question Here is the link that I have in the URL bar when I try to sign in https://api.login.yahoo.com/oauth2/request_auth_fe?client_id=dj0yJmk9OWE0Y1JZQ2NMZ3dOJmQ9WVdrOVIyNVdRMHhWWVVnbWNHbzlNQT09JnM9Y29uc3VtZXJzZWNyZXQmc3Y9MCZ4PWM5&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Faccounts%2Fyahoo%2Flogin%2Fcallback%2F&scope=sdps-r&response_type=code&state=W9uBoxwTCi66 Anyway, even if this is the cause, I do not know how to fix it, and can find no such solution, can somebody help me please, Thank you very much -
how can I send dynamic - static content from django admin?
I am trying to send bulk emails via Django admin (actions) without my send_html_mail takes 2 important arguments subject and html_content, but I want to some kind of input, textarea without saving in the database , and send the html content to all selected emails class EmailThread(threading.Thread): def __init__(self, subject, html_content, recipient_list, sender): self.subject = subject self.recipient_list = recipient_list self.html_content = html_content self.sender = sender threading.Thread.__init__(self) def run(self): msg = EmailMessage(self.subject, self.html_content, self.sender, self.recipient_list) msg.content_subtype = 'html' msg.send() def send_html_mail(subject, html_content, recipient_list, sender): EmailThread(subject, html_content, recipient_list, sender).start() @admin.register(emails) class BULKAdmin(admin.ModelAdmin): actions = ['bulk_mail', ] def bulk_mail(self, request, queryset): recievers = [] for emails in emails.objects.all(): recievers.append(emails.from_email) send_html_mail('demo', 'demo', recievers, settings.EMAIL_HOST_USER) bulk_mail.short_description = 'send bulk newsletter' -
How Do I Use A Nodejs Project In My Python-based Web App
I'm currently building a web app with flask, which is a python-based framework similar to Django. I found this open source software mathsteps that I would like to use in my project. However, the project was built for nodejs and I can't figure out how to use it in my app. From what I've seen, nodejs is a back-end framework that would be an alternative to my flask one. I don't know how I would use a node app with my python one. Can I run the node app within my python one and just request data from the node app when I need it? Could I run the node app in browser? -
Odd behaviour on REST: Update/patch View doesn't allow get method and returns 405 when called via requests
Similar questions have been asked before, but I can't seem to fix my problem with the answers. I am trying to partially update an object and I overwrote the partial_update method in REST's generic UpdateAPIView but when I call this view via requests I get a 405:get method not allowed-response. What is extremely odd is that my code was working for about 2 weeks and now all of the sudden I get this error. I'm banging my head against a wall and can't seem to figure this out. In my view I am doing this: class BuildingUpdateAPI(UpdateAPIView): serializer_class = BuildingSerializer def partial_update(self, request, *args, **kwargs): """Patches building specified in URL with data in request.""" network = Network.objects.get(name=self.kwargs["name_network"]) building = network.buildings.get(name=self.kwargs["name_building"]) serializer = BuildingSerializer(building, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return JsonResponse(status=200, data=serializer.data) msg = ( "Error message" ) return JsonResponse(status=400, data=msg, safe=False) My serializer is simple, it only defines the fields (but I can provide it if it helps). In other answers it is said that REST looks for a get-method and can't find it. But I am calling this not via get, but via patch: ep = "http:localhost:/path/to/update/" data { "update_field": "123" } r = requests.request("patch", url=ep, data=data, headers=get_headers()) Other … -
for in django template doesn't showed up
Hi i have work on a website and use Django for it's Back-End, i use for to show list of users(for example) according to below code: <table id="example" style="width:100%" class="table table-striped table-bordered"> <thead> <tr> <th>Username/Email</th> </tr> </thead> <tbody> {% for user in userslist %} <tr> <td>{{user}}</td> </tr> {% endfor %} </tbody> </table> it runs without any error but nothing showed up in place of tag. Pythons part: def show_users(request): users = User.objects.all() template = loader.get_template('user/users_table.html') users_list = [] for i in range(len(users.all())): users_list.append(users[i].get_username()) print(users_list) return HttpResponse(template.render({"users_list":users_list}, request))