Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django:How to get the response location(url) of HttpResponseRedirect
I am using django to dev a website. I need to get the url (location) from the redirect response, but can't find any method or attr. Traceback (most recent call last): File "/opt/python27/lib/python2.7/site-packages/django/core/handlers/base.py", line 223, in get_response response = middleware_method(request, response) File "/opt/dbinabox/DBInBoxWeb/dbinabox/dbasrm/altus.py", line 16, in process_response print response.header AttributeError: 'HttpResponseRedirect' object has no attribute 'header' -
django - redis how to pass jwt
redis 4.0.8 django 2.0.2 mac 10.13 python 3.6.4 User Info in REDIS hash userinfo:* * is userUID field = email password userType and search email to userUID hash email:userUID field = email , value = userUID redis_connection.py import jwt user send email and password compare email , password if it correct this token create jwt_token = {'token':jwt.encode({'userUID':userUID, 'email':email, 'userType':userType}, 'secret','HS256')} return jwt_token Got it at views.py , How to add token at request -
Django how to use two view in a template
I have two view section , one of them save the fields into database and one of them is for autocomplete of a field , how can i use both of them in a html template : FIEST VIEW : def stock(request): stocks_form=StocksForm(None) if request.method == "POST": stocks_form =StocksForm(data=request.POST) if stocks_form.is_valid(): instance=stocks_form.save() instance.user=request.user instance.save() messages.success(request,"Successful" ,extra_tags="savestock") else: messages.error(request, "Error!") else: stocks_form=StocksForm() return render(request,'BallbearingSite/stock.html',{'stocks_form':stocks_form}) SECOND VIEW : class StocksAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return Stocks.objects.none() qs = Stocks.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs urls.py ??? url(r'^stock/$',views.stock,name='stock'), url(r'^stock/$',views.StocksAutocomplete.as_view(create_field='name'),name='stock'), TEMPLATE : <form enctype="multipart/form-data" method="post" > {% csrf_token %} {{ stocks_form.as_p }} <input id="savestocks" type="submit" name="" value="ثبت"> </form> FORMS.py : class StocksForm(forms.ModelForm): class Meta(): model=Stocks fields=('name','number','suffix','brand','comment','price') widgets = { 'name': autocomplete.ModelSelect2(url='stock_autocomplete') } def clean_name(self): return self.cleaned_data['comment'].upper() -
How to stop logging Recent actions and History in Django 2.* admin panel?
to all! I'm using Django 2.* and have no idea how to remove this useless for me logging features from Django Admin panel. I need completely stop tracking all recent actions and logging history in Django admin panel. Please help me find out a solution. (i've Googled well enough before asking for help here) -
Django rest: You do not have permission to perform this action during creation api schema
I am trying to add some schema views to my django project (i used this examples) My code: def get_auth(): auth = [ path('', include('rest_framework.urls', namespace='rest_framework')), path('register', RegisterApiView), path('token/obtain/', TokenObtainPairView), path('token/refresh/', TokenRefreshView), ] return auth def get_schema(): schema_url_patterns = [ path('api/auth', include(get_auth())), ] schema_view = get_schema_view( title='Auth Schema', url='/api/auth/', patterns=schema_url_patterns, ) return schema_view urlpatterns = [ path('api/auth/', get_schema()), ] And when I try to connect to /api/auth/ I encounter an error: HTTP 403 Forbidden Allow: GET, HEAD, OPTIONS Content-Type: application/coreapi+json Vary: Accept { "detail": "You do not have permission to perform this action." } -
Django 2.0 slug urls.py unexpected keyword argument 'slug'
the site is very simple just 3 pages ,, home and the second url shown in urls.py works great but when i go from the subjects to unit page i got: TypeError at /subjects/units/english units() got an unexpected keyword argument 'slug' i have no idea why i'm getting this error .. the new modifications made in django 2.0 in url and path i read the documentation but i don't understand <slug> part well ,, is it <slug> or <slug:slug> i don't get it and what's the meaning of the first and the second one ??? .. in templates folder {% url 'units' item.slug %} units is the name of the path but is -- item.slug -- right ?? if any one explained it to me i would be very grateful. models.py class Unit(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) name = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) archived = models.BooleanField(default=False) slug = models.SlugField(max_length=250, unique=True) created = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated = models.DateTimeField(auto_now=True, null=True, blank=True) seo_name = models.CharField(max_length=60, blank=True, null=True) seo_description = models.CharField(max_length=165, blank=True, null=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Unit, self).save(*args, **kwargs) def __str__(self): return self.name views.py from django.http import HttpResponse from django.template import loader from .models import Subject, Unit, Lesson … -
Building a data driven Dashboard in Django along with pandas
Problem statement - what am trying to do is create a dashboard using Django and pandas. Pandas will do the calculation part and Django would be displaying the data and all plots and graphs. Achieved: Created an app and imported pandas in the views file. and then rendering it. though getting my data on display but its the error screen with my data. what I understood is I have to use a template to show my data. my code: def index(request): df = pd.DataFrame(pd.read_csv("C:/Users/lol/Desktop/lol.csv")) dff = df[["column_one", "column_two", "column_three"]] dff = dff.set_index("column_one") return render(request, dff.head(5)) If someone can point me how to push the data frame to the website in a tabular format. Thanks -
How to use jquery DataTables with django JsonResponse?
I am having tough time implementing dataTables for pagination. Can someone provide a working example for the problem? I am new for implementing jquery/javascript and learning it by reading examples. Below js script is working for doing other tasks on the same page but I am stuck in implementing this pagination here. My view is def ajax_load_questions(request): all_questions = Questions.objects.all() classroom = request.GET.get('classroom') topics = request.GET.getlist('topics_all[]') difficulty = request.GET.getlist('difficulty[]') subtopics = request.GET.getlist('subtopics_all[]') filter1 = all_questions.filter(classroom=classroom).filter(topic__id__in=topics) questions_list = filter1.filter(subtopic__id__in=subtopics).filter(difficulty__in=difficulty) response_questions = {} try: response_questions['questions'] = list(questions_list) except: response_questions['error'] = "No questions available" return JsonResponse(response_questions) My html file is <form method="post" id="questionForm" filter-question-url="{% url 'qapp:ajax_load_questions' %}" novalidate> {% csrf_token %} <table> {{form.as_table}} </table> <br> <button id="id_filter_button" type="button">Filter</button> <hr> <p>Questions</p> <div id="id_questions_list"> </div> <hr> <button type="submit">Submit</button> </form> Table I want to show pagination for <table border="1" id="id_question_table"> <thead> <tr> <th>Questions</th> [other fields] </tr> </thead> <tbody> {% for que in questions_list %} <tr> <td>{{que.question}}</td> [other fields] </tr> {% endfor %} </tbody> </table> js Script for getting other data on the same page $.ajax({ url: url, data: {'classroom':classroomId, 'difficulty':difficulty_list, 'topics_all':myTopics, 'subtopics_all':mySubtopics}, success: function (data) { $('#id_questions_list').html(data) // I guess this has to be changed but don't know how } }); I am really stuck on … -
Django - Support Multiple Login Mechanism
I've a Django Application which needs to support multiple login mechanisms ie, the default Django Authentication, Phone Number(or some other Unique Identifier) OTP Authentication and should also support token mechanism. I know all about how I can handle them individually (default username password, Django Oauth Toolkit, and making a separate Auth Backend for OTP), but don't know how to support multiple login mechanisms. How can I achieve this? Any example will be highly appreciated. -
What's the meaning of RUN mkdir /code and ADD . /code/
I'm now following instructions of Docker to create a Django+MySQL project. But for the Dockerfile, could any one explain why we have these two lines? FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code <=====Why we need to mkdir here, will /code dir be delete after build? RUN mkdir /code/db WORKDIR /code ADD ./mysite/requirements.txt /code/ <==For my understanding, here we copy our local requirements file into image's /code dir? RUN pip install -r requirements.txt ADD . /code/ <== What's this step doing? Copying all my current dir's content into /code? why we do this? -
Django - redis how to use AuthToken
used Django 2.0.2 , redis 4.0.8 , mac 10.13 ,python 3.6.4 userinfo in redis String user 1 userinfo:* is hash fields:email password createDate sex userType * is userUID use incr String user and email:userUID search UID to email fields : email value : userUID user send email and password Compare email and password If it correct There is no problem so far. but use this from rest_framework.authtoken.models import Token Token.objects.create(user=user) i don't know use Token without RDBMS i don't want to RDBMS i just use redis How to use Token with redis and if you know better way or Easy way plase help me -
row wise duplicate data need to be eliminated(Rowspan) using Django Python
As i have a dictionary in python. Dictionary values look like. d= {'Report.thpl Team =FULL'{'cdp.c': 899, '_arp_fusen.c': 34, 'discovery.c': 34, 'subnet.c': 4}, 'P1.thpl Team = Over': {'discovery.c': 34, 'file23.c': 4, 'cdp/cdp.c': 937, '_fusen.c': 83}, 'P1_Report1.thpl': {'arp_fusen.c': 83, 'disynet.c': 34, 'routes.c': 2, 'routing.c': 937}} My table looks this |test | file_name |coverage | ********************************************************** |Report.thpl Team =FULL | cdp.c | 899 | |Report.thpl Team =FULL | _arp_fusen.c | 34 | |Report.thpl Team =FULL | Discovery.c | 34 | |Report.thpl Team =FULL | subnet.c | 4 | |P1.thpl Team = Over | discovery.c | 34 | |P1.thpl Team = Over | file23.c | 4 | |P1.thpl Team = Over | cdp/cdp.c | 937 | |P1.thpl Team = Over | _fusen.c | 83 | |P1_Report1.thpl | arp_fusen.c | 83 | |P1_Report1.thpl | disynet.c | 34 | |P1_Report1.thpl | routes.c | 2 | |P1_Report1.thpl | routing.c | 937 | *********************************************************** code in article.html <table class="table table-hover" style="width:80%;" > <tr style="color:white;"> <th>Test Case</th> <th>File Name</th> <th>Coverage</th> </tr> {% for key, value in d.items %} <tr> {% for k,v in value.items %} {% if forloop.parentloop.first %} <td rowspan="{{ key|length }}">{{ key }}</td> {% endif %} <td>{{ k }}</td> <td>{{ v }}</td> {% endfor %} </tr> {% … -
How to convert evtx log file into cef log file format through wmi using python
my question is about How to convert evtx log file into cef log file format through wmi using python i strucking in this problem of converting evtx log file format into cef file format -
Django Auth Views login page displays no errors
I am using Django Auth Views to implement my login page. This is my url: url(r'^login/$', auth_views.login, {'template_name':'users/login.html'}, name='login'), And this is the template: {% extends 'base.html' %} {% block content %} <div class="ui raised text container segment"> <div class="ui horizontal divider">Login</div> <form method='POST'> <div class="ui form segment"> {% csrf_token %} <div class="required field"> {{ form.username.label }} {{ form.username }} {{ form.username.errors }} </div> <div class="required field"> {{ form.password.label }} {{ form.password }} {{ form.password.errors }} </div> <button class="ui primary submit button" name="submit_button" id="submit_button" type="submit">Login</button><br> Forgot your password? Click <a href='/password_reset/'>here</a>. </div> </form> <div class="ui bottom attached warning message"> <i class="icon help"></i> Haven't signed up yet? <a href="/signup/">Signup here</a> instead. </div> </div> {% endblock %} When I type in a Password that I know is right, no error messages are shown. Is there a fix for this? Thanks -
Django template does not detect instance of model
I added a Languages model to models.py: class Languages(models.Model): language = models.CharField(max_length=20,blank=False) level = models.CharField(max_length=30,blank=False) ordering = models.IntegerField(default=1) class Meta: order = ['order','id'] def __unicode__(self): return ''.join([self.language, '-', self.level]) called python3 manage.py makemigrations && python3 manage.py migrate and created a couple of instances: python3 manage.py shell In [1]: from resume.models import Languages In [2]: Languages.objects.all() Out[2]: <QuerySet [<Languages: Languages object (5)>, <Languages: Languages object (6)>]> In [3]: Languages.objects.get(id=5).__dict__ Out[3]: {'_state': <django.db.models.base.ModelState at 0x7f0f21bb7668>, 'id': 5, 'language': 'English', 'level': 'professional', 'ordering': 1} however my template does not detect any language: <h2>Languages</h2> {% for lan in languages %} <div> <h3>{{ lan.language }}</h3> <h5>{{ lan.level }}</h5> </div> {% endfor %} On the html of the site I see <h2>Languages but not the rest. Other models work fine. As said, this is the latest model I added to models.py. I also called flush: python3 manage.py flush This is part of showmigrations: python3 manage.py showmigrations | grep -i langua [X] 0016_remove_language_personalinfo [X] 0018_delete_language [X] 0019_languages How to troubleshoot this problem? -
Why is the consumer run twice when two users share the same websocket connection?
It's a one-to-one chat with message persistence. The issue is that when two users connect to the same chat, any message a user sends will be broadcast once but saved in the db twice. When only a single user is connected, however, it will work as normal--only save once. Help me figure out why the consumer is being run twice? Here is the relevant minimal code: class ChatConsumer(AsyncJsonWebsocketConsumer): ... async def receive_json(self, content): """ Called when we get a text frame. Channels will JSON-decode the payload for us and pass it as the first argument. """ # Messages will have a "command" key we can switch on command = content.get("command", None) recipient = content.get("recipient", None) sender = self.scope["user"] try: if command == "join": # Make them join the room await self.join_room(content["room"]) previous_message_list = await get_saved_messages(recipient, sender) for msg in previous_message_list: await self.send_json({ "msg_type": MSG_TYPE_MESSAGE, "room": content["room"], "username": msg.sender.user.username, "message": msg.message, },) elif command == "leave": # Leave the room await self.leave_room(content["room"]) elif command == "send": await self.send_room( content["room"], content["message"], content["recipient"] ) except ClientError as e: # Catch any errors and send it back await self.send_json({"error": e.code}) ... async def send_room(self, room_id, message, recipient): """ Called by receive_json when someone sends … -
Using Celery or Django-Background-Tasks on Openshift 3
I'm trying to figure out what the best way to actually invoke one of these on my pod. ie: For Django-Background-Tasks, you need to run python manage.py process_tasks How do I run this on my Django pod automatically, without having to ssh into my pod and just run it. I've been trying to use a Post Lifecycle Hook, but maybe I'm just doing it wrong. Any help would be appreciated. Thanks! P.S I'm currently working on a basic example using the openshift 3 django-ex github repo. (https://github.com/sclorg/django-ex) -
Tagging system for Django?
I'm looking for a tagging system I can use on my Django website to organize and structure language learning materials. Something similar to the tagging that is available on most blogs would be useful. Many thanks, Torsten -
Username Check DJANGO AJAX - Alert not working
I have a registration form class RegistrationForm(UserCreationForm): class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) email = forms.EmailField(required=True) def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['password1'].help_text = "Your password can't be too similar to your other personal information.Your password must contain at least 8 characters.Your password can't be a commonly used password.Your password can't be entirely numeric." def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: self.add_error('password1', 'Re-enter password') raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user I want to check username availability using ajax: views.py from django.contrib.auth.models import User from django.http import JsonResponse def validate_username(request): username = request.GET.get('username', None) data = { 'is_taken': User.objects.filter(username__iexact=username).exists() } return JsonResponse(data) Register.HTML { extends 'base.html' %} {% block javascript %} <script> $("#id_username").change(function () { var form = $(this).closest("form"); $.ajax({ url: form.attr("data-validate-username-url"), data: form.serialize(), dataType: 'json', success: function (data) { if (data.is_taken) { alert(data.error_message); } } }); }); </script> {% endblock %} {% block content %} <form method="post" data-validate-username-url="{% url 'validate_username' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign … -
attribute error on value for field on serializer django rest framework
I am receving the following error: AttributeError: Got AttributeError when attempting to get a value for field `city` on serializer `SearchCitySerializer` my serializers are correct though unless I am clearly missing something. Here is my model: class SearchCity(models.Model): city = models.CharField(max_length=200) here is my serializer class SearchCitySerializer(serializers.ModelSerializer): class Meta: model = SearchCity fields = ('pk','city') and here it is used in the view: from serializers import SearchCitySerializer def get(self, request, format=None): searchcityqueryset = SearchCity.objects.all() serializedsearchcity = SearchCitySerializer(searchcityqueryset) return Response({ 'searchcity': serializedsearchcity.data, }) the full error I am getting: File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/suitsandtablessettingsapp/views.py", line 37, in get 'searchcity': serializedsearchcity.data, File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 537, in data ret = super(Serializer, self).data File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 262, in data self._data = self.to_representation(self.instance) File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 491, in to_representation attribute = field.get_attribute(instance) File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/rest_framework/fields.py", line 462, in get_attribute raise type(exc)(msg) AttributeError: Got AttributeError when attempting to get a value for field `city` on serializer `SearchCitySerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'city'. [28/Feb/2018 02:41:43] "GET /api/dependancy/suitsadmin/settings/ HTTP/1.1" 500 20823 -
DRF serializer do not return a value with extra_kwargs of write_only
I'm practicaly copying the exemple code from the documentation, but the password field, with "extra_kwargs = {'password': {'write_only': True}}" is not returned as validated data. this is the code: class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = models.UserProfile fields = ('email', 'first_name', 'last_name', 'birthday', 'gender', 'telephone', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = models.UserProfile( email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], birthday=validated_data['birthday'], gender=validated_data['gender'], telephone=validated_data['telephone'] ) user.set_password(validated_data['password']) user.save() return user Take a look at the local variables. "password" is passed to the initialization function but do not return as validated_data self: UserProfileSerializer(data={'email': 'magalhaes@magalhaes.com', 'first_name': 'eduardo', 'last_name': 'magal', 'birthday': None, 'gender': None, 'telephone': '123465', 'password': 123456}): email = EmailField(max_length=255, validators=[]) first_name = CharField(max_length=64) last_name = CharField(max_length=64) birthday = DateField(allow_null=True, required=False) gender = ChoiceField(allow_null=True, choices=(('M', 'Male'), ('F', 'Female'), ('O', 'Outro')), required=False) telephone = CharField(allow_null=True, max_length=50, required=False) password = CharField(max_length=128, write_only=True) validated_data: {'birthday': None, 'email': 'magalhaes@magalhaes.com', 'first_name': 'eduardo', 'gender': None, 'last_name': 'magal', 'telephone': '123465'} No password... Thanks in advance!! -
Django CKEditor doesn't work on admin page
I tried to install CKeditor but couldn't figure out a way. Steps I tried pip install django-ckeditor Add 'ckeditor' to your INSTALLED_APPS setting. Run the collectstatic CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor" to my settings and from ckeditor.fields import RichTextField class MyModel(models.Model): myfield = RichTextField() when I requested the admin page for proper model, I can only get blank white page. There is no error on terminal. CKeditor files returns 302 HTTP. Screenshot from my admin page it is strange I can see related ckeditor things on DOM. am I missing something? -
Any way to group aggregations in Django?
We're currently using Django 1.8 and Postgres. I have an aggregation that I want to perform, but I want the aggregations grouped by month. This is trivial to do in SQL, but I can't seem to figure out any way to go about it with the Django ORM. Here's an example of the SQL query I'm performing that provides the desired results(SQL Fiddle): SELECT EXTRACT(month from date) as month, EXTRACT(year from date) as year, SUM(total) as total FROM transaction GROUP BY year, month ORDER BY year, month; And here's an example of my translation to Django(this one is using the Month class from this answer, but I've tried several variations): results = Transactions.all().annotate(month=Month('date')).aggregate(total=Sum('total', output_field=DecimalField())) There's some additional aggregating going on here, but I removed it for clarity. I don't care what the Django output would end up looking like as long as it's grouped by month. -
Django refuses to cascade on delete
Django 1.9 with PostgreSQL. I have a model that looks like this: class MyCrossModel(models.Model): one_thing = models.ForeignKey('OneThing', on_delete=models.CASCADE) other_thing = models.ForeignKey('OtherThing', on_delete=models.CASCADE) When I go to delete one of these in the database, it cascade-deletes the one_thing, but does not cascade_delete the other_thing. Scouring the Django docs but cannot find any mention of this behavior. -
EmailField allows but get SMTPRecipientsRefused exception
I am sending an email on my django application. the recipient address is an 'EmailField' Here how I defined it on forms. recipient_email = EmailField( required=True, label="E-mail address", max_length=254, widget=forms.EmailInput(attrs={'size':'80'}) ) As a test case I tried an email address with exactly 254 characters. 7yvghdfsvy7dfvy7y7y7y7y7vy7vy7vyyvyy7v7dyvysdfuivhjkvcbherhe77fuihrubhvfhbervfhfhvuirdhfuier89f84ewr4wur4wurewuiehifhesfshjfbsdvsdvcbsdhvgcsvcsdhvcbsdvbsdhvbuisdvghuisdvh4e7h7f478fgy4f4yuwgf4yuwgf4whu4wfbferhjbfeshjbfshjbfhuewrfhb4wy84ygf@emtwwavds.co.jp I know this is not a valid email address but EmailField allows it. but while sending this email, i have got 'SMTPRecipientsRefused' exception. the exception value says too long (255 bytes max) If i delete a one character of the address, it is working fine with 253 characters. My problem is how this 254 characters got [too long (255 bytes max)] error? even though I have handled it by catching SMTPException, can anyone suggest me a better way to validate the email address, thus I can display better error message. Django version : 1.11.3 Python version : 3.6.3