Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implement AWS authentication to use end user's resources in Python & Django App
I'm working on a project using Python(3.6) and Django(1.10) in which i need to use end user's account resource to make his code deployed on his aws account. I have set up 2 accounts(1 as my app & 2nd as a user's account) and make authentication successful.But when I have passed this auth in another view it throws some errors. Here's what I have tried: From views.py: def boto3_with_role(role_arn, session_prefix, external_id, **kwargs): """ Create a partially applied session to assume a role with an external id. A unique session_name will be generated by {session_prefix}_{time} `session` can be passed, otherwise the default sesion will be used see: http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-api.html """ sts = boto3.client('sts') res = sts.assume_role( RoleArn=role_arn, RoleSessionName='{}_{}'.format(session_prefix, int(time.time())), ExternalId=external_id, *kwargs, ) creds = res['Credentials'] print(creds) return partial(boto3.session.Session, aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'], ) class AwsAuthentication(LoginRequiredMixin, CreateView): def post(self, request, *args, **kwargs): AwsSession = boto3_with_role('arn:aws:iam::497736713165:role/IstiocloudCrossAccount', 'MyPrefix', 'abd37214@cloud') my_session = AwsSession() client = my_session.resource('s3') for bucket in client.buckets.all(): print(bucket.name) return render(request, 'dockerDep/aws/selectDeployment.html', {'bucket': bucket.name}) # return HttpResponse('Your Bucket is: {}'.format(bucket.name)) # From here AWS Deployments starting class AwSlsDeployment(LoginRequiredMixin, CreateView): def get(self, request, *args, **kwargs): AwsSession = boto3_with_role('arn:aws:iam::497736713165:role/IstiocloudCrossAccount', 'MyPrefix', 'abd37214@cloud') user_session = AwsSession() client = user_session.resource('s3') for bucket in client.buckets.all(): print(bucket.name) return render(request, 'dockerDep/aws/slsDeployment.html', {'bucket': bucket.name}) … -
How do I only check for existing form fields values if it was modified?
I am trying to allow users the ability to update their profile, but can't seem to figure out how to only raise an error if the 2 fields username, email were modified, or if the user is not that user. As of now, I can't save the updates as the error is continuously popping up since the user has those values obviously. I've also tried excludes but couldn't get it to work right either. Here is my code: forms.py class UpdateUserProfile(forms.ModelForm): first_name = forms.CharField( required=True, label='First Name', max_length=32, ) last_name = forms.CharField( required=True, label='Last Name', max_length=32, ) email = forms.EmailField( required=True, label='Email (You will login with this)', max_length=32, ) username = forms.CharField( required = True, label = 'Display Name', max_length = 32, ) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') def clean_email(self): email = self.cleaned_data.get('email') username = self.cleaned_data.get('username') if (User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists()): raise forms.ValidationError('This email address is already in use.' 'Please supply a different email address.') return email def save(self, commit=True): user = super().save(commit=False) user.email = self.cleaned_data['email'] user.username = self.cleaned_data['username'] if commit: user.save() return user, user.username views.py def update_user_profile(request, username): args = {} if request.method == 'POST': form = UpdateUserProfile(request.POST, instance=request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('user-profile', … -
How read information of mongodb on django environment
i have this 2 collection on mongodb airports routes I was searching how do that, i found djongo. After reading I understood the following. I must make models that matching those data, then only use queries. There are models only with few fields. Then I could use this methods e.g. Airports.objects.filter(name_airports__startswith='Goro') am I right? If anyone can guide me to right way , I'll be very grateful. If you have an example on the web, please share that with us, thanks in advance. -
Best way to Auto Fill CharField for token in Django
i need to generate a token for every user that will be created automatically -
Django objects.get matching query does not exist
I'm trying to get all attributes of a single object. I keep getting a "Devices matching query does not exist." I just cannot figure out my issue. Models.py `class Devices(models.Model): category_id = models.ForeignKey(Category, on_delete=models.CASCADE) device_description = models.CharField(max_length=100) device_status = models.CharField(max_length=50) device_date = models.DateTimeField() device_user = models.CharField(max_length=50)` Views.py def view_status(request, pk=None): device = Devices.objects.get(pk=pk) return render(request, 'homesite/device_status.html', device) urls.py url(r'^viewstatus/$', views.view_status, name='ViewStatus'), here is the url I use to call http://localhost:8000/homesite/viewstatus/?pk=1 There are 4 records in my able so I know there is a match for PK=1. -
How to enforce non empty on slugrelatedfield for many to many in serializer using Django Rest Framework?
Django version : 1.11 DRF version : 3 I have the following: class Shape(ProductVariantParent): art_numbers = models.ManyToManyField(Product, through='ShapeArtNumber') class ShapeSerializer(serializers.ModelSerializer): art_numbers = \ ArtNumberSlugRelatedField(queryset=Product.objects.all(), slug_field='art_number', many=True, required=True) class ArtNumberSlugRelatedField(serializers.SlugRelatedField): def to_internal_value(self, data): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user try: new_or_found_object, created = \ self.get_queryset().get_or_create(**{self.slug_field: data}) if created and user is not None: new_or_found_object.created_by = user new_or_found_object.updated_by = user new_or_found_object.save() return new_or_found_object except ObjectDoesNotExist: self.fail('does_not_exist', slug_name=self.slug_field, value=smart_text(data)) except (TypeError, ValueError): self.fail('invalid') Shape and Product are many to many relation. Shape treats the related field So when I pass in Product.art_numbers as None, i will trigger a cannot be null error message. When I pass in Product.art_numbers as [], I will not trigger any error message. How do I ensure that Product.art_numbers cannot be empty so I can trigger the right error message about how the art_numbers cannot be empty error message? I also use internationalization so I prefer that the right cannot be empty error message can be shown when I change the browser language settings? -
I don't know if I am deploying right.. site doesn't work
So I have studied the book, how to tango with django 1.10 and I was trying to deploy here my project. The bash part worked perfectly, but when I deployed and I go to danielcirstea.pythonanywhere.com/rango the app doesn't show.This is my web configuration: https://i.imgur.com/5ZiOC8U.png I also changed DEBUG to FALSE and hosts as needed. Please help. -
Correct architecture for scaling a backend
I have 3 instance of my django app hosted on Google Compute Engine in 3 different locations around the world. I am autoscaling my app to set up more instances when the cpu is at 70%. I also have a loadbalancer set up to route traffic to a close and functioning instance. This all works fine however what I don't get is how my database is scaled along with my app, in my case I have one mysql instance that stores all the data from all instances but I am not sure how to scale it since I want the same data to be available for all instances. Having only one presents many problems such as high latency for instances accessing it from another part of the world as well as all requests going to this single mysql instance. How can I better my architecture? -
How to modify request.POST in django custom middleware?
I want to add client_id and client_secret to the django POST request. Here is how my middleware.py file looks like: class LoginMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # auth_header = get_authorization_header(request) # Code to be executed for each request before # the view (and later middleware) are called. #Add Django authentication app client data to the request request.POST = request.POST.copy() request.POST['client_id'] = '12345678' request.POST['client_secret'] = '12345678' response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response Middleware is being successfully processed when I check it with a debugger. Thought when a view is called the 'client_id' and 'client_secret' fields are missing in the request. What could be the problem? How to properly add such data to the request? -
Display from 2 tables in Django
my function in view return a context, in this context there is 2 tables this is my view : > def myfunction(request): > ......... > > context = { 'dst_link' : second, 'titles' : third } > return render(request,'mytestapp/result.html',context ) so in the result.html i want to display the 2 tables like that : <li > <a href="https:{{second}}" target=_blank > {{third}}</a> </li> the problem is that i have 2 tables and i don't know how to make a boucle in the 2 tables in the same time -
dlib and django. how to integrate and import dlib into django
I am trying to use dlib in my django project. I am using aws ubuntu, but I was not able to use pip dlib, so I compiled directly according davisking instruction to use this PR https://github.com/davisking/dlib/pull/1040. So I was success to install compile dlib and install in my ubuntu. Now is how to use dlib in django. I tried "import dlib" but its not recognized. This is how I install dlib and last part of the execution. $ python setup.py install ..... ..... Processing dlib-19.8.99-py2.7-linux-x86_64.egg creating /usr/local/lib/python2.7/dist-packages/dlib-19.8.99-py2.7-linux-x86_64.egg Extracting dlib-19.8.99-py2.7-linux-x86_64.egg to /usr/local/lib/python2.7/dist-packages Adding dlib 19.8.99 to easy-install.pth file Installed /usr/local/lib/python2.7/dist-packages/dlib-19.8.99-py2.7-linux-x86_64.egg Processing dependencies for dlib==19.8.99 Finished processing dependencies for dlib==19.8.99 settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... 'mapwidgets', 'dlib', ] but it came out with errors below. removing this it still does not recognize "import dlib" Traceback (most recent call last): File "manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File … -
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?