Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add 'delete' support in django rest framework ModleViewSet?
I use django rest framework. models.py class TaskQueue(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField() task_key = models.CharField(max_length=30, unique=True) views.py class TaskQueueView(viewsets.ModelViewSet): queryset = TaskQueue.objects.all() serializer_class = TaskQueueSerializer urls.py router = SimpleRouter() router.register(r'task', views.TaskQueueView) get and post is ok, while do delete: curl -X DELETE -i 'http://127.0.0.1:8000/task/' --data '{"task_key":"1"}' It will show {"detail":"Method \"DELETE\" not allowed."} How to make viewset of django rest framework support delete? Environment: python3.6.4 Django==2.0.7 djangorestframework==3.8.2 -
bitly v4 django python
Am learning bitly to shorten url using python and django, currently using: import requests url ='https://api-ssl.bitly.com/v3/shorten? access_token=*** &longUrl=***' short =requests.get(url) print(short) This works fine. Then I went reading bitly docs. and came across: bitly with python. As the access_token is included in url, so I was thinking of using bitly v4 but couldn't get how to. I just need a simple function to short url, but via v4 -
Django rest_framework custom error message
I have a API endpoint where it will do input validation using rest_framework's serializer.is_valid() where it will return custom error message and response. serializer = FormSerializer(data=data) if not serializer.is_valid(raise_exception=False): return Response({"Failure": "Error"}, status=status.HTTP_400_BAD_REQUEST) Is it possible to populate validation errors without using the generic response provided by raise_exception=True? I am trying to avoid using the generic response as it will display all the validation errors if there are more than one error. The response will be something like return Response( { "Failure": "Error", "Error_list": {"field1": "This field is required"} }, status=status.HTTP_400_BAD_REQUEST ) -
I can't get Ajax data with Django
I do a System Key Verify. I use python to coding . Django is my Framework. I send system key from user input. when it's onblur, I send a ajax to django. $.ajax({ async: false, //false url: $(This).attr('verify-str'), dataType: "JSON", type: "POST", data: { name: $(this).val() }, success: function (data) { } }); Here's my python code if request.is_ajax(): # Get postData key = request.POST.get('name') cur = db.cursor() sql = "select COUNT(*) count from sys_tenants_infomation WHERE tenants_id = %s " try: cur.execute(sql, (key,)) results = cur.fetchall() for row in results: count = row[0] print(count) except Exception as e: raise e finally: connection.close() You can see enter image description here I cant get request.POST.get('name') request.POST.get('name') is NONE And i dont know why -
Google App Engine- Error(libraries entries are only supported by the "python27" runtime)
I developed a web application based on Python 3.6 and Django 2.0 and want to deploy in Google App Engine first time. When I tried to deploy(gcloud app deploy) it, it did not go through with the error message as follows, (acct) C:\Users\tsjee_000\dev\acct\src>gcloud app deploy ERROR: (gcloud.app.deploy) An error occurred while parsing file: [C:\Users\tsjee_000\dev\acct\src\app.yaml] libraries entries are only supported by the "python27" runtime in "C:\Users\tsjee_000\dev\acct\src\app.yaml", line 34, column 13 app.yaml runtime: python api_version: 1 threadsafe: yes env: flex entrypoint: gunicorn -b :$PORT main:app handlers: - url: /static static_dir: static/ - url: .* script: acct.wsgi.application libraries: - name: MySQLdb version: 1.2.5 Does not GAE support Python 3 and Django 2 yet? I looked for the answer and tried in many ways but it did not work. -
Unable to verify token with django-otp
I'm attempting to implement a pretty simple 2fa system in my django project using django-otp. I'd like to use TOTP based devices. However, I cannot get my tokens to ever pass the verify_token method. I'm doing something like this: from django_otp.plugins.otp_totp.models import TOTPDevice my_user = ... # create a totp device object, tied to the user totp_device = TOTPDevice.objects.create(user=my_user) #get the config url qr_config_url = totp_device.config_url # otpauth://totp/my_user?digits=6&secret=LOMCRJND7YFGCB7DOP3R8DX4XMFQKPG5&period=30&algorithm=SHA1 Then, I use the given qr_config_url to generate a QR code, using either renderers in my app, or just freeware around the net. Either produce the same authenticator results in my phone app (which I trust). The problem is, whenever I call token = <token from app> totp_device.verify_token(int(token)) It always returns False. I'm a bit stuck. I'm confident my authenticator app is working well, but the tokens given simply never pass the verification check. -
The view newsletter.views.control_newsletter_edit didn't return an HttpResponse object. It returned None instead
This is my urls.py : from django.urls import path from newsletter.views import control_newsletter, control_newsletter_list, control_newsletter_detail, control_newsletter_edit urlpatterns = [ path('newsletter/', control_newsletter, name='control_newsletter'), path('newsletter_list/', control_newsletter_list, name='control_newsletter_list'), path('newsletter_detail/<int:pk>/', control_newsletter_detail, name='control_newsletter_detail'), path('newsletter_edit/<int:pk>/', control_newsletter_edit, name='control_newsletter_edit'),] and this is my view.py : def control_newsletter_edit(request, pk): newsletter = get_object_or_404(Newsletter, pk=pk) if request.method == 'POST': form = NewsletterCreationForm(request.POST, instance=Newsletter) if form.is_valid(): newsletter = form.save() if newsletter.status == 'Published': subject = newsletter.subject body = newsletter.body from_email = global_settings.EMAIL_HOST_USER for email in newsletter.email.all(): send_mail(subject=subject, from_email=from_email, recipient_list=[email], message=body, fail_silently=True) messages.success(request, 'Your Changes Write Successfully.', 'alert alert-success alert-dismissible') else: messages.warning(request, 'SomeThing Went Wrong..', 'alert alert-warning alert-dismissible') return redirect('control_newsletter_detail', pk=newsletter.pk) else: form = NewsletterCreationForm(instance=newsletter) context = { 'form': form, } return render(request, 'control_panel/control_newsletter.html', context) when I try to access to newsletter_edit/1/ from here in my teplate code : <div class="col-sm-8"> <div class="col-sm-2"> <a href="{% url 'control_newsletter_edit' pk=newsletter.pk %}"> <button class="btn-success">Edit</button> </a> </div> I faced to this error : ValueError at /panel/newsletter_edit/1/ The view newsletter.views.control_newsletter_edit didn't return an HttpResponse object. It returned None instead. I checked my urls.py and my views.py over and over but I cant find out what is my problem. is any body know why I face to this error? In addition, I'm sorry for writing mistakes in my question. … -
Adding Authotization Headers to My Angular APP Http Post Request
I want to add Authorization Headers to a Post request after researching a lot over the web and trying all possible ways of adding headers to a request i still couldn't make it happen i need to authenticate the post request of my angular app to django server headers2 = { "Content-Type": "application/json", "Authorization": "JWT " + token } json_data = json.dumps({"content":" content nice content"}) posted_response = requests.post(ENDPOINT, data=json_data, headers=headers2) when i fired this code it's running perfectly fine and adding it my data base using python requests i assumed the process would be same for angular as well and added authorization headers directly to the headers of http post request createPost(input:HTMLInputElement){ // input.value=''; let post={content:input.value}; let head = new Headers({ 'Content-Type': 'application/json', // 'Authorization': "JWT"+'Bearer '+localStorage.getItem("token") "Authorization": "JWT " + localStorage.getItem("token") }); let requestOptions = new RequestOptions({headers: head}); let body = JSON.stringify(post); this.http.post(this.url,body,requestOptions) .subscribe(response =>{ post['id']=response.json().id; this.posts.splice(0,0,post); }); the token value is stored in localstorage but it didn't work so after crawling over google and all i came to know about Http Interceptors created a service and tried to add the authorization to them @Injectable({ providedIn: 'root' }) export class AuthoService implements HttpInterceptor { constructor() { } intercept(req,next){ let … -
Reverse for 'password_change' with no arguments not found. 1 pattern(s) tried: ['r^password_change/$']
I added django.contrib.auth authentication views to my app. Now I am unable to access these views. I am getting the error as mentioned in the title above. Do I have to remove the namespace or change the namespace to other name? urls.py : from django.contrib.auth import views as auth_views from django.conf.urls import url,include from . import views app_name = 'set_goals' urlpatterns = [ url(r'^$',views.index,name='index'), url(r'^(?P<pk>[0-9]+)/about/$',views.about,name='about'), url(r'^(?P<pk>[0-9]+)/download/$', views.download, name='download'), url(r'^login_user/$', views.login_user, name='login_user'), url(r'^logout_user/$', views.logout_user, name='logout_user'), url(r'^register/$', views.register, name='register'), url('r^password_change/$',auth_views.password_change,{'post_change_redirect':'set_goals:password_change_done'},name='password_change') , url('r^password_change/done/$',auth_views.password_change_done,name='password_change_done'), ] base.html : {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'set_goals:about' user.id %}">All Goals</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'set_goals:password_change' %}">Change Password</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'set_goals:logout_user' %}">Logout ({{user.username}})</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'set_goals:index' %}">About</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'set_goals:login_user' %}">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'set_goals:register' %}">SignUp</a> </li> {% endif %} what is the mistake here? what is the change to be done here? Please help. Thanks in Advance! -
django-comments add a new url and a view for comments?
i am newer and study django.when i install django_comments , i need add to add a new url and view for django_comments, but it don't work. comments folder structure: __init__.py __pycache__/ forms.py migrations/ models.py templates/ urls.py views.py __init__.py: def get_model(): from comments.models import CommentModel return CommentModel def get_form(): from comments.forms import CommentForm return CommentForm and forms.py and models.py is fine work.but when i add urls.py, views.py and add the urls to main urls file. it don't work. urls.py: from django.urls import path from . import views urlpatterns = [ path('delete/<int:comment_id>/', views.delete_own_comment, 'delete_own_comment'), ] views.py from .models import CommentModel @login_required def delete_own_comment(request, comment_id): comment = get_object_or_404(CommentModel, id=comment_id, site__pk=settings.SITE_ID) if comment.user == request.user: comment.is_removed = True comment.save() but when i add path('mycomments/', include('comments.urls')) to main urls.py, it run strange errors. can anyone help me??? -
Django validator to correct rather than reject user input
In my elicitation app (started as the polls tutorial, now much larger) I am implementing my own simple hashtags for text answers. The implementation is quite minimal, and really just uses a word-search filter based on a query-string of the word that has been tagged. The problem is that a lot of characters that are valid in an text field are not acceptable in a URL, so hashtags made by non-expert users need to be amended to work correctly. People want to hyphenate or & ampersand their words, and it doesn't work. It also would be annoying if some people are #brain-storming and others are #brainstorming. What are the risks of creating a pseudo-validator that strips query-string breaking chars from user entries, but does not create validation errors? I'm working on my own at present, but do see this as a product other people will work on or fork in the future. If I create a validator for this task is it more appropriate to 'validate' and amend as part of a ModelForm field, or in the models? (Everything is a django form in this app). Is this already in core django somewhere? (I'm not looking to drop in a … -
Add/delete/update Django ManyToManyField through iterated forms in one view
It seems like this is definitely not the best way to do it, but it seems to be almost working for me. I am trying to create a view where I have a table of users that are generated from one model, but then also an extra column at the end that contains a simple form (checkbox) for each row in the table which can add, remove, or update a ManyToManyField. I want to be able to have the user be able to check many different users, none, or any combination. The issue I'm running into is that when one of the form checkboxes is clicked, it removes any existing checkboxes that were checked and only keeps the newly clicked checkbox checked. I feel it has something to do with how I'm iterating through if request.method == 'POST' and all the code below it, as I've never done something like that. My code is as follows: views.py def employee_output_table(request): table = Employees.objects.all() queue_exists = UserSurveyQueue.objects.filter(user=request.user) context = [] for user in table: d = {} d['user'] = user username = User.objects.get(username=user).username queue = None if queue_exists: queue = queue_exists.get(user=request.user) context.append(d) if request.method == "POST": form = UpdateSurveyQueueForm(request.POST, instance=queue, user=request.user.id, query=user) … -
How to check if value occurs in a field of a model list in Django?
I have a list of Django models, I want to check if a string value occurs somewhere in a specific field for ANY model in the list. Please see the example below: class something: animals = [] #type: list[Animals] def does_atleast_one_animal_make_that_sound(animal_sound): if animal_sound in ...# for each animal in animals, turn animal.sound into a list print('One of the animals in the list makes this sound') else: print('No animal makes this sound') How would I correctly write the part of the function with the "..."? -
delete session value on template
i'm create a session value on a views(insertProduct): def insertProduct request.session['insert_product'] = 'ok_insert' return redirect('list_products') def listProducts context ={ 'productos':Products.objects.all() } return render(request, 'mytemplate.html', context) on my template validate if exist on session: {% if request.session.insert_product == 'ok_insert'%} //do something //here i need delete the session value {% endif %} please maybe any idea or suggest thanks !! -
Django objects order_by give me duplicates users
I am trying to get all users (excepted request.user) and order them by datetime of last message they received. Maybe I am doing it wrong. @login_required def get_users(request): if request.method == 'POST': users = list(User.objects.filter(~Q(username = request.user)) .order_by('personal_messages__sent_date').values()) return HttpResponse(dumps({'users': users})) return redirect('message:index') dumpsis from json_tricks. Data are received by a Vue.js object with JS fetch My models.py from django.db import models from django.conf import settings class PersonalMessage(models.Model): text = models.TextField() sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='personal_messages', null=True, on_delete=models.SET_NULL) recipient = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) sent_date = models.DateTimeField('sent date', auto_now_add=True) The thing is if I only do users = list(User.objects.filter(~Q(username = request.user)).values()) it works well but if I add the order_by users = list(User.objects.filter(~Q(username = request.user)) .order_by('personal_messages__sent_date').values()) I get duplicates for each user. Seems it returns each user n times if user is linked with n messages. Maybe there is another way. Any Idea? -
how can I do a following system with just a manytomanyfield?
I am doing a following system for a django project. models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followers = models.ManyToManyField('self', symmetrical=False, blank=True, related_name='followers_profile') following = models.ManyToManyField('self', symmetrical=False, blank=True, related_name='following_profile') biography = models.TextField(max_length=500, blank=True, null=True) profile_picture = models.ImageField(blank=True, null=True) def __str__(self): return self.user.username And I want to know if I can do this with just a followers field. -
Make a multiple ChoiceField based on a ManyToMany relation but with other table values
Let's say I have the following models : class Identifiers(models.Model): number = models.IntegerField(unique=True) #other things class Items(models.Model): number = models.ForeignKey(Identifiers, to_field='number') type = models.CharField() aspect = models.CharField() class Equipment(models.Model): items = models.ManyToMany(Identifiers) So basically, my model Equipment is a "list" of Items, but referred with the Identifiers model, as one ID regroups multiple items (same item that share different names for example). By default, the generated form field will be populated with Identifiers objects, but I'd like to replace them with Items objects (of course, selecting multiple items will be equivalent to selecting only one of them). What I'd like to do is to populate the choices with a part of the Items objects (just a few, I'll probably work with pages to list them all as the Items table is currently filled with over 9k objects), but to keep all Items already present in my element instance as well as initial choices (only shown as one Items element for one Identifiers element, not all of them). I'm using a javascript plugin for dual select boxes with a search field so I can't load all values at once as it will be too slow. I first wanted to get elements … -
Render JSON from external url in the same template
I need to render the info of the JSON that is returned from another view. Here is my code, i tryed using HttpResponseRedirect but couldn't do it. When i click the button i'm supossed to render the JSON that the utils returns to the view 'estadistica', on the second div (col.sm.9) in the same page, hopefully without recarging all the page template <!DOCTYPE html> <html lang="en"> <head> <title>Ganadero</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <style> /* Set height of the grid so .sidenav can be 100% (adjust if needed) */ .row.content {height: 1500px} /* Set gray background color and 100% height */ .sidenav { background-color: #f1f1f1; height: 100%; } /* Set black background color, white text and some padding */ footer { background-color: #555; color: white; padding: 15px; } /* On small screens, set height to 'auto' for sidenav and grid */ @media screen and (max-width: 767px) { .sidenav { height: auto; padding: 15px; } .row.content {height: auto;} } </style> </head> <body> <div class="container-fluid"> <div class="row content"> <div class="col-sm-3 sidenav"> <h4>Ganado</h4> <form method="POST"> {% csrf_token %} <label class="row"> Animal: {{ form.animal }} </label> <label class="row"> Ciudad: {{ form.ciudad }} </label> <label class="row"> Feria: … -
how to avoid circular references and write DRY code in django
Whenever I create DRY functions that I can reuse later and then use them in models, I get circular references; For example: I have the following models: from social.services import get_top_viewed_posts class Post(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) title = models.CharField('Post Title', max_length=255) class ActivityUpdateEmail(models.Model): sent = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now = True) def send(self): posts = get_top_viewed_posts() My top viewed posts function is another file called services.py so I can access it other places. It looks like: def get_top_viewed_posts(): posts = Post.objects.filter( pk__in=popular_posts_ids, ).order_by( '-created_at' ) return posts Then I get the error: services.py", line 1, in <module> from social.models import Post ImportError: cannot import name 'Post' How can I use this dry approach of abstracting functionality, and then being able to use them in my models? -
Reducing Django queries! Get all results in one query rather than multiple?
In my program, I am getting all items that belong to a table and are part of a certain category. This should be a really simple SQL query...but it seems like Django is making things much more complicated. sqs = super(ItemView, self).get_queryset() res = sqs.exclude(item_status='hidden') return res There are ~50 items that should be found. In the view, Django gets a queryset that is full of <SearchResult> objects. This gets sent to the front end where it is looped over and added to the page. {% for item in items %} {% individual_item %} {% endfor %} The Django toolbar is showing an individual query for every single item, so in this case, over 50 queries for what should be one. Am I just misunderstanding how Django works and this is normal behavior? Or is there a way for me to run this as the one simple query it should be and send all the results from the view to the front end? -
Django Class Based View Generic To Accept List
I'm using class based views to return a list based upon a GET request. My class is inheriting from generics.ListAPIView. The issue that I'm having is that generics.ListAPIView expects a queryset object. Instead of a queryset object, I would like to use a row or dictionary object. How can I configure the generics.ListAPIView to accept a list or dictionary instead of a queryset or RAWqueryset object? http://www.django-rest-framework.org/tutorial/3-class-based-views/ -
Django/Python - Help moving is_authenticated and user == model.user to view
First off, sorry if I am not clear on what I'm trying to do or if I don't give enough info, I'm still relatively new to Django/Python. I currently have a view that renders something like a blog post: class SingleCharacter(LoginRequiredMixin,generic.DetailView): model = models.Character def get_context_data(self, **kwargs): context = super(SingleCharacter, self).get_context_data(**kwargs) return context And, in the template for this view, I have a template tag that checks if the user is authenticated AND the owner of the post: {% if user.is_authenticated and user == character.user %} However, I'm currently in the process of incorporating xhtml2pdf into my project and this method of securing the post to only the user who created it is causing some issues. I'm wondering if it's possible to move the user.is_authenticated and user == character.user into the view instead of a template tag, and if so can i do it with a simple if statment, something like this? class SingleCharacter(LoginRequiredMixin,generic.DetailView): model = models.Character if user.is_authenticated and user == character.user: def get_context_data(self, **kwargs): context = super(SingleCharacter, self).get_context_data(**kwargs) return context else: <I'll include some redirect to a 404 page> I'm trying to see if there's another way to do it, but I thought I'd throw this out here … -
Migrate data from Drupal 7
I'm migrating a drupal website to Django, and I need to get the post (news) from my drupal installation... The question is: what tables do I need to read to do that? -
Subquery in django ORM
I have a table with next columns: key time value And I need to have a query like that: SELECT "time", SUM("value") FROM ( SELECT "key", django_trunc_datetime("time"), AVG("value") FROM my_table GROUP BY "key", django_trunc_datetime("time") ) GROUP BY "time" Is it possible in Django ORM? Maybe with some fake model based on the subquery? Thanks -
Django 2.1 - creating the correct path URL for primary keys
I am new to Django and I am trying to create a school database webapp as a training exercise.(using Django 2.1) I set up two models School and Student. I have the home page being a list view of all the schools in the database. Each of these schools is an anchor reference to display the school details and a list of all the schools students. Each school student is also an anchor reference to the Student detail page. The error am getting is on my path on my urls page. path('<int:pk>/<int:cpk>/',views.StudentDetailView.as_view(),name='student_details'), This line gets the url to output the primary key of the school that I am currently on and the primary key on the student I selected. When I click the student name it goes to the student with the same primary key as the school since the url is (basic_app/1/1/). How do I get it to pull from the second number in the url (ckp) and display that primary key data? For example, school with the pk of 1 has 10 students. On the school detail page it list all the students. When I click on student 3, the url will look like basic_app/1/3/ (based upon the …