Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Save multiple selections for the same input name to the database and getting it back in another view
I need to save several checkboxes values that have the same name. like: <input type="checkbox" name="eth_hisp" value="Mexican" id="eth1_hisp" class='chk-btn'/> <label for='eth1_hisp'>Mexican</label> <input type="checkbox" name="eth_hisp" value="Cuban" id="eth2_hisp" class='chk-btn'/> <label for='eth2_hisp'>Cuban</label> <input type="checkbox" name="eth_hisp" value="Puerto Rican" id="eth3_hisp" class='chk-btn'/> <label for='eth3_hisp'>Puerto Rican</label> I need to store values which will be selected (checked) to database as one value. (It is possible to be done as the string with the command: eth_hisp=''.join(form.getlist('eth_hisp')) Question: How to transfer these values back to the view (it will be another view as a variable name? In other words, There is another view where selected checkboxes has to be also selected if in the example above they were checked (1 view - is user view, 2 view is admin edit view) -
django import some fields by excel and some fields by default
My view code for importing data in the db is like this : def excel_import(request): uploadform=UploadFileForm(None) if request.method == 'POST' : uploadform = UploadFileForm(request.POST, request.FILES) if uploadform.is_valid(): file = uploadform.cleaned_data['docfile'] data = bytes() for chunk in file.chunks(): data += chunk dataset = XLS().create_dataset(data) result = ExportSpec().import_data(dataset,dry_run=False, raise_errors=True, user=request.user) return render(request, 'BallbearingSite/news.html',{'uploadform':uploadform}) and my models is like this : class Stocks(models.Model): docfile = models.FileField(blank=True,null=True,upload_to='documents/') user=models.ForeignKey(User, null=True) name=models.CharField(max_length=128,verbose_name=_('stockname')) number=models.CharField(max_length=64,verbose_name=_('number')) suffix=models.CharField(max_length=12,verbose_name=_('uffix')) brand=models.CharField(max_length=64, validators=[ RegexValidator(regex='^[A-Z]*$',message=_(u'brand must be in Capital letter'),)] ,verbose_name=_('brand')) comment=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('comment')) price=models.PositiveIntegerField(blank=True,null=True,verbose_name=_('price')) date=models.DateTimeField(auto_now_add = True,verbose_name=_('date')) checking= ((_('pending'),_('pending')), (_('reject'),_('reject')), (_('approved'),_('approved')), (_('expired'),_('expired')), ) confirm=models.CharField(choices=checking,max_length=10,verbose_name=_('confirmation'), default=_('pending')) seller=models.BooleanField(verbose_name=_('seller'), default=1) I want to get some fields by excel file and some fields like date,confirm,user set by default also the id should set by default as latest id+1 for each row of the excel file Any advice is appreciated. -
django Restframework _ registraion via sms with random string
I need to add a functionality to my registration process.a token for users, sending to them via sms and activate their account.if token matches to the user input,the account will be activate.so my first thought was to create a FirstToken model that has OneToOneRelation to User model.token will created with some random string and sends to the user visa sms. models.py class FirstToken(models.Model): token = models.CharField(max_length=6, blank=True) user = models.OneToOneField(User,on_delete=models.CASCADE, related_name='first_token') def save(self, *args, **kwargs): chars = string.ascii_lowercase + string.digits size = 6 self.token ="".join(random.choice(chars)for _ in range(size)) super(FirstToken, self).save(*args, **kwargs) UserProfile is extends from User Model serializers.py class ActivateUserSerializer(serializers.ModelSerializer): phonenumber = serializers.CharField() token = serializers.CharField() class Meta: model = FirstToken fields = ['phonenumber', 'token'] def validate(self, validated_data): x = validated_data.get('phonenumber') phonenumber = UserProfile.objects.get(phonenumber__exact=x) if not phonenumber : raise serializers.ValidationError("phonenumber is not correct") else : return phonenumber def validate(self, validated_data): token = validated_data.get('token') x = validated_data.get('phonenumber') if token == "1jzyvm": user = UserProfile.objects.get(phonenumber=x) user.is_active = True user.save() else : raise serializers.ValidationError("ops ....") return user so basically i made a random string.i tried to test it with a string that i made from Admin.if string matches make the user active. by the way for sending string via sms i will made … -
Handling duplicate email address in django allauth
What I am trying to do ? I am trying to avoid duplicate email address by following these steps: Before user login to my site I check to see if the email address already exists. If no then login the user otherwise check the below steps. Check to see if the provider of registered user match the user trying to login. If no then don't allow user to login otherwise login the user. What is the problem ? I get the following error: Error:AttributeError at /accounts/twitter/login/callback/ 'QuerySet' object has no attribute 'profile' My Code: views.py: @receiver(pre_social_login) def handleDuplicateEmail(sender, request, sociallogin, **kwargs): if sociallogin.account.provider == 'facebook' or sociallogin.account.provider == 'twitter': email_address = sociallogin.account.extra_data['email'] # I use fb, twitter & linkedin this is for fb & twitter else: email_address = sociallogin.account.extra_data['email-address'] # This is for linkedin users = User.objects.all().filter(email=email_address) if users: if not (users.profile.provider == sociallogin.account.provider): response = 'Your social account email address is already registered to some account. Please choose a different one.' raise ImmediateHttpResponse(render(request, 'index.html', {'type': True, 'response': response})) # redirect to index template with error message. models.py: class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) provider = models.CharField(max_length=256, blank=True, null=True) -
Django + Axios: File download not working in Firefox
I am using Axios to send my Django backend information, which in turns creates a file and sends it back to the front end. The code I have below works great in Safari and Chrome. However, the file does not download in firefox. BTW, no errors show up in the firefox console, or in Django. Axios axios({ method:'post', url:'/api/downloadDoc', responseType:'blob', data: params, }) .then(response => { let blob = new Blob([response.data], {type: 'application/force-download'}) let link = document.createElement('a') link.href = window.URL.createObjectURL(blob) link.download = "YourPaper.docx" link.click() }) .catch(e => { console.log(e) }) Django View Sending File def downloadPaper(request): if request.method == "POST": #Recieve info through post and create document #variable path is path to newly created document wrapper = FileWrapper(open(path, 'rb')) response = HttpResponse(wrapper, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=' + 'yourpaper.docx' response['Content-Length'] = os.path.getsize(path) return response return HttpResponse(status=405) I am hoping someone knows what could be causing firefox to not download. Thanks! -
First attempt at Django (2.0) models resulting in AttributeError when making migrations.
As a complete beginner, I really hope I'm missing something obvious here, and that someone with experience can easily point out my mistake. I'm in the first steps of creating some Django models, and can't figure out how to resolve an error I get when I try to make migrations. From my research, it looks like this error is vague. I have no idea what it means by saying there's no attribute 'model'. Here's the traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 332, in execute self.check() File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 22, in check_admin_app errors.extend(site.check(app_configs)) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\contrib\admin\sites.py", line 79, in check if modeladmin.model._meta.app_config in app_configs: AttributeError: 'Book' object has no attribute 'model' And here's the model code: class Author(models.Model): name = models.CharField(max_length=80, blank=False, null=False, unique=True) class Book(models.Model): title = … -
Django Form submit manipulate values
so currently I am stuck with a Message app in Django. So I am passing a list of user names to my template to a input field for autocomplete suggestions who to send the message to. Now when I save the model it says "receiver must be a user instance". How can I change/manipulate the value and look the associated user with username up in my database (like I tried in my clean & save function, see Link, but I think the error message appears before it comes to the lines) Thanks very much! -
Setting up Django and mongodb
I am using Django 1.9 and I trying to connect to MongoDB database to store the data. I googled but I did not find any tutorial to setup the django with the MongoDB database. Can anyone please provide me tutorial to setup the mogndb db database with the django? -
How to know if a new user has created an account by clicking on the invitation email sent by an existing user of the site? (python-django)
I am trying to improve an existing feature that allows the users to invite their friends via email invitation. What I want to do is to know if someone has clicked on the link sent in the email invitation and registered in the site. (For example, if a new user registers by clicking on the email invite that I sent, then I get some special features after he completes registration). The first thing that popped in my mind is to create a new table to track all the invitations by the user who sent it, and the user to whom it was sent. But then the same user may receive multiple invitations if he has many friends that are already registered (So, I decided this isn't the best way). I have done some research and came across python signals. But it is confusing and there aren't that many tutorials/ examples for similar use case. How can this be implemented? Any help would be great. Even links to coding tutorials of similar use cases helps too. Thank you! -
Django model field set default user in model
I have an existing model in which I want to add a User foreign key ex: user = models.ForeignKey(User, unique=False) If I set the parameter default=User.admin I get an attribute error, how can I set the default to be the User admin or any other user? -
Change the field class on error
I want to change the input field class and other attributes in case of error. So in form init : for f_name in self.fields: if f_name in self.errors: self.fields[f_name].widget.attrs['error'] = a else: self.fields[f_name].widget.attrs['error'] = b Now, I want to cycle thru the widget attributes and remove some attributes, not to be added to the html field(see error in this case). {% for name, value in widget.attrs.items %}{% if name is not error %}{% if value is not False %} ..... the condition is not working: {% if name is not error %} I tried is not, != , is not in(error, alpha) also using error as string 'error' are not working, but {% if name == error %} is working I don't understand why, because it should work as in normal python. The value of error can variate. -
Password Reset only by Username
I Implimented django password reset using email but currently want to restrict to only username so that user can change password only by using username. tried django built-in and plugin but unable to set to only username . Any suggestions would be appreciated -
Django Internationalization - Gettext error
Am building a site with Django. After downloading gettext-0.19.8.tar.gz ---> /Users/cohen/Downloads/gettext-0.19.8 and running all of the steps ./configure make and sudo make installation I received this error during it's installation python manage.py makemessages -l en Everything ran smoothly with the Gettext part until the instalation. I am using a MAC, using Pycharm as my IDE. Please advise! PS there is a way to bipass the gettext instalation in order to make the messages? Thank you! xgettext: ./venv/lib/python3.6/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/webencodings/__init__.py:1: Unknown encoding "utf8". Proceeding with ASCII instead. xgettext: Non-ASCII string at ./venv/lib/python3.6/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/webencodings/__init__.py:64. Please specify the source encoding through --from-code or through a comment as specified in http://www.python.org/peps/pep-0263.html. Why i got this error. I can't do the proper translation with this command I followed this training: Django internationalization minimal example http://www.marinamele.com/taskbuster-django-tutorial/internationalization-localization-languages-time-zones https://gist.github.com/mbillard/1647940 -
Access logged in user from extra template tags file
I try to create a django template tag in which I need the logged in user, e.g. @register.filter() def foo(id): return Bar.objects.get(creator = request.user.id) but I get a NameError, saying that request is not defined. Is there a way to access the request object in app_extras file? -
Django update "extended user profile" model field from webhook paramater
I am getting a webhook from our billing processor after a user makes a payment. So far I have successfully saved the webhook in models for record keeping. However, now I need to update the User account_paid field to the appropriate status. I believe I've outlined the steps properly but I am stuck on implementing the code. How do I update account_paid and make sure it's the right user ID? views.py #@require_POST def webhook(request): template_name = 'payment/index.html' hook = Webhook() hook.user = request.GET.get('clientAccnum') hook.clientSubacc = request.GET.get('clientSubacc') hook.eventType = request.GET.get('eventType') hook.eventGroupType = request.GET.get('eventGroupType') hook.subscriptionId = request.GET.get('subscriptionId') hook.timestamp = request.GET.get('timestamp') hook.timestamplocal = timezone.now() hook.save() print (hook.user, hook.clientSubacc, hook.timestamplocal) if hook.eventType == 'RenewalSuccess': #Update user account_level to Paid Account Profile.account_paid.update(True) else: #Update user account_level to Free Profile.account_paid.update(False) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) birth_date = models.DateField(null=True, blank=True) account_level = models.BooleanField(default=False) There are no error messages yet because I'm trying to figure out the structure right now. The goal is to finish this question with a working solution. *Side note: I know webhooks are delivered to URL as POST but for now I am using get purely for debugging purposes. -
You're accessing the development server over HTTPS, but it only supports HTTP
I've developed my own website on Django for a while, and today I started to learn how to deploy it. In the middle of the deployment work, I tried to host again locally, which seemingly went fine, BUT when I tried to access the site through my browser, the server printed this: [13/Jan/2018 16:56:49] code 400, message Bad request syntax ('\x16\x03\x01\x00À\x01\x00\x00¼\x03\x03ßà\x84¼+Jnßþn-ñ\x88ý©vAþK\x83¤²êT\x86\x0b.\x8em\x0b:â\x00\x00\x1cÚÚÀ+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00') [13/Jan/2018 16:56:49] code 400, message Bad HTTP/0.9 request type ('\x16\x03\x01\x00À\x01\x00\x00¼\x03\x03\x87') [13/Jan/2018 16:56:49] You're accessing the development server over HTTPS, but it only supports HTTP. [13/Jan/2018 16:56:49] You're accessing the development server over HTTPS, but it only supports HTTP. [13/Jan/2018 16:56:49] code 400, message Bad request version ('JJÀ+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00') [13/Jan/2018 16:56:49] You're accessing the development server over HTTPS, but it only supports HTTP. I don't know what I've done for this to happen. Here are some of the things I've done to the project that could have caused it. But of course, there could be other reasons too. 1.Added this is the settings.py: SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True X_FRAME_OPTIONS = 'DENY' # Heroku: Update database configuration from $DATABASE_URL. import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Static files (CSS, JavaScript, Images) # … -
Django: weird behavior of foreign key lookup and annotate F expression
class Sentence(Model): name = CharField() class Tokens(Model): token = CharField() sentence = ForeignKey(Sentence, related_name='tokens') Sentence.objects.annotate(n=Count('tokens', distinct=True)).filter(n=5).filter(tokens__name__in=['se']).annotate(n0=F('tokens')).filter(tokens__name__in=['faire']).annotate(n1=F('tokens')).filter(tokens__name__in=['faire']).annotate(n2=F('tokens')).filter(tokens__name__in=['un']).annotate(n3=F('tokens')).filter(tokens__name__in=['avoir']).annotate(n4=F('tokens')) Above code generates the following query: SELECT "sentence"."id", "sentence"."name" COUNT(DISTINCT "token"."id") AS "n", T3."id" AS "n0", T4."id" AS "n1", T4."id" AS "n2", T6."id" AS "n3", T6."id" AS "n4" FROM "sentence" LEFT OUTER JOIN "token" ON ("sentence"."id" = "token"."sentence_id") INNER JOIN "token" T3 ON ("sentence"."id" = T3."sentence_id") INNER JOIN "token" T4 ON ("sentence"."id" = T4."sentence_id") INNER JOIN "token" T5 ON ("sentence"."id" = T5."sentence_id") INNER JOIN "token" T6 ON ("sentence"."id" = T6."sentence_id") INNER JOIN "token" T7 ON ("sentence"."id" = T7."sentence_id") WHERE (T3."name" IN (se) AND T4."name" IN (faire) AND T5."name" IN (un) AND T6."name" IN (avoir) AND T7."name" IN (faire)) GROUP BY "word_frword"."id", T3."id", T4."id", T6."id" HAVING COUNT(DISTINCT "token"."id") = 5 Why is numbering so strange (starts with T3)? But moreover why n2 is assigned to T4, not T5? Same for n4 and T6. Looks like numbers go by 2. What I want to accomplish is capture token id on each step of inner join. It works when there are one join, but then it breaks. Any suggestions? -
QuerySet in Django 2.0. doesnt work
I had a little break in Django and today I decided to come back to this framework. But now I have a problem with elementary thinks. I want to complete one of the guides in polish language. I've install Django 2.0 and I created some things like this: models.py from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE, ) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now ) published_date = models.DateTimeField( blank = True, null = True ) def publish(self): self.published_date = timezone.now() self.save def __str__(self): return self.title project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path(r'', include('blogs.urls')), ] app urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'),] views.py from django.shortcuts import render from django.utils import timezone from .models import Post def post_list(request): posts = Post.objects.order_by('title','published_date').first() return render(request, 'blogs/post_list.html', {}) and post_list.html <div> <h1><a href="/">My blog</a></h1> </div> {% for post in posts %} <div> <p>published: {{ post.published_date }}</p> <h1><a href="">{{ post.title }}</a></h1> <p>{{ post.text|linebreaksbr }}</p> </div> {% endfor %} Prompt do not receive any errors, but when I checking the localhost:8000 I have only a <h1> text. I … -
Modify one ForeignKey of a ModelForm get IntegrityError
I am want to creat a very simple commenting system for a basic django website. Each comment has a ForeignKey of the Article it is about. Obviously the ForeignKey should be initialised directly to the ForeignKey of the article the user is on. I don't understand why this is not working. I get an integrity error but if I change in the Model of the Comment, null=True then it does not save the article. When I print form1.articleRef I get the right thing def lire_article(request, slug): """ Affiche un article complet, sélectionné en fonction du slug fourni en paramètre """ article = get_object_or_404(Article, slug=slug) comments=Comment.objects.filter(articleRef=article) form1 = CommentForm(request.POST or None) if form1.is_valid(): form1.save(commit=False) form1.articleRef = article form1.save() envoi = True return render(request, 'blog/lire_article.html', {'article': article,'comments': comments,'form1':form1}) -
why doesn't pip freeze > requirements.txt output Django?
I'm trying to deploy my Django site on Heroku, and thus, I need a requirements.txt file with the necessary packages that Heroku needs to install for me. I understand Django is a necessary package to be installed. Unfortunately, Django isn't included in the file when I run pip freeze > requirements.txt. Why is this? I'm not sure what to show you so you can tell me what's going wrong. Let me know and I'll add it. FYI the site hosts just fine on my local computer, so Django is definitely installed. -
Render view of Django FormSet inside a Bootstrap Modal
I want to put a Django FormSet inside of a Bootstrap 4 modal, just like is done here. However, the big difference is that tutorial (and every other one I've found) is only using Forms, whereas I want to use a FormSet. Where the approach breaks down for me is here: return JsonResponse({'html_form': html_form}). JsonReponse can convert a form to Json, but it cannot convert a formset to Json. So I am wondering, is there another approach. Should I 1) Convert the formset to a dictionary and just return the dictionary? if so, how best to convert a formset to a dictionary? I am not the biggest fan of this approach because I have several customizations in the formset that I suspect I will lose. 2) Pass the entire Formset View into the Modal as html? is this even possible? 3) is there some 3rd approach that might work, perhaps using AngularJS? I will really appreciate any insight on this. -
Django Error - TemplateSyntaxError at / Could not parse the remainder: '['userType']' from '['userType']'
{% if 'is_logged_in' in request.session %} {% if request.session['userType'] == 0 %} {% include 'headersuccess.html' %} {% else %}dfgh {% endif %} This is my code. I am checking two conditions But I am getting the above error . Can anybody please help me to solve the same? My views.py is @csrf_exempt def index(request): if('is_logged_in' in request.session): id = request.session['authToken']; return render(request,"index.html",{'uid':id}); else: return render(request,"index.html",{}); -
How to declare a function in JavaScript?
I have a problem - I declared a function, but it execute incompletly: some of the instructions within execute, some not. I guess it happens, because DOM content hadn't loaded yet. But when I declare it inside of jQuery's $(document).ready() function I can't call it anywhere. How to declare function in JavaScript, to use it anywhere in the code? Here is my code: script.js (loaded at the end of body): function setSearchableColumns() { $('#data thead').prepend('<tr class="searching-row"></tr>'); $('#data thead th').each(function(){ var title = $(this).text(); $('.searching-row').each(function() { $(this).append('<th><input type="text" class="form-control form-control-sm" id="search_' + title + '" placeholder="Szukaj ' + title + '"/></th>'); }) }); table.columns().every(function(index) { var tableColumn = this; $('#data thead').find('input').eq(index).on('keyup change', function (e) { tableColumn.search(this.value).draw(); }) }); $('#search_\\#').remove(); //THIS DON'T EXEC $('#search_Operacje').remove(); //THIS DON'T EXEC } Written at the end of actually rendered template in django: $(document).ready(function(){ var table = $('#data').DataTable({ "ordering": true, "language": { "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Polish.json" }, "columns": [ null, { "width": "35%" }, null, null, null, { "width": "75px" }, ] }); setSearchableColumns(); }); -
Change primary key on manytomany field Django
Is it possible to change primary key of many to many field from default to uuid? Table is already populated. What is the best way for migration? -
Loading Image in a React+Django app
So I have a little project written in python/django for the backend and react for the frontend. I followed the tutorial from: http://geezhawk.github.io/using-react-with-django-rest-framework I want to show an image for the logo of the project, the webpack build was success, but however, the image could not load up when I see the page, I suppose that is because the compiled URL of the image could not be resolved from the django's urls, and also accessing the url for it just load the same index page.... At this point I'm not sure how I can fix it, but I would be more than grateful if anyone can point me to an example code of how to do this, how to load image in a react + django project.